Rock - Paper - Scissors question

Hi everyone,

Can I use swicht to write this part of the code?

function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return “Tied game!”;
} else if (
(userChoice === “rock” && computerChoice === “paper”) ||
(userChoice === “paper” && computerChoice === “scissors”) ||
(userChoice === “scissors” && computerChoice === “rock”)
) {
return “Computer won!”;
} else if (userChoice === undefined) {
return “Not a valid object”
}
else {
return “User won!”;
}
}

Not easily.
You use could nested switch blocks, one for userChoice and one for computerChoice.

function determineWinner(userChoice, computerChoice) {
  switch(userChoice) {
    case "rock": 
      switch(computerChoice) {
         case "rock":
           return "Tied game!";
         case "paper":
           return "Computer won!";
         case "scissors":
           return "User won!";
      }
    case "paper":
      switch(computerChoice) {
         case "rock":
           return "User won!";
         case "paper":
           return "Tied game!";
         case "scissors":
           return "Computer won!";    
      }
    case "scissors":
      switch(computerChoice) {
         case "rock":
           return "Computer won!";
         case "paper":
           return "User won!";
         case "scissors":
           return "Tied game!";    
      }
    default:
      return "invalid choice";
  } // end of switch(userChoice)
}

Or something unusual using switch(true)

function determineWinner(userChoice, computerChoice) {
  switch(true) {
     case (userChoice === computerChoice):
       return "Tied game!";
     case (userChoice === "rock" && computerChoice === "paper"):
     case (userChoice === "paper" && computerChoice === "scissors"):
     case (userChoice === "scissors" && computerChoice === "rock"):
       return "Computer won!"
     case (userChoice == undefined):
       return "Not a valid choice!";
     default:
       return "User won!";
  } // end of switch
}

I didn’t need to put break because the return already exits the switch-block.

So, in this case is better to use the ‘if’ conditional?

Yes. An if-conditional is better here.

1 Like