How to extend the function in rock, paper, scissors game


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-Bthev-mskY8/1/5?curriculum_id=506324b3a7dffd00020bf661


How do I get the code to run again after an incorrect response is given by the user? For example, if the user inputs cat, I added in an else statement to prompt the user for a valid response. But after this the code doesn't repeat so whatever second response the user inputs doesn't matter and the game ends.


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  {
        prompt("Your choice is invalid, please choose rock, paper, or scissors") ;
    }
    
} 

compare(userChoice, computerChoice)


#2

This here below is how I did mine. Which might be right. It returns the statement rather than prompt and the game ends. It does not claim a winner. But, it does still allow the computer to make a choice. Its the first time i have seen this question asked. That means some of us are going over and beyond. maybe scheduling a MeetUp about to finish this bit of code is in order..Anyway here...

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 !== "rock" || choice1 !== "paper" || choice1 !== "scissors") {
return "Please enter valid choice 'rock, paper or scissors'"
}
};

Cheers.


#3

If you check the Corner Bar, you may find others who have worked on this game past paper, rock, scissors as choices. :slight_smile:

https://discuss.codecademy.com/c/Codecademy-Community-Lounge/Corner-Bar


#4

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