Last Updated: December 27, 2021
·
1.448K
· mateuszgachowski

A simple "Paper, Scissors, Rock" game in few lines

Lets prepare some data and functions to be used later:

var outcomes = ['rock', 'scissors', 'paper'];

// Creates random outcome
var randomOutcome = function () {
  return outcomes[Math.floor(Math.random() * outcomes.length)];
};

// Init prompter (ask user for answer)
var prompter = function () {
    var answer = prompt('Select your outcome (paper, scissors, rock)');
    return (outcomes.indexOf(answer) !== -1) ? answer : prompter();
};

Ok, now we have almost everything we need. We can now fire the prompter:

// Get user answer
var userChoice = prompter();

Ok, we have the user answer... Lets ask the computer:

// Generate computers answer
var computerChoice = randomOutcome();

Great. Thats all we need. Now teh magic.

var userChoiceIndex = outcomes.indexOf(userChoice);
var computerChoiceIndex = outcomes.indexOf(computerChoice);

console.log('Your choice: '+ userChoice);
console.log('Computer choice: ' + computerChoice);

if (userChoiceIndex === computerChoiceIndex) {
    console.log('Draw');
}
else if (outcomes.splice(userChoiceIndex - 1, 1)[0] === computerChoice) {
    console.log('Computer wins')    
}
else {
    console.log('You win');
}

The hard part here is this line:

(outcomes.splice(userChoiceIndex - 1, 1)[0] === computerChoice)

What it accually do is take the element before users answer and compare it to the computers choice. If it's the last element of the array, it takes the first element and so on.
Rock wins scissors, scissors wins paper and paper covers rock which wins scissors etc.

Thats all!

Related protips