Skip to content

Instantly share code, notes, and snippets.

@ralgh
Forked from joehinkle/RPS.js
Last active December 22, 2015 00:59
Show Gist options
  • Select an option

  • Save ralgh/6393681 to your computer and use it in GitHub Desktop.

Select an option

Save ralgh/6393681 to your computer and use it in GitHub Desktop.
var
choices = ['rock','paper','scissors'], // Classic version
// choices = ['cockroach','foot','nuke'], // Foot crushes cockroach, nuke blows up foot, cockroach survives nuke.
// choices = ['rock','paper','scissors','spock','lizard'], // Rock-Paper-Scissor-Spock-Lizard version
choicesCount = choices.length,
promptString = (function(choices){
var string = '',
c = choicesCount - 1;
for (var i = 0; i <= c; i++) {
string += (i === 0) ? capitalize(choices[i]) : choices[i];
string += (i === (c - 1)) ? ' or ' : (i != c) ? ', ' : '';
}
return string + '?';
})(choices),
gamesCount = prompt('Best of?', 3) * 1 || 1,
humanChoiceIndex = -1,
computerChoiceIndex = -1;
for (var i = gamesCount - 1; i >= 0; i--) {
while (choices[humanChoiceIndex] === undefined) {
humanChoiceIndex = choices.indexOf(prompt(promptString).toLowerCase());
if (choices[humanChoiceIndex] === undefined) {
alert('Not a valid choice. Try again.');
}
}
computerChoiceIndex = Math.floor(Math.random() * choicesCount);
document.write('<div>' + compare( choices[humanChoiceIndex], choices[computerChoiceIndex] ) + '</div>');
humanChoiceIndex = -1;
computerChoiceIndex = -1;
}
function compare( humanChoice, computerChoice ) {
var humanChoiceIndex = choices.indexOf(humanChoice),
computerChoiceIndex = choices.indexOf(computerChoice),
// I wish I could take credit for this logic:
// http://stackoverflow.com/questions/9553058/scalable-solution-for-rock-paper-scissor#9553712
winner = (choicesCount + humanChoiceIndex - computerChoiceIndex) % choicesCount;
if (winner){
return (winner % 2) ?
'You Win! <b>' + capitalize(humanChoice) + '</b> beats ' + computerChoice + '.'
:
'Computer Wins! ' + capitalize(computerChoice) + ' beats <b>' + humanChoice + '</b>.';
}
else{
return 'Tie. <b>' + capitalize(humanChoice) + '</b> equals ' + computerChoice + '.';
}
}
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment