Thu. Dec 5th, 2019

Coding Is Future

Read the best technology articles

JavaScript Rock Paper Scissors Game Making

1 min read

It’s a game that most of us know. We put our hands in the shape of rock, paper, scissors and try to outmaneuver one of us. The loser has to pay the penalty which determined at the beginning of the game.

Now let’s explain the rule of the game a little.

Paper is superior to rock.

Rock is superior to scissors.

Scissors are superior to paper.

Now starting from this hierarchy I have prepared a rock-paper-scissors game in javascript. You can examine the codes.

Let me explain a little bit about the game. When you click on one of the pictures of paper, scissors, rock; at the same time, the computer also makes a choice. The selection is evaluated according to the above conditions. As a result, the winner is determined. Clicking the pictures again will restart the game.

You will also need to add the shared images below to the application folder.

<!doctype html>
<html>
<head>
<title>Rock Paper Scissors Game</title>
<meta charset="utf-8">
<style>
body{
background: #e74c3c;
}
#list img{
padding:5px;
border:1px #232333 solid;

}
#result{
float:left;
width: 260px;
height: 260px;
font-size:2em;
padding:20px;
background: #f1c40f;

}
#pc-result{
float:left;

}

</style>
</head>
<body>

<div id="list">
<img src="paper.png" id="paper" width="300" height="300" data-id="0">
<img src="scissors.png" id="scissors" width="300" height="300" data-id="1">
<img src="rock.png" id="rock" width="300" height="300" data-id="2">
</div> 
<div id="pc-result">
<img src="" id="pc-choice" width="300" height="300" alt="pc choice">
</div>
<div id="result">

</div>

<script>
var list=["paper.png","scissors.png","rock.png"];
var paper=document.getElementById("paper");
var scissors=document.getElementById("scissors");
var rock=document.getElementById("rock");
var pcChoice=document.getElementById("pc-choice");
var printResult=document.getElementById("result");


paper.onclick=makeChoice;
scissors.onclick=makeChoice;
rock.onclick=makeChoice;


function makeChoice(){
var pc= RandomPaper();


var choice= this.dataset.id;
if(pc==0 && choice==0)
{
result="You both made the same choice.";
}
else if(pc==0 && choice==1)
{
result="You won.";
}
else if(pc==0 && choice==2)
{
result="You lost.";
}
else if(pc==1 && choice==0)
{
result="You lost.";
}
else if(pc==1 && choice==1)
{
result="You both made the same choice.";
}
else if(pc==1 && choice==2)
{
result="You won.";
}
else if(pc==2 && choice==0)
{
result="You won.";
}
else if(pc==2 && choice==1)
{
result="You lost.";
}
else if(pc==2 && choice==2)
{
result="You both made the same choice.";
}

printResult.innerHTML=result;
}

function RandomPaper(){
var number= Math.round(Math.random()*2);
pcChoice.src=list[number]; 

return number;
}

</script>
</body>
</html>

1 thought on “JavaScript Rock Paper Scissors Game Making

Leave a Reply

%d bloggers like this: