Programming, Music, Games. Creation.

Rock, Paper, Scissors – Simple Java Game

rps



//coded by Bermuda
//imnotbermuda.com

/*global variables*/
var userChoice;
var computerChoice;
var result;

/*compare() - returning 0 here will result in rematch*/
var compare = function(choice1,choice2){

if(choice1===choice2){
console.log("Tie! Rematch!");
return 0;//rematch when it was a draw
}

if(choice1==="rock"){
if(choice2=="scissors"){
return "rock wins";
}else{
return "paper wins";
}
}

if(choice1==="paper"){
if(choice2=="rock"){
return"paper wins";
}else{
return"scissors wins";
}
}

if(choice1==="scissors"){
if(choice2=="rock"){
return"rock wins";
}else{
return"scissors wins";
}
}

console.log("rock, paper or scissors only!")
return 0;//rematch for invalid input
}

/*play() - the trigger!*/
var play = function(){

userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice = Math.random();//random number between 0 and 1
if (computerChoice < 0.34) {//giving (at least trying :P) to give fair chances to rps
computerChoice = "rock";
} else if(computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}

console.log("Computer Choice : " + computerChoice)
console.log("Your Choice : " + userChoice)

result = compare(userChoice,computerChoice)// compare value returned to result, used to determine next step
console.log(result)

if(result===0) {
play()//play function again if result = 0
} else {
var playagain=0//declare variable playagain
playagain = prompt("Type 1 to play again. Simply press Enter to exit!")
if (playagain==="1"){
play()
}
}

}

play()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s