Skip to content

Instantly share code, notes, and snippets.

@jdkeith
Forked from joehinkle/RPS.js
Last active December 21, 2015 21:39
Show Gist options
  • Save jdkeith/6370088 to your computer and use it in GitHub Desktop.
Save jdkeith/6370088 to your computer and use it in GitHub Desktop.
// Initializing Variables
function RPSLS()
{
var choices = [
{
name: "rock",
beats: {
"scissors": "crushes",
"lizard": "crushes"
}
},
{
name: "paper",
beats: {
"spock": "disproves",
"rock": "covers"
}
},
{
name: "scissors",
beats: {
"paper": "cuts",
"lizard": "decapitates"
}
},
{
name: "lizard",
beats: {
"spock": "poisons",
"paper": "eats"
}
},
{
name: "spock",
beats: {
"scissors": "smashes",
"rock": "vaporizes"
}
}
];
function play()
{
var cpuChoice = choices[ Math.floor( Math.random() * choices.length ) ];
var i;
var details;
var userChoice = prompt("Do you choose rock, paper or scissors, lizard, or spock?");
while( true )
{
for(i=0; i<choices.length; i++ ) {
if( choices[i].name === userChoice ) {
userChoice = choices[i];
break;
}
}
// it's not a string
if( userChoice.name ) {
break;
}
userChoice = prompt("You did not select rock, paper, scissors, lizard, or spock. Please try again.");
}
if( cpuChoice == userChoice ) {
return "The result is a tie!";
}
details = {
youPicked: userChoice.name,
cpuPicked: cpuChoice.name,
how: cpuChoice.beats[userChoice.name],
cpuWins: true
};
if( ! details.how ) {
details.how = userChoice.beats[cpuChoice.name];
details.cpuWins = false;
}
return "You picked " + details.youPicked + ". " +
"Computer picked " + details.cpuPicked + ". " +
(details.cpuWins ? details.cpuPicked : details.youPicked ) + " " +
details.how + " " +
(details.cpuWins ? details.youPicked : details.cpuPicked) + ". " +
"You " + (details.cpuWins ? "lose" : "win") + ".";
}
return { play: play };
}
// not including the prompt stuff
// to play a new game
var rpsls = new RPSLS();
rpsls.play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment