Skip to content

Instantly share code, notes, and snippets.

@mteece
Forked from joehinkle/RPS.js
Last active December 21, 2015 21:19
Show Gist options
  • Save mteece/6367538 to your computer and use it in GitHub Desktop.
Save mteece/6367538 to your computer and use it in GitHub Desktop.
Making game and objects configurable for rock, paper, scissors, lizard, spock. See http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock.
// Initializing Variables
var userChoice = prompt("Do you choose rock, paper, scissors, lizard, or spock?");
var choices = ["rock", "paper", "scissors", "lizard", "spock"];
var computerChoice = choices[ Math.floor( Math.random() * choices.length ) ];
// Function that compares the two values
function compare( choice1, choice2 ) {
var rock = {
defeats: ["scissors", "lizard"],
loses: ["paper", "spock"],
name: ["rock"]
};
var paper = {
defeats: ["rock", "spock"],
loses: ["scissors", "lizard"],
name: ["paper"]
};
var scissors = {
defeats: ["paper", "lizard"],
loses: ["rock", "spock"],
name: ["scissors"]
};
var lizard = {
defeats: ["paper","spock"],
loses: ["rock", "scissors"],
name: ["lizard"]
};
var spock = {
defeats: ["scissors", "rock"],
loses: ["lizard", "paper"],
name: ["spock"]
};
var perms = [rock, paper, scissors, lizard, spock];
var plen = perms.length;
for(i=0; i<plen; i++) {
var obj = perms[i];
if(obj.name[0] === choice1) {
for(y=0; y<2; y++){
switch(choice2) {
case obj.defeats[y]:
return obj.name + " defeats " + obj.defeats[y];
break;
case obj.loses[y]:
return obj.name + " loses to " + obj.loses[y];
break;
case obj.name[y]:
return obj.name + " ties " + obj.name[y];
break;
}
}
// Stop looping as soon as possible.
break;
}
}
}
document.write("<div>User selects: " + userChoice + "</div>");
document.write("<div>Computer selects: " + computerChoice + "</div>");
document.write("<div>Results are: " + compare(userChoice, computerChoice) + "</div>");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment