Help with my code on Rock, Paper, Scissors?


#1

https://www.codecademy.com/courses/learn-javascript-functions/projects/rock-paper-scissors?course_redirect=introduction-to-javascript

Hey all, so in my code below, I decided to think outside the box with my code for “determineWinner”. If the game isn’t a tie, I keep getting undefined when it logs “determineWinner”. When it’s a tie, it logs everything correctly including who the winner is, but any other variation and it returns undefined for the winner. My determineWinner function seems to the issue. Any ideas? Is the way I coded it just not right?


const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  switch (userInput) {
    case 'rock':
      	return 'rock';
      	break;
      // checks if user chose rock
    case 'paper':
      	return 'paper';
      	break;
      // checks if user chose paper
    case 'scissors':
      	return 'scissors';
      	break;
      // checks if user chose scissors
    default:
      console.log('Error 404');
      break;
      // error message if user enters invalid input
  }
}
const getComputerChoice = () => {
 let randomNumber = Math.floor(Math.random() * 3);
 switch (randomNumber){
   case 0:
   		return 'rock';
   case 1:
      return 'paper';
   case 2:
     	return 'scissors';
 } 
};

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice){
     return 'The game is a tie!';
  }
  
  switch (determineWinner) {
    case userChoice === 'rock' && computerChoice === 'paper':
      return 'The computer wins!';
    case userChoice === 'rock' && computerChoice === 'scissors':
      return 'You win!';
    case userChoice === 'paper' && computerChoice === 'rock':
      return 'You win!';
    case userChoice === 'paper' && computerChoice === 'scissors':
      return 'The computer wins!';
    case userChoice === 'scissors' && computerChoice === 'rock':
      return 'The computer wins!';
    case (userChoice === 'scissors' && computerChoice === 'paper'):
      return 'You win!';
  } 
}

const playGame = () => {
	const userChoice = getUserChoice('paper');
  const computerChoice = getComputerChoice();
  console.log(`You chose ${userChoice}.`);
  console.log(`The computer chose ${computerChoice}.`);
  console.log(determineWinner(userChoice, computerChoice));
}
playGame();

#2

You can’t use a switch statement here.

we have two variables of which we need to check the value (userChoice and computerChoice). A switch statement only does us any good if we have one variable which we want to compare with different cases.


#3

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