Skip to content

Instantly share code, notes, and snippets.

@cipto-hd
Last active August 29, 2015 14:02
Show Gist options
  • Save cipto-hd/fc88f00fb2b9700b92a2 to your computer and use it in GitHub Desktop.
Save cipto-hd/fc88f00fb2b9700b92a2 to your computer and use it in GitHub Desktop.
Rock, Paper, Scissors choice game, Code Academy course js exercise
var userChoice;
var getUserChoice = function(){
var userChoice = prompt("Choose rock, paper, scissors!");
if((userChoice != null) && !(userChoice==="rock" || userChoice==="paper" || userChoice==="scissors" )) {getUserChoice();}
return userChoice;
};
userChoice = getUserChoice();
if(userChoice === null) console.log("Cancel play the game");
else {
var computerChoice = Math.random(); userChoice
if (computerChoice < 0.34) { computerChoice = "rock"; }
else if(computerChoice <= 0.67) { computerChoice = "paper"; }
else { computerChoice = "scissors"; }
console.log("Computer: " + computerChoice);
console.log("You: " + userChoice);
var compare = function(choice1,choice2){
if(choice1 === choice2) return "tie";
else if(choice1==="rock"){
if(choice2==="scissors") return "rock";
else return "paper";
}else if(choice1==="paper"){
if(choice2==="rock") return "paper";
else return "scissors"; }
else{
if(choice2==="rock") return "rock";
else return "scissors"; }
}
var result = compare(userChoice,computerChoice);
if(result=="tie") message = "The result is tie!"
else{
if(result==userChoice) winner = "You";
else winner = "Computer"
message = "The winner is " + winner;
}
console.log(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment