I am currently done with this little Rock, Paper, Scissors, Lizard, Spock game in JavaScript. The game is working fine, but I am not pleased with the code. Is there a way to refactor these if
statements? I was thinking about ternary operators and I tried doing so but failed. This is basically my function based on which I get the results.
function result(userChoice, cpuChoice) {
var result = '';
if(userChoice == 'rock' ) {
if (cpuChoice == 'rock') {
result = 'Tie';
ties++;
} else if ( cpuChoice == 'spock') {
result = 'Spock vaporizes rock';
loses++;
} else if ( cpuChoice == 'lizard' ) {
result = 'Rock crushes lizard';
wins++;
} else if ( cpuChoice == 'paper' ) {
result = 'Paper covers rock';
loses++;
} else if ( cpuChoice == 'scissors' ) {
result = 'Rock crushes scissors';
wins++;
};
} else if(userChoice == 'paper') {
if (cpuChoice == 'paper') {
result = 'Tie';
ties++;
} else if ( cpuChoice == 'spock') {
result = 'Paper disproves Spock';
wins++;
} else if ( cpuChoice == 'lizard' ) {
result = 'Lizard eats paper';
loses++;
} else if ( cpuChoice == 'rock' ) {
result = 'Paper covers rock';
wins++;
} else if ( cpuChoice == 'scissors' ) {
result = 'Scissors cuts paper';
loses++;
};
} else if(userChoice == 'scissors') {
if (cpuChoice == 'scissors') {
result = 'Tie';
ties++;
} else if ( cpuChoice == 'spock') {
result = 'Spock distroys scissors';
loses++;
} else if ( cpuChoice == 'lizard' ) {
result = 'Scissors beheads lizard';
wins++;
} else if ( cpuChoice == 'rock' ) {
result = 'Rock crushes scissors';
loses++;
} else if ( cpuChoice == 'paper' ) {
result = 'Scissors cuts paper';
wins++;
};
} else if(userChoice == 'lizard') {
if (cpuChoice == 'lizard') {
result = 'Tie';
ties++;
} else if ( cpuChoice == 'spock') {
result = 'Lizard poisons Spock';
wins++;
} else if ( cpuChoice == 'scissors' ) {
result = 'Scissors beheads lizard' ;
loses++;
} else if ( cpuChoice == 'rock' ) {
result = 'Rock crushes lizard';
loses++;
} else if ( cpuChoice == 'paper' ) {
result = 'Lizard eats paper';
wins++;
};
} else if(userChoice == 'spock') {
if (cpuChoice == 'spock') {
result = 'Tie';
ties++;
} else if ( cpuChoice == 'lizard') {
result = 'Lizard poisons Spock';
loses++;
} else if ( cpuChoice == 'scissors' ) {
result = 'Spock distroys scissors';
wins++;
} else if ( cpuChoice == 'rock' ) {
result = 'Spock vaporizes rock';
wins++;
} else if ( cpuChoice == 'paper' ) {
result = 'Paper disproves Spock';
loses++;
};
} else {
return false;
};
return result;
};