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!
Written by Mateusz Gachowski
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Paper
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#