Reputation:
I just finished making a rps game on codecademy, and there are some extra tasks that include making an outcome if the user inputs wrong info. Basically, if you don't write an input of "rock", "paper" or "scissors" it will ask you again until you put in the right one.
How can i call userChoice variable until it gets the right answer. I tried it like this, but it just asks 2 times and then posts whatever you write.
var userChoice = prompt("Do you choose rock, paper or scissors?");
if (userChoice != "rock", "paper", "scissors") {
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";
}
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";
}
}
}
console.log("Human: " + userChoice);
console.log("Computer: " + computerChoice);
compare(userChoice, computerChoice);
Upvotes: 0
Views: 277
Reputation: 27
Use the following
do {
userChoice = prompt("Do you choose rock, paper or scissors?");
} while (userChoice != "rock", "paper", "scissors")
Upvotes: 0
Reputation: 1409
Use a function that references itself:
var userChoice = function () {
var choice = prompt("Do you choose rock, paper or scissors?");
if (choice !== "rock" && choice !== "paper" && choice !== "scissors") {
return userChoice();
} else {
return choice;
}
};
This fiddle has the whole thing working.
Upvotes: 1