forked from GavinLonDigital/HuntTheAceJSGame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
623 lines (483 loc) · 13.5 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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
const cardObjectDefinitions = [
{id:1, imagePath:'/images/card-KingHearts.png'},
{id:2, imagePath:'/images/card-JackClubs.png'},
{id:3, imagePath:'/images/card-QueenDiamonds.png'},
{id:4, imagePath:'/images/card-AceSpades.png'}
]
const aceId = 4
const cardBackImgPath = '/images/card-back-blue.png'
let cards = []
const playGameButtonElem = document.getElementById('playGame')
const cardContainerElem = document.querySelector('.card-container')
const collapsedGridAreaTemplate = '"a a" "a a"'
const cardCollectionCellClass = ".card-pos-a"
const numCards = cardObjectDefinitions.length
let cardPositions = []
let gameInProgress = false
let shufflingInProgress = false
let cardsRevealed = false
const currentGameStatusElem = document.querySelector('.current-status')
const scoreContainerElem = document.querySelector('.header-score-container')
const scoreElem = document.querySelector('.score')
const roundContainerElem = document.querySelector('.header-round-container')
const roundElem = document.querySelector('.round')
const winColor = "green"
const loseColor = "red"
const primaryColor = "black"
let roundNum = 0
let maxRounds = 4
let score = 0
let gameObj = {}
const localStorageGameKey = "HTA"
/* <div class="card">
<div class="card-inner">
<div class="card-front">
<img src="/images/card-JackClubs.png" alt="" class="card-img">
</div>
<div class="card-back">
<img src="/images/card-back-Blue.png" alt="" class="card-img">
</div>
</div>
</div> */
loadGame()
function gameOver()
{
updateStatusElement(scoreContainerElem,"none")
updateStatusElement(roundContainerElem,"none")
const gameOverMessage = `Game Over! Final Score - <span class = 'badge'>${score}</span> Click 'Play Game' button to play again`
updateStatusElement(currentGameStatusElem,"block",primaryColor,gameOverMessage)
gameInProgress = false
playGameButtonElem.disabled = false
}
function endRound()
{
setTimeout(()=>{
if(roundNum == maxRounds)
{
gameOver()
return
}
else
{
startRound()
}
},3000)
}
function chooseCard(card)
{
if(canChooseCard())
{
evaluateCardChoice(card)
saveGameObjectToLocalStorage(score, roundNum)
flipCard(card,false)
setTimeout(() => {
flipCards(false)
updateStatusElement(currentGameStatusElem,"block", primaryColor,"Card positions revealed")
endRound()
},3000)
cardsRevealed = true
}
}
function calculateScoreToAdd(roundNum)
{
if(roundNum == 1)
{
return 100
}
else if(roundNum == 2)
{
return 50
}
else if(roundNum == 3)
{
return 25
}
else
{
return 10
}
}
function calculateScore()
{
const scoreToAdd = calculateScoreToAdd(roundNum)
score = score + scoreToAdd
}
function updateScore()
{
calculateScore()
updateStatusElement(scoreElem, "block", primaryColor, `Score <span class='badge'>${score}</span>`)
}
function updateStatusElement(elem, display, color, innerHTML)
{
elem.style.display = display
if(arguments.length > 2)
{
elem.style.color = color
elem.innerHTML = innerHTML
}
}
function outputChoiceFeedBack(hit)
{
if(hit)
{
updateStatusElement(currentGameStatusElem, "block", winColor, "Hit!! - Well Done!! :)")
}
else
{
updateStatusElement(currentGameStatusElem, "block", loseColor, "Missed!! :(")
}
}
function evaluateCardChoice(card)
{
if(card.id == aceId)
{
updateScore()
outputChoiceFeedBack(true)
}
else
{
outputChoiceFeedBack(false)
}
}
function canChooseCard()
{
return gameInProgress == true && !shufflingInProgress && !cardsRevealed
}
function loadGame(){
createCards()
cards = document.querySelectorAll('.card')
cardFlyInEffect()
playGameButtonElem.addEventListener('click', ()=>startGame())
updateStatusElement(scoreContainerElem,"none")
updateStatusElement(roundContainerElem,"none")
}
function checkForIncompleteGame()
{
const serializedGameObj = getLocalStorageItemValue(localStorageGameKey)
if(serializedGameObj)
{
gameObj = getObjectFromJSON(serializedGameObj)
if(gameObj.round >= maxRounds)
{
removeLocalStorageItem(localStorageGameKey)
}
else
{
if(confirm('Would you like to continue with your last game?'))
{
score = gameObj.score
roundNum = gameObj.round
}
}
}
}
function startGame(){
initializeNewGame()
startRound()
}
function initializeNewGame(){
score = 0
roundNum = 0
checkForIncompleteGame()
shufflingInProgress = false
updateStatusElement(scoreContainerElem,"flex")
updateStatusElement(roundContainerElem,"flex")
updateStatusElement(scoreElem,"block",primaryColor,`Score <span class='badge'>${score}</span>`)
updateStatusElement(roundElem,"block",primaryColor,`Round <span class='badge'>${roundNum}</span>`)
}
function startRound()
{
initializeNewRound()
collectCards()
flipCards(true)
shuffleCards()
}
function initializeNewRound()
{
roundNum++
playGameButtonElem.disabled = true
gameInProgress = true
shufflingInProgress = true
cardsRevealed = false
updateStatusElement(currentGameStatusElem, "block", primaryColor, "Shuffling...")
updateStatusElement(roundElem, "block", primaryColor, `Round <span class='badge'>${roundNum}</span>`)
}
function collectCards(){
transformGridArea(collapsedGridAreaTemplate)
addCardsToGridAreaCell(cardCollectionCellClass)
}
function transformGridArea(areas)
{
cardContainerElem.style.gridTemplateAreas = areas
}
function addCardsToGridAreaCell(cellPositionClassName)
{
const cellPositionElem = document.querySelector(cellPositionClassName)
cards.forEach((card, index) =>{
addChildElement(cellPositionElem, card)
})
}
function flipCard(card, flipToBack)
{
const innerCardElem = card.firstChild
if(flipToBack && !innerCardElem.classList.contains('flip-it'))
{
innerCardElem.classList.add('flip-it')
}
else if(innerCardElem.classList.contains('flip-it'))
{
innerCardElem.classList.remove('flip-it')
}
}
function flipCards(flipToBack){
cards.forEach((card,index)=>{
setTimeout(() => {
flipCard(card,flipToBack)
},index * 100)
})
}
function cardFlyInEffect()
{
const id = setInterval(flyIn, 5)
let cardCount = 0
let count = 0
function flyIn()
{
count++
if(cardCount == numCards)
{
clearInterval(id)
playGameButtonElem.style.display = "inline-block"
}
if(count == 1 || count == 250 || count == 500 || count == 750)
{
cardCount++
let card = document.getElementById(cardCount)
card.classList.remove("fly-in")
}
}
}
function removeShuffleClasses()
{
cards.forEach((card) =>{
card.classList.remove("shuffle-left")
card.classList.remove("shuffle-right")
})
}
function animateShuffle(shuffleCount)
{
const random1 = Math.floor(Math.random() * numCards) + 1
const random2 = Math.floor(Math.random() * numCards) + 1
let card1 = document.getElementById(random1)
let card2 = document.getElementById(random2)
if (shuffleCount % 4 == 0)
{
card1.classList.toggle("shuffle-left")
card1.style.zIndex = 100
}
if (shuffleCount % 10 == 0)
{
card2.classList.toggle("shuffle-right")
card2.style.zIndex = 200
}
}
function shuffleCards()
{
let shuffleCount = 0
const id = setInterval(shuffle, 12)
function shuffle()
{
randomizeCardPositions()
animateShuffle(shuffleCount)
if(shuffleCount == 500)
{
clearInterval(id)
shufflingInProgress = false
removeShuffleClasses()
dealCards()
updateStatusElement(currentGameStatusElem, "block", primaryColor, "Please click the card that you think is the Ace of Spades...")
}
else{
shuffleCount++
}
}
}
function randomizeCardPositions()
{
const random1 = Math.floor(Math.random() * numCards) + 1
const random2 = Math.floor(Math.random() * numCards) + 1
const temp = cardPositions[random1 - 1]
cardPositions[random1 - 1] = cardPositions[random2 - 1]
cardPositions[random2 - 1] = temp
}
function dealCards()
{
addCardsToAppropriateCell()
const areasTemplate = returnGridAreasMappedToCardPos()
transformGridArea(areasTemplate)
}
function returnGridAreasMappedToCardPos()
{
let firstPart = ""
let secondPart = ""
let areas = ""
cards.forEach((card, index) => {
if(cardPositions[index] == 1)
{
areas = areas + "a "
}
else if(cardPositions[index] == 2)
{
areas = areas + "b "
}
else if (cardPositions[index] == 3)
{
areas = areas + "c "
}
else if (cardPositions[index] == 4)
{
areas = areas + "d "
}
if (index == 1)
{
firstPart = areas.substring(0, areas.length - 1)
areas = "";
}
else if (index == 3)
{
secondPart = areas.substring(0, areas.length - 1)
}
})
return `"${firstPart}" "${secondPart}"`
}
function addCardsToAppropriateCell()
{
cards.forEach((card)=>{
addCardToGridCell(card)
})
}
function createCards()
{
cardObjectDefinitions.forEach((cardItem)=>{
createCard(cardItem)
})
}
function createCard(cardItem){
//create div elements that make up a card
const cardElem = createElement('div')
const cardInnerElem = createElement('div')
const cardFrontElem = createElement('div')
const cardBackElem = createElement('div')
//create front and back image elements for a card
const cardFrontImg = createElement('img')
const cardBackImg = createElement('img')
//add class and id to card element
addClassToElement(cardElem, 'card')
addClassToElement(cardElem, 'fly-in')
addIdToElement(cardElem, cardItem.id)
//add class to inner card element
addClassToElement(cardInnerElem, 'card-inner')
//add class to front card element
addClassToElement(cardFrontElem, 'card-front')
//add class to back card element
addClassToElement(cardBackElem, 'card-back')
//add src attribute and appropriate value to img element - back of card
addSrcToImageElem(cardBackImg, cardBackImgPath)
//add src attribute and appropriate value to img element - front of card
addSrcToImageElem(cardFrontImg, cardItem.imagePath)
//assign class to back image element of back of card
addClassToElement(cardBackImg, 'card-img')
//assign class to front image element of front of card
addClassToElement(cardFrontImg, 'card-img')
//add front image element as child element to front card element
addChildElement(cardFrontElem, cardFrontImg)
//add back image element as child element to back card element
addChildElement(cardBackElem, cardBackImg)
//add front card element as child element to inner card element
addChildElement(cardInnerElem, cardFrontElem)
//add back card element as child element to inner card element
addChildElement(cardInnerElem, cardBackElem)
//add inner card element as child element to card element
addChildElement(cardElem, cardInnerElem)
//add card element as child element to appropriate grid cell
addCardToGridCell(cardElem)
initializeCardPositions(cardElem)
attatchClickEventHandlerToCard(cardElem)
}
function attatchClickEventHandlerToCard(card){
card.addEventListener('click', () => chooseCard(card))
}
function initializeCardPositions(card)
{
cardPositions.push(card.id)
}
function createElement(elemType){
return document.createElement(elemType)
}
function addClassToElement(elem, className){
elem.classList.add(className)
}
function addIdToElement(elem, id){
elem.id = id
}
function addSrcToImageElem(imgElem, src){
imgElem.src = src
}
function addChildElement(parentElem, childElem){
parentElem.appendChild(childElem)
}
function addCardToGridCell(card)
{
const cardPositionClassName = mapCardIdToGridCell(card)
const cardPosElem = document.querySelector(cardPositionClassName)
addChildElement(cardPosElem, card)
}
function mapCardIdToGridCell(card){
if(card.id == 1)
{
return '.card-pos-a'
}
else if(card.id == 2)
{
return '.card-pos-b'
}
else if(card.id == 3)
{
return '.card-pos-c'
}
else if(card.id == 4)
{
return '.card-pos-d'
}
}
//local storage functions
function getSerializedObjectAsJSON(obj)
{
return JSON.stringify(obj)
}
function getObjectFromJSON(json)
{
return JSON.parse(json)
}
function updateLocalStorageItem(key, value)
{
localStorage.setItem(key, value)
}
function removeLocalStorageItem(key)
{
localStorage.removeItem(key)
}
function getLocalStorageItemValue(key)
{
return localStorage.getItem(key)
}
function updateGameObject(score,round)
{
gameObj.score = score
gameObj.round = round
}
function saveGameObjectToLocalStorage(score,round)
{
updateGameObject(score, round)
updateLocalStorageItem(localStorageGameKey, getSerializedObjectAsJSON(gameObj))
}