I have made a simple Rock Paper Scissors game that can be played in the console. It uses a series of if/else if statements to compare the inputs by the user against the computers selections and outputs a winner based on this. My issue is that the code is a bit long and repetitive so I’m not sure if there is a way to possibly make it more compact.
This is my code at the moment:
function start(computerSelection, playerSelection){
if (computerSelection === playerSelection){
return "It's a tie!"
}
else if (computerSelection === "rock" && playerSelection === "paper"){
playerScore += 1;
return "You win!";
}
else if (computerSelection === "rock" && playerSelection === "scissors"){
computerScore += 1;
return "Computer wins!";
}
else if (computerSelection === "paper" && playerSelection === "rock"){
computerScore += 1;
return "Computer wins!";
}
else if (computerSelection === "paper" && playerSelection === "scissors"){
playerScore += 1;
return "You win!";
}
else if (computerSelection === "scissors" && playerSelection === "paper"){
computerScore += 1;
return "Computer wins!";
}
else if (computerSelection === "scissors" && playerSelection === "rock"){
playerScore += 1;
return "You win!";
}
else{
return "Invalid entry!"
}
}
This is not all the code for the game, just the section that I’m looking to shorten.
9
Answers
you can use a data driven system:
Firstly you don’t need to do this kind of if/else logic when returning in each block:
That can be written as just
Secondly, if you want to use a switch statement, as you’re not just checking a single value, you could try:
Thirdly, in your function you increment
playerScore
andcomputerScore
, but they’re not initialised anywhere, and you don’t use them anywhere. So I removed them from my answer.Very quickly, without switch/case and without making too many changes to your original code:
In my opinion, you don’t need any
else
statement here and you can summarize conditions with the same outcome.This is shorter
You can use
switch case
to write those statments,it will look like this:Something like this?
You can also add this:
A simplified version of the above code.
You actually only need to determine who wins. Here is one idea to do that.
See also …
you can make like this: