Rock, Paper, or Scissors - Javascript

Hello, I write this following the instruction, but when I run, it runs the tie case two times. Like userInput is ‘rock’ and computerChoice = ‘rock’, it should stop at log to the console ‘This game is tie’, but it runs to another if and log ‘You won!’.

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === ‘rock’ || userInput === ‘paper’ || userInput === ‘scissors’) {
return userInput;
} else {
console.log(‘Error!!!’)
}
}

// console.log(getUserChoice(‘rock’));
// console.log(getUserChoice(‘pork’));

var computerchoice;
function getComputerChoice() {
computerchoice = Math.floor(Math.random() * 3);
switch (computerchoice) {
case 0:
return ‘rock’;
break;
case 1:
return ‘paper’;
break;
case 2:
return ‘scissors’;
break;
}
}

// console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
console.log(‘This game is tie.’);
}
if (userChoice === ‘rock’) {
if (computerChoice === ‘paper’) {
return ‘The computer won’;
} else {
return ‘You won!’;
}
}
if (userChoice === ‘paper’) {
if (computerChoice === ‘scissors’) {
return ‘The computer won’;
} else {
return ‘You won!’;
}
}
if (userChoice === ‘scissors’) {
if (computerChoice === ‘paper’) {
return ‘The computer won’;
} else {
return ‘You won!’;
}
}
if (userChoice === ‘bomb’) {
return ‘You won!’;
}
}

/* Test determineWinner function */
console.log(determineWinner(‘paper’, ‘scissors’)); // prints something like ‘The computer won!’
console.log(determineWinner(‘paper’, ‘paper’)); // prints something like ‘This game is a tie!’
console.log(determineWinner(‘paper’, ‘rock’)); // prints something like ‘You won!’
console.log(determineWinner(‘bomb’, ‘rock’));

// function playGame() {
// const userChoice = getUserChoice(‘rock’);
// const computerChoice = getComputerChoice();
// console.log('You threw: ’ + userChoice);
// console.log(‘The computer threw:’ + computerChoice);
// console.log(determineWinner(userChoice, computerChoice));
// }

// playGame();

Hate to be the one to say this, buckle up and bear down. Start debugging! Point out the things you have questions about and we can guide you.

you may need to make some of your if statements into else if statements.
like here:

if (userChoice === 'rock') {

and in several other places.

The way you have the code now, even if the userChoice and if computerChoice are the same,
it keeps checking for a winner after checking if those are equal.

2 Likes