-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscript.js
More file actions
456 lines (396 loc) · 9.48 KB
/
script.js
File metadata and controls
456 lines (396 loc) · 9.48 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/** @constant */
const SYMBOLS = [
"😺",
"🖐",
"🧳",
"☂️",
"🧵",
"🧶",
"👓",
"👕",
"👑",
"👠",
"🐞",
"🦋",
"🐝",
"🐟",
"🍄",
"🐚",
"🌻",
"⛄️",
"🍎",
"🚗",
"🏀",
"🦄",
"🦊",
"🌎",
"🍉",
"🍩",
"🍿",
"🥝",
"🎸",
"🚜",
"⏰",
"🔑",
"🎁",
]
/** @constant */
const SHOW_CARD_DURATION = 1500
/** @constant */
const LOCAL_STORAGE_NAMESPACE = 'hu.violapeter.memorygame'
/** @enum */
const GameDifficulty = {
Beginner: 4,
Intermediate: 6,
Advanced: 8,
}
/**
* @enum
*/
const GameStatus = {
Won: 'WON',
BeginGame: 'BEGIN_GAME',
InGame: 'IN_GAME',
BetweenSteps: 'BETWEEN_STEPS',
}
/**
* @typedef {{
* turned: number[],
* found: number[],
* board?: string[],
* steps: number,
* status: GameStatus,
* timerId?: number,
* startTime?: number,
* difficulty: GameDifficulty,
* }} AppState
*/
/**
* Current state of the game
*
* @type AppState
*/
const AppState = {
board: null,
turned: [],
found: [],
steps: 0,
status: GameStatus.BeginGame,
timerId: undefined,
startTime: 0,
difficulty: GameDifficulty.Intermediate,
}
/**
* @param {*[]} array
* @returns {[]}
*/
function shuffle(array) {
const collection = array
let len = array.length
let random
let temp
while (len) {
random = Math.floor(Math.random() * len)
len -= 1
temp = collection[len]
collection[len] = collection[random]
collection[random] = temp
}
return collection
}
/**
* @param {*[]} data
* @param {number} count
* @returns {*[]}
*/
function pickRandom(data, count) {
data = [...data]
const pickedElements = []
while (count--) {
pickedElements.push(data.splice(Math.floor(Math.random() * data.length), 1)[0])
}
return pickedElements
}
/** @returns {boolean} */
function isPairRevealedInStep() {
return AppState.turned.length % 2 === 0
}
/** @returns {boolean} */
function isWin() {
return AppState.turned.length === AppState.board.length
}
/** Resets the last turned 2 cards */
function turnBackCards() {
setTimeout(() => {
AppState.turned = AppState.turned.slice(0, -2)
AppState.status = GameStatus.InGame
updateUI(AppState)
}, SHOW_CARD_DURATION)
}
function clearGame() {
if (AppState.timerId !== undefined) {
clearInterval(AppState.timerId)
AppState.timerId = undefined
}
clearLocalStorage()
}
/** Checks the app's state and decides the next step */
function checkState() {
if (!isPairRevealedInStep()) {
return
}
AppState.status = GameStatus.BetweenSteps
if (isWin()) {
AppState.status = GameStatus.Won
clearGame()
return
}
if (isPair()) {
AppState.status = GameStatus.InGame
pairFound()
return
}
turnBackCards()
}
/**
* @param index
* @return {HTMLDivElement}
*/
function getCardElementByIndex(index) {
return document.querySelector(`.card[data-id="${index}"]`)
}
/** @return {number[]} */
function getLastTurnedPair() {
return AppState.turned.slice(-2)
}
/** @returns {boolean} */
function isPair() {
const [a, b] = getLastTurnedPair()
return AppState.board[a] === AppState.board[b]
}
function pairFound() {
AppState.found.push(...getLastTurnedPair())
getLastTurnedPair().forEach((index) => {
const el = getCardElementByIndex(index)
el.classList.add('found')
setTimeout(() => {
moveCardOutOfBoardWithTransition(el, 0.1)
}, 1000)
})
}
/** @param {number} cardId */
function turnCard(cardId) {
if (AppState.turned.includes(cardId)) {
return
}
AppState.turned.push(cardId)
AppState.steps++
checkState()
}
/** @returns {boolean} */
function isCardTurnAllowed() {
return AppState.status === GameStatus.InGame || AppState.status === GameStatus.BeginGame
}
/** @returns {boolean} */
function shouldInitTimer() {
return AppState.status === GameStatus.BeginGame && !AppState.timerId
}
function startTimer() {
AppState.timerId = setInterval(() => updateUI(AppState), 1000)
}
function initTimer() {
if (!shouldInitTimer()) {
return
}
AppState.status = GameStatus.InGame
AppState.startTime = Date.now()
startTimer()
updateUI(AppState)
}
/** @param {number} cardId */
function handleClickCard(cardId) {
if (!isCardTurnAllowed()) {
return
}
turnCard(cardId)
updateUI(AppState)
initTimer()
}
/**
* @param {string[]} board
* @returns {string}
*/
function renderBoard(board) {
return board.map((content, id) => `
<button class="card" data-id="${id}" aria-label="Kártya megrdítása">
<div class="card-inner">
<div class="card-back" aria-hidden="true"></div>
<div class="card-front" aria-hidden="true">${content}</div>
</div>
</button>`).join('')
}
/** @return {NodeListOf<Element>} */
function getCards() {
return document.querySelectorAll('.card')
}
/**
* Callback of the iterateCards function.
* @see iterateCards
* @callback iteratorCallback
* @param {HTMLDivElement} card
* @param {number} index
*/
/**
* @param {iteratorCallback} callback
*/
function iterateCards(callback) {
getCards().forEach(callback)
}
/**
* @param {AppState} state
* @void
*/
function renderUI(state) {
document.querySelector('.board').innerHTML = renderBoard(state.board)
iterateCards((card, index) => {
card.addEventListener('click', () => handleClickCard(index))
card.classList[state.found.includes(index) ? 'add' : 'remove']('already-found')
})
document.querySelectorAll('.js-yes, .js-replay').forEach((el) => {
el.addEventListener('click', () => {
startNewGame()
})
})
document.documentElement.style.setProperty('--grid', String(state.difficulty))
updateUI(state)
}
/**
* @param {number} milliseconds
* @returns {string}
*/
function convertMsToMinutesSeconds(milliseconds) {
const minutes = Math.floor(milliseconds / 60000)
const seconds = Math.round((milliseconds % 60000) / 1000)
return seconds === 60
? `${minutes + 1}:00`
: `${minutes}:${seconds.toString().padStart(2, '0')}`
}
/** @param {AppState} state */
function updateUI(state) {
iterateCards((card, cardId) => {
card.classList[state.turned.includes(cardId) ? 'add' : 'remove']('turned')
})
document.querySelector('.win').classList[state.status === GameStatus.Won ? 'add' : 'remove']('open')
document.querySelector('.js-time').innerHTML = convertMsToMinutesSeconds(
Date.now() - state.startTime
)
document.querySelector('.js-steps').innerHTML = `${AppState.steps} lépés`
if (shouldSave()) {
saveToLocalStorage(state)
}
}
/**
* @param {number} columns
* @param {number} [rows]
* @returns {string[]}
*/
function generateBoard(columns, rows = columns) {
const symbolCount = (columns * rows) / 2
const symbols = pickRandom(SYMBOLS, symbolCount)
return shuffle([...symbols, ...symbols])
}
/** @returns {boolean} */
function shouldSave() {
return AppState.status === GameStatus.InGame || AppState.status === GameStatus.BetweenSteps
}
/** @param {AppState} state */
function saveToLocalStorage(state) {
const asString = JSON.stringify(state)
localStorage.setItem(LOCAL_STORAGE_NAMESPACE, asString)
}
/** @returns {(AppState|null)} */
function readStateFromLocalStorage() {
const stored = localStorage.getItem(LOCAL_STORAGE_NAMESPACE)
if (stored === null) {
return null
}
return JSON.parse(stored)
}
function clearLocalStorage() {
if (localStorage.getItem(LOCAL_STORAGE_NAMESPACE) !== null) {
localStorage.removeItem(LOCAL_STORAGE_NAMESPACE)
}
}
function startNewGame() {
clearGame()
AppState.board = generateBoard(AppState.difficulty)
AppState.turned = []
AppState.found = []
AppState.steps = 0
AppState.status = GameStatus.BeginGame
AppState.startTime = Date.now()
renderUI(AppState)
dealCards()
}
/** @param {AppState} state */
function restoreSavedGame(state) {
AppState.board = state.board
AppState.turned = state.turned
AppState.found = state.found
AppState.steps = state.steps
AppState.status = state.status
AppState.startTime = state.startTime
AppState.difficulty = state.difficulty
startTimer()
if (AppState.status === GameStatus.BetweenSteps) {
checkState()
}
renderUI(AppState)
}
/** @param {HTMLDivElement} card */
function moveCardOutOfBoard(card) {
const BOX_SHADOW_CORRECTION = 12
const { x, y, width, height } = card.getBoundingClientRect()
card.style.setProperty(
'transform',
`translate(-${x + width + BOX_SHADOW_CORRECTION}px, -${y + height + BOX_SHADOW_CORRECTION}px)`
)
}
/**
* @param {HTMLDivElement} card
* @param {number} transitionDelay
*/
function moveCardOutOfBoardWithTransition(card, transitionDelay) {
const removeTransitionProperty = () => {
card.style.removeProperty('transition')
card.style.removeProperty('transition-delay')
card.removeEventListener('transitionend', removeTransitionProperty)
}
card.style.setProperty('transition', 'transform .2s ease')
card.style.setProperty('transition-delay', `${transitionDelay}s`)
card.addEventListener('transitionend', removeTransitionProperty)
moveCardOutOfBoard(card)
}
function moveCardsOutOfBoard() {
iterateCards(moveCardOutOfBoard)
}
function dealCards() {
moveCardsOutOfBoard()
setTimeout(() => {
iterateCards((card, index) => {
card.style.setProperty('transition', 'transform .2s ease')
card.style.setProperty('transition-delay', `${index * 0.02}s`)
card.style.removeProperty('transform')
})
}, 10)
}
/** Entry point */
function init() {
const savedGame = readStateFromLocalStorage()
if (savedGame) {
restoreSavedGame(savedGame)
return
}
startNewGame()
}
init()