# Rock Paper Scissors Game using if statements

I am doing the codecademy course and had to do a rock paper scissors game as a project. Rather than following the instructions I tried Doing it on my own. How I could make the code more efficient?

//Only outputs 1-3
const COMPUTERCHOICE = (min=1, max=4) => {
return Math.floor(Math.random() * (max - min) + min); };

//Establishes a relation between the numbers and items
console.log('1 = Scissors, 2 = Paper, 3 = Rock\n')

function game(userChoice, computer) {

if (userChoice === 3 && computer === 1){
return User chose ${userChoice}, Computer chose${computer}, user Wins!
}else if (computer === 3 && userChoice === 1){
return User chose ${userChoice}, computer chose${computer}, Computer Wins!
}else if (userChoice < computer){
return Player chose ${userChoice}, Computer Chose${computer} User Wins! :D;
} else if (userChoice === computer) {
return It's a draw!
}else {
return Player chose ${userChoice}, Computer Chose${computer} Computer wins :(;
};
}

console.log(game(3, COMPUTERCHOICE()))

• I like to make a whatBeatsWhat mapping for this scenario. player1 wins if whatBeatsWhat[p1Choice] === p2Choice. player2 wins if whatBeatsWhat[p2Choice] === p1Choice. Otherwise, it's a tie. I find this to be a simple, readable solution. Nov 2, 2021 at 21:35

The best way to improve this would be to somehow use a switch statement in the game logic rather than an excessive if-else chain. The return statements would replace your break statements.

Another small tip would be to use a more descriptive function name like checkChoice over game. Think about writing code for humans first and computer second. Believe that in a professional environment someone else will eventually look at and maintain your code, and the best way to help them do their job is to make nothing ambiguous.

Finally, reference and use a JavaScript style guide, like Google's.

• How should this code be changed to switch statements? Do you mean something like switch (true) { case userChoice === 3 && computer === 1: ... }? Could you show the refactored code?
– tsh
Oct 30, 2021 at 4:09
• There are several options, which is why one specific solution is not showcased. This question is also asked in an academic context, so it's best for the student to think and implement rather than copy-paste code that could potentially have bugs.
– T145
Oct 30, 2021 at 7:25

If you just return (userChoice % 3 - computer % 3 + 3) % 3 on valid inputs;

• In case of tie, you always get 0

• (0 - 0 + 3) % 3
• (1 - 1 + 3) % 3
• (2 - 2 + 3) % 3
• In case userChoice loses, you always get 1

• (1 - 0 + 3) % 3
• (2 - 1 + 3) % 3
• (0 - 2 + 3) % 3
• In case userChoice wins, you always get 2

• (1 - 2 + 3) % 3
• (2 - 0 + 3) % 3
• (0 - 1 + 3) % 3

You can use the returned value (0, 1, 2) to determine which messages to print. You can also use the similar logic on other types of inputs (such as String), since 'p' < 'r' < 's'.