-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
272 lines (210 loc) · 7.15 KB
/
index.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
const CHOICES = ['rock', 'paper', 'scissors']
const equivalentEmoji = {
rock: '🪨',
paper: '📃',
scissors: '✂️',
}
const controlStepVal = {
KeyH: -1,
KeyJ: 2,
KeyK: -2,
KeyL: 1,
}
let existingTimeout = null
controlStepVal['ArrowLeft'] = controlStepVal.KeyH
controlStepVal['ArrowRight'] = controlStepVal.KeyL
controlStepVal['ArrowDown'] = controlStepVal.KeyJ
controlStepVal['ArrowUp'] = controlStepVal.KeyK
function getComputerChoice() {
const randomChoice = Math.floor(Math.random() * 3)
return CHOICES[randomChoice]
}
function playSingleRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase().trim()
computerSelection = computerSelection.toLowerCase().trim()
const beatsWho = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper',
}
if (playerSelection === computerSelection) {
return [-1, "It's a tie!"]
} else if (beatsWho[playerSelection] === computerSelection) {
return [
1,
`You Win! [${equivalentEmoji[playerSelection]} beats ${equivalentEmoji[computerSelection]}]`,
]
} else {
return [
0,
`You Lose! [${equivalentEmoji[computerSelection]} beats ${equivalentEmoji[playerSelection]}]`,
]
}
}
function changeVisuallySelected(prevSelectedOption, newSelectedOption) {
if (prevSelectedOption) {
const optionText = document.getElementById('option-text')
prevSelectedOption.innerHTML = optionText.textContent
}
newSelectedOption.innerHTML =
'<span id="cursor">▶</span>' +
`<span id="option-text">${newSelectedOption.textContent}</span>`
return newSelectedOption
}
function getNextNthSibling(selectedOption, n) {
const sign = n < 0 ? 'neg' : 'pos'
n = Math.abs(n)
while (n > 0) {
const sibling =
sign === 'neg'
? selectedOption.previousElementSibling
: selectedOption.nextElementSibling
if (!sibling) return selectedOption
selectedOption = sibling
n--
}
return selectedOption
}
function getScoreView(score) {
return '★ '.repeat(score) + '☆ '.repeat(5 - score)
}
function displayMessage(
textElement,
textValue,
duration = 5000,
type = 'general'
) {
if (type === 'round' && existingTimeout) clearTimeout(existingTimeout)
textElement.textContent = textValue
const timeoutId = setTimeout(() => {
textElement.textContent = ''
}, duration)
// overwrite existing timeout
if (type === 'round') existingTimeout = timeoutId
}
function toggleMenuDisable(nodeList, value) {
for (let i = 0; i < nodeList.length - 1; i++) {
nodeList[i].disabled = value
}
}
function game() {
let gameStarted = false
let playerScore = 0
let computerScore = 0
let lastRoundMessage = ''
let roundMessageRepeat = 0
const playerPickDisplay = document.getElementById('player-pick')
const computerPickDisplay = document.getElementById('computer-pick')
const playerScoreDisplay = document.getElementById('player-score')
const computerScoreDisplay = document.getElementById('computer-score')
const generalMessageDisplay = document.getElementById('general-message')
const roundMessageDisplay = document.getElementById('round-message')
const mainItem = document.getElementById('main-item')
let currentlySelected = mainItem
const menuOptions = document.querySelectorAll('#shape-menu button')
const menuOptionValue = {
'rock-item': 'rock',
'paper-item': 'paper',
'scissors-item': 'scissors',
}
toggleMenuDisable(menuOptions, true)
changeVisuallySelected(undefined, currentlySelected)
displayMessage(generalMessageDisplay, "Select 'Start' to play game", 2000)
function gameOver() {
gameStarted = false
toggleMenuDisable(menuOptions, true)
playerPickDisplay.textContent = '�'
computerPickDisplay.textContent = '�'
/* playerScoreDisplay.textContent = getScoreView(0)
computerScoreDisplay.textContent = getScoreView(0) */
mainItem.textContent = 'Restart'
if (currentlySelected !== mainItem) {
// carry out if the game ended thru game playing (main item not selected)
currentlySelected = changeVisuallySelected(currentlySelected, mainItem)
} else {
// carry out if the game ended by clicking 'Quit'
changeVisuallySelected(undefined, mainItem)
}
let finalMessage
if (playerScore < 5 && computerScore < 5) {
finalMessage = 'What a sore quitter! ⁑ρ'
} else {
if (playerScore > computerScore) finalMessage = 'You Win ⚐ the game!'
else finalMessage = 'You Lose ☠ the game!'
}
displayMessage(generalMessageDisplay, finalMessage)
playerScore = 0
computerScore = 0
}
function checkRound(e) {
e.stopPropagation()
// return immediately if the event comes not from a pressed 'Enter' key or a mouse click
const notKeyboardTargeting = e.type === 'keydown' && e.code !== 'Enter'
if (e.type !== 'click' && notKeyboardTargeting) return
if (!gameStarted) {
toggleMenuDisable(menuOptions, false)
mainItem.textContent = 'Quit'
changeVisuallySelected(undefined, mainItem)
gameStarted = true
return
}
const isQuitting =
e.currentTarget.id === 'main-item' ||
(currentlySelected.id === 'main-item' && e.code === 'Enter')
if (gameStarted && isQuitting) {
gameOver()
return
}
const userSelection = menuOptionValue[currentlySelected.id]
const opponentSelection = getComputerChoice()
playerPickDisplay.textContent = equivalentEmoji[userSelection]
computerPickDisplay.textContent = equivalentEmoji[opponentSelection]
const [userWon, message] = playSingleRound(userSelection, opponentSelection)
if (lastRoundMessage === message) roundMessageRepeat++
else {
roundMessageRepeat = 0
lastRoundMessage = ''
}
lastRoundMessage = message
const additionalMessage = roundMessageRepeat
? ' (x' + (roundMessageRepeat + 1) + ')'
: ''
displayMessage(
roundMessageDisplay,
`${message}${additionalMessage}`,
2000,
'round'
)
const soundToPlay = document.querySelector(`audio[data-key="${userWon}"]`)
if (soundToPlay) {
soundToPlay.currentTime = 0
soundToPlay.play()
}
if (userWon === 1) playerScore++
else if (userWon === 0) {
computerScore++
playerPickDisplay.classList.add('damaged')
}
playerScoreDisplay.textContent = getScoreView(playerScore)
computerScoreDisplay.textContent = getScoreView(computerScore)
if (playerScore === 5 || computerScore === 5) gameOver()
}
menuOptions.forEach(option => {
option.addEventListener('mouseenter', e => {
if (!gameStarted) return
currentlySelected = changeVisuallySelected(currentlySelected, e.target)
})
option.addEventListener('click', checkRound, { capture: true })
})
window.addEventListener('keydown', checkRound)
window.addEventListener('keydown', e => {
if (!gameStarted) return
const stepSize = controlStepVal[e.code]
const nthSibling = getNextNthSibling(currentlySelected, stepSize)
currentlySelected = changeVisuallySelected(currentlySelected, nthSibling)
})
playerPickDisplay.addEventListener('animationend', () => {
playerPickDisplay.classList.remove('damaged')
})
}
game()