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!