Why? everything is "rock wins"


#1


I am stuck at the last exercise, 9. next steps.


For some reason, when I play this the answer that comes out is ALWAYS going to be rock wins.
Is this a glitch or is something wrong in my code? I tried tweaking it a bit, but it still doesn't change at all.


var getChoices = function() {
    var userChoice = prompt("Do you choose rock, paper or scissors?");
    if (userChoice === "rock" || userChoice === "paper" || userChoice === "scissors") {
        var computerChoice = Math.random();
        if (computerChoice < 0.34) {
            computerChoice = "rock";
        } else if(computerChoice <= 0.67) {
            computerChoice = "paper";
        } else {
            computerChoice = "scissors";
        } 
        console.log("Computer: " + computerChoice);
        console.log("Player: " + userChoice); 
    } else {
        getChoices();
    }

};


var compare = function(choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!";
    } else if (choice1 === "rock") {
        if (choice2 === "scissors") {
            return "rock wins";
        } else {
            return "paper wins";
        }
    } else if (choice1 === "scissors") {
        if (choice2 === "paper") {
            return "scissors wins";
        } else {
            return "rock wins";
        }
    } else if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        } else {
            return "scissors wins";
        }
    } else {
        return "this is a glitch";
    }
};
getChoices();
console.log(compare(userChoice, computerChoice));
console.log(compare(userChoice, computerChoice));
compare(userChoice, computerChoice);


#2

i run your code i get:

Computer: paper
Player: rock
ReferenceError: userChoice is not defined

the problem is that userChoice and computerChoice have a local variable scope, they only exist within the getChoices function


#3

thank you. I fixed it by declaring the variables in the beginning, and deleting the "var" inside the functions.


#4

that is a possibility, creating global variable and then updating the global variable in the function.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.