Step 9 Help


#1

Hello,

So for Step 9, I figured out how to do #1, I'm skipping #2, and I'm trying to work on #3. When there's a tie, how do I start the game over again? At first, I thought I could add code inside the if/else function that says choice 1 === choice 2. In there, I put a prompt to ask for the user's choice. However, when I tested it until I got a tie, a prompt never appeared.

Another problem I wanted to figure out is if I prompt the user, I would need the computer to generate a new choice as well. My original thought was to paste the code from the beginning within this function, but that seems inefficient.

Any suggestions or help? Here's my code, with the section highlighted.

var userChoice = prompt("Do you choose rock, paper or scissors?");

if (userChoice === "rock") {
console.log("You: " + "rock");
}
else if (userChoice === "paper") {
console.log("You: " + "paper");
}
else if (userChoice === "scissors") {
console.log("You: " + "scissors");
}
else {
confirm(userChoice + " is not a valid answer");
var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log("You: " + userChoice);
}

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!";**
** var userChoice = prompt("Do you choose rock, paper or scissors?");**
}
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";
}
}
};

compare(userChoice, computerChoice);

#2

If it is a tie you need to:

  1. inform the user that it's a tie;
  2. ask user for the choice and save input in the userChoice variable;
  3. assign new random value to the computerChoice and later change this value to "rock", "paper" or "scissors";
  4. execute compare function with new values (use console.log around the function call to print the result to the console).

Another problem I wanted to figure out is if I prompt the user, I would need the computer to generate a new choice as well. My original thought was to paste the code from the beginning within this function, but that seems inefficient.

Exactly. To fulfill steps 2 & 3 you just need to copy the code from the beginning. That's against the DRY (don't repeat yourself) principle. What is the solution? Create a function that asks the user for the input and generates the new choice for computer. You should call this function in the beginning and here.


#3

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