So I was extending the rock/paper/scissors JS game from Codecademy to validate user input, but I can't get the program to keep on asking for the right user input when the user inserts something other than 'rock', 'paper' or 'scissors'.
var userChoice;
userChoice = prompt('Do you choose rock, paper, or scissors?');
console.log('User choice: ' + userChoice);
if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors') {
userChoice = prompt('Select again.');
} else if (userChoice === computerChoice) {
userChoice = prompt('It\'s a tie! Pick again.');
console.log('New user choice: ' + userChoice);
}
//computer random choice
var computerChoice = Math.random();
console.log('Computer random number: ' + computerChoice);
// assign rock, paper, scissors values
if (computerChoice <= 0.33) {
computerChoice = 'rock';
} else if (computerChoice <= 0.67) {
computerChoice = 'paper';
} else {
computerChoice = 'scissors';
}
console.log('Computer choice: ' + computerChoice);
// compare user and computer choices
var compare = function(choice1, choice2) {
if (choice1 === 'rock') {
if (choice2 === 'scissors') {
return 'Rock wins!';
} else {
return 'Paper wins!';
}
} else if (choice1 === 'scissors') {
if (choice2 === 'rock') {
return 'Rock wins!';
} else {
return 'Scissors win!';
}
} else if (choice1 === 'paper') {
if (choice2 === 'rock') {
return 'Paper wins!';
} else {
return 'Scissors win!';
}
}
};
console.log(compare(userChoice, computerChoice));
This works fine the first time the user enters something like 'r' to the prompt, but if the input is something wrong the second time, it doesn't work and the console logs undefined
on the last line console.log(compare(userChoice, computerChoice));
How do I get it to keep on asking for the valid input? Thanks in advance guys!
You have a few issues with your code. To solve the first problem you can do this:
however, you still have an issue with the second part:
This code will never fire because you calculate
computerChoice
AFTER making the comparison. You should move this code into yourcompare
function:Problem is, you are missing the
return
statement in the functioncompare()
:Using loop can help here. Possibly do..while loop.
After you run
userChoice = prompt('Select again.');
, you just continue on to complete the rest of the code execution. What you need is some kind of looping condition that checks if they have entered valid input and lets the code continue only once it is valid. (hint: "while" loops)Try out the following: