[Solved] "Rock, Scissors, Paper" game with players giving inappropriate choice


#1

Hello,guy. I just wanted to create a "Rock, Scissors, Paper" game that when the play gives the choice other than "Rock, Scissors, Paper", the console gives respond "Please enter the correct choice." but I kept running into troubles.

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";
} console.log("Computer: " + computerChoice);

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 === "paper") {

if (choice2 === "rock") {
    return "Paper wins";           
} else {
    return "Scissors wins";
}

} else if (choice1 === "scissors") {

if (choice2 === "rock") {
    return "Rock wins";
} else {
    return "Scissors wins";
}

} else if (choice1 !== "scissors","rock","paper") {
if (choice2 === "rock") {
return "Please enter the correct choice.";
} else if (choice2 === "scissors") {
return "Please enter the correct choice.";
} else {
return "Please enter the correct choice.";
}
}
};

compare (choice1, choice2);

Here is my code. Can anyone please help me to point out what I did wrong? Thank you.


#2

The last block

This does not work because of the line

else if (choice1 !== "scissors","rock","paper") {

When you want to compare three strings and check if user input matches at least one of them you have to use the || ( or ) operator between the strings.

In this case we are trying to figure out if the user input is not scissors or rock.

else if ( choice1 !== "scissors" || choice1 !== "rock") {
   do something if the input is not scissors or rock;
} else {
   do something when the input is scissors or rock;
}

But in that way the program will just end and user has to restart the program/game. My way to do this would be with while loop, so it would be a endless loop until user enters a valid input. I am pretty sure at one point you will be teached the while loop in the exercise.


#3

Ahhhhh~ Thank you so much!!
But I haven't got to the "While" session. Hopefully it can solve this problem by then!!
Thanks a lot!! This problem has bothered me for 2 day!! :joy: :joy: :joy: :joy: