Skip to content

Instantly share code, notes, and snippets.

@osgix
Created January 8, 2014 09:35
Show Gist options
  • Save osgix/8314129 to your computer and use it in GitHub Desktop.
Save osgix/8314129 to your computer and use it in GitHub Desktop.
Rock paper scissors game with javascript
var compare = function(userChoice, computerChoice) {
if(userChoice == 'R') {
if(computerChoice == 'S') {
return 1;
}
else if(computerChoice == 'P') {
return 2;
}
else {
return 0;
}
}
else if(userChoice == 'S') {
if(computerChoice == 'P') {
return 1;
}
else if(computerChoice == 'R') {
return 2;
}
else {
return 0;
}
}
else {
if(computerChoice == 'R') {
return 1;
}
else if(computerChoice == 'S') {
return 2;
}
else {
return 0;
}
}
}
var takeComputerChoice = function() {
var random = Math.floor((Math.random()*3)+1);
if(random == 1) {
return 'R';
}
else if(random == 2) {
return 'P';
}
else {
return 'S';
}
}
var takeUserChoice = function() {
var choice = prompt("Rock(R) / Paper(P) / Scissors(S) / Exit(E)");
if(choice == 'R' || choice == 'P' || choice == 'S' || choice == 'E') {
return choice;
}
else {
alert("You must write R or P or S...");
return 'X';
}
}
var rockPaperScissorsGame = function() {
var userChoice = 'O';
var computerChoice = 'O';
while (userChoice != 'E'){
userChoice = takeUserChoice();
if(userChoice != 'X' && userChoice != 'E') {
computerChoice = takeComputerChoice();
var result = compare(userChoice, computerChoice);
if(result == 1) {
alert("User wins...");
}
else if(result == 2) {
alert("Computer wins...");
}
else {
alert("Draw...");
}
}
}
alert("game is over, thank you");
}
rockPaperScissorsGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment