Ok, I'm still a beginner at JavaScript, but I'm trying to write a rock-paper-scissors type game. Everything is working pretty well, except that every time that I run the "reload" function the output is whatever is the first "if" statement of the second if/else statement. By this I mean that the output "Both sides reload." would come back every time if the code were to be arranged how it is below. Also I already know that the randomizer works. Any help will be greatly appreciated. Thanks.
var reload = function() {
var random = function() {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
var compDecision = 1
}
else if (randomizer > 67) {
var compDecision = 2
}
else if (33 < randomizer && randomizer <= 67) {
var compDecision = 3
}}
if (compDecision = 1) {
confirm("Both sides reload.")
}
else if (compDecision = 2) {
confirm("You reload and the enemy takes up defensive positions.")
}
else if (compDecision = 3) {
confirm("The enemy takes you out as you reload.")
}}
1 Answer 1
First of all use = for assignments, and == for logical compare operation.
Then you should declare var compDecision as a empty or default var and then assign to it a value without using var again. I would recommended using semi-colons ; to end your statements, unlike JavaScript, they are not optional for other languages.
Here is your working code, check the differences conclude the solution:
var reload = function () {
var compDecision = 0;
var random2 = function () {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
compDecision = 1;
} else if (randomizer > 67) {
compDecision = 2;
} else {
compDecision = 3;
}
}
random2();
if (compDecision == 1) {
alert("Both sides reload.");
} else if (compDecision == 2) {
alert("You reload and the enemy takes up defensive positions.");
} else if (compDecision == 3) {
alert("The enemy takes you out as you reload.");
}
}
reload();
Tested here : http://jsfiddle.net/urahara/6rtt0w62/
5 Comments
; won't hurt, but not using them properly may lead to problems.. @Spencer Wieczorek any Polish relatives :) ?;) to end your statements, unlike JavaScript, they are not optional for other languages.".if (33 < randomizer && randomizer <= 67) as it has exhausted all other possibilities at that point.
=is an assignment operator, not a comparator; possible duplicate of function doesn't work==or===for comparison not=. And you are using a local variable used in another function. You are placing a function inside another function, I'm doubting you want to do that.random()at all? AlsocompDecisionis a local variable!