/
rps.html
75 lines (71 loc) · 2.68 KB
/
rps.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//rock, paper and scissors in array and assign it to options variable
let options = ['rock', 'paper', 'scissors'];
//anonymous function to get a random number between 1-3 and use the random+
//number to get a option from options array.
const computerSelection = function(){
let selected = Math.floor(Math.random()*3)+1;
return options[selected-1];
}
//Main function to check who wins
function playRound(player, computer){
if(options.includes(player)){
if((player === 'rock' && computer === 'scissors')
|| (player === 'paper' && computer === 'rock')
|| (player === 'scissors' && computer === 'paper')){
return 'Player wins';
}else if(player === computer){
return 'Game Tie';
}
else{
return 'Computer wins';
}
}else{
return 'Wrong input';
}
}
//Another function to check who win the match.
function winner(playerWin, computerWin){
if(playerWin > computerWin){
return 'Player Wins';
}else if(computerWin > playerWin){
return 'Computer Wins';
}else{
return 'Match Tie';
}
}
//This is the function which loops five times and calculate wins and finally display the winning message.
function game(){
let i=1;
let playerWin = 0, computerWin = 0;
while(i<=5){
let playerSelection = prompt('Select Rock or Paper or Scissors ?');
let result = playRound(playerSelection, computerSelection());
alert(result);
if(result === 'Player wins'){
playerWin += 1;
}else if(result === 'Computer wins'){
computerWin += 1;
}else if(result === 'Wrong input'){
i -= 1;
}
i += 1;
}
alert('Number of match: '+(i-1)+'\nPlayer won '+playerWin+' times'+
'\nComputer won '+computerWin+' times\n Match Tie '+((i-1)-(playerWin+computerWin))
+'\n'+winner(playerWin, computerWin));
alert('Reload the page to play again');
}
game();
</script>
</body>
</html>