Skip to content

Instantly share code, notes, and snippets.

@mateuszgachowski
Created October 10, 2013 11:03
Show Gist options
  • Select an option

  • Save mateuszgachowski/6916668 to your computer and use it in GitHub Desktop.

Select an option

Save mateuszgachowski/6916668 to your computer and use it in GitHub Desktop.
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');
return (outcomes.indexOf(answer) !== -1) ? answer : prompter();
};
// Get user answer
var userChoice = prompter();
// Generate computers answer
var computerChoice = randomOutcome();
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');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment