Cant figure out what is wrong with my code in Rock, Paper, Scissors


#1

So here is my code. But when I get th "Prompt" window up and type in something, the "message" I write in pops up in the console. Not "Rock wins".

If I were to type "Hello this is me talking", it would say " "Hello this is me talking" " in the console.
I did pass the course with this code, so I dont quite understand.

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
    if(computerChoice < 0.34) {
	    computerChoice = "rock";
    }else if(computerChoice <= 0.67) {
	    computerChoice = "paper";
    }else{
	    computerChoice = "scissors";
    
    }

choice1 = computerChoice;
choice2 = userChoice;

var compare = function(choice1, choice2) {
    
    if(choice1 === choice2) {
        return "The result is a tie!";
    } 
    if(choice1 === "Rock") {
        if(choice2 === "Scissors") {
            return ("Rock wins!");
        }else{
            return ("Paper wins!");
        }
    } 
        if(choice1 === "Paper") {
            if(choice2 === "Rock") {
                return ("Paper wins!");
        }else{ 
                return ("Scissors wins!");
        }
    }
    
    if(choice1 === "Scissors") {
        if(choice2 === "Rock") {
            return ("Rock wins!");
        }else{
            return ("Paper wins!");
        }
    }
    
    console.log(compare(choice1,choice2));
}

#2

the function call should be outside the function

the function call executes the function, so then it makes sense to place the function call outside the function


#3

Not quite sure I completely follow you here, Stetim94. I am just getting started with coding, so having some troubles understanding sometimes, heh..


#4

okay, look at this code with comments:

if(choice1 === "Scissors") {
        if(choice2 === "Rock") {
            return ("Rock wins!");
        }else{
            return ("Paper wins!");
        }
    }
    // function call
    console.log(compare(choice1,choice2));
} // this } closes function

see how the function call is inside the function? place it outside the function.

you could consider to remove this lines:

choice1 = computerChoice;
choice2 = userChoice;

and supply userChoice and computerChoice as arguments at your function call rather then choice1 and choice2


#5

Okey, then I understood. Because I tried moving the "console.log(compare(choice1,choice2));" so that it became like the code below. But when I do it like this it give me an syntax error..

...

if(choice1 === "Scissors") {
    if(choice2 === "Rock") {
        return ("Rock wins!");
    }else{
        return ("Paper wins!");
    }
}

} console.log(compare(choice1,choice2));

...


#6

on your function call, why use choice1 and choice2 as arguments?

if you have a syntax error, post an updated version of your code (full code)


#7

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