-
Notifications
You must be signed in to change notification settings - Fork 0
/
rps.js
103 lines (87 loc) · 3.02 KB
/
rps.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const ROCK = 'rock'
const PAPER = 'paper'
const SCISSORS = 'scissors'
function getComputerChoice() {
let num = Math.random();
if (num <= 0.33) {
return ROCK;
} else if (num <= 0.66) {
return PAPER;
}
return SCISSORS;
}
function gameResult(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return 0
}
if (playerSelection === ROCK && computerSelection === SCISSORS ||
playerSelection === SCISSORS && computerSelection === PAPER ||
playerSelection === PAPER && computerSelection === ROCK) {
return 1
}
return -1
}
function craftResult(playerChoice, computerSelection, result) {
switch (result) {
case 0:
return `It is a tie. Both players chose ${playerChoice}.`
case -1:
return `Computer wins! ${computerSelection} beats ${playerChoice}.`
default:
return `Player wins! ${playerChoice} beats ${computerSelection}.`
}
}
function craftFinalResult(playerScore, computerScore) {
let finalScoreString = `Final Score, Player ${playerScore}, Computer ${computerScore}. `;
let result = 'It is a tie!';
if (playerScore > computerScore) {
result = 'Player wins!';
} else if (playerScore < computerScore) {
result = 'Computer wins!';
}
return finalScoreString + result;
}
let playerScore = 0;
let computerScore = 0;
const buttons = document.querySelectorAll('.btn');
function updateScoreString(result) {
switch (result) {
case -1:
computerScore++;
break;
case 1:
playerScore++;
break;
default:
}
return `Player Score: ${playerScore}, Computer Score: ${computerScore}`;
}
// Iterate through each button and add a click event listener
buttons.forEach(button => {
button.addEventListener('click', function(e) {
// Play Game
let computerSelection = getComputerChoice();
let playerChoice = e.target.innerText.toLowerCase();
let result = gameResult(playerChoice, computerSelection);
// Update Result String
let resultTxt = craftResult(playerChoice, computerSelection, result);
let resultElem = document.querySelector('#result');
resultElem.innerText = resultTxt;
// Update Score String
let scoreString = updateScoreString(result);
let scoreElem = document.querySelector('#score');
scoreElem.innerText = scoreString;
// When game is over, display the final message and reset the game.
let finalElem = document.querySelector('#final');
if (playerScore >= 5 || computerScore >= 5) {
let finalResultStr = craftFinalResult(playerScore, computerScore);
finalElem.innerText = finalResultStr;
playerScore = 0;
computerScore = 0;
scoreElem.innerText = 'Your Score: 0 Computer Score: 0';
resultElem.innerText = '';
} else {
finalElem.innerText = '';
}
});
});