Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
799 lines (694 loc) · 27.5 KB
/
Copy pathscript.js
File metadata and controls
799 lines (694 loc) · 27.5 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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// ============================================================================
// GAME CONFIGURATION
// ============================================================================
const DIFFICULTY_CONFIG = {
easy: { gridSize: 4, pairs: 8 },
medium: { gridSize: 6, pairs: 18 },
hard: { gridSize: 8, pairs: 32 }
};
// Card symbols using emojis or image URLs
const CARD_SYMBOLS = {
default: ['🎮', '🎲', '🎯', '🎪', '🎨', '🎭', '🎬', '🎤',
'🎧', '🎸', '🎹', '🎺', '🎻', '🎼', '🎵', '🎶',
'🏀', '⚽', '🏈', '⚾', '🎾', '🏐', '🏉', '🎱',
'🏓', '🏸', '🏒', '🏑', '🥊', '⛳', '🏹', '🎣'],
tropical: [
'./assets/images/tropical/palm-tree.jpg',
'./assets/images/tropical/coconut.jpg',
'./assets/images/tropical/parrot.jpg',
'./assets/images/tropical/hibiscus.jpg',
'./assets/images/tropical/pineapple.jpg',
'./assets/images/tropical/tropical-leaves.jpg',
'./assets/images/tropical/toucan.jpg',
'./assets/images/tropical/tropical-flower.jpg',
'./assets/images/tropical/beach-ocean.jpg',
'./assets/images/tropical/seashell.jpg',
'./assets/images/tropical/flamingo.jpg',
'./assets/images/tropical/banana.jpg',
'./assets/images/tropical/mango.jpg',
'./assets/images/tropical/palm-leaves.jpg',
'./assets/images/tropical/plumeria.jpg',
'./assets/images/tropical/butterfly.jpg',
'./assets/images/tropical/tropical-fish.jpg',
'./assets/images/tropical/sunset-beach.jpg',
'./assets/images/tropical/sun.jpg',
'./assets/images/tropical/island-bird.jpg',
'./assets/images/tropical/tropical-bird.jpg',
'./assets/images/tropical/crab.jpg',
'./assets/images/tropical/sea-turtle.jpg',
'./assets/images/tropical/cactus.jpg',
'./assets/images/tropical/peacock.jpg',
'./assets/images/tropical/macaw.jpg',
'./assets/images/tropical/coconut-2.jpg',
'./assets/images/tropical/tropical-leaf.jpg',
'./assets/images/tropical/palm-tree-2.jpg',
'./assets/images/tropical/ocean-2.jpg',
'./assets/images/tropical/palm-tree-3.jpg',
'./assets/images/tropical/beach-paradise.jpg'
],
beach: ['🏖️', '🌊', '🏄', '🐚', '⛱️', '🦀', '🌅', '🐠',
'🦑', '🐟', '🏊', '⛵', '🛟', '🩱', '🥽', '🤿',
'🏝️', '☀️', '🌴', '🥥', '🍹', '🦩', '🐬', '🌺',
'🕶️', '👙', '🧴', '🪁', '🏐', '🦈', '🐙', '🪸'],
sunset: ['🌅', '🌄', '☀️', '🌞', '⭐', '🌟', '✨', '🌠',
'🌇', '🌆', '🌃', '🌌', '🌉', '🎆', '🎇', '🔥',
'💛', '🧡', '❤️', '💜', '💗', '💖', '💕', '🌺',
'🌸', '🌼', '🌻', '🏵️', '💐', '🌷', '🌹', '🥀']
};
// Storage keys
const SESSION_STATE_KEY = 'memoryGameState';
const TOTAL_MOVES_KEY = 'memoryGameTotalMoves';
// ============================================================================
// GAME STATE
// ============================================================================
let gameState = {
difficulty: 'easy',
cards: [],
flippedCards: [],
matchedPairs: 0,
moves: 0,
timer: 0,
timerInterval: null,
isProcessing: false,
soundEnabled: true,
theme: 'default'
};
// ============================================================================
// SOUND EFFECTS
// ============================================================================
const cardFlipSound = new Audio('./assets/sound/cardflip.mp3');
const cardMatchSound = new Audio('./assets/sound/cardmatch.mp3');
const cardFailSound = new Audio('./assets/sound/cardfail.mp3');
const congratsSound = new Audio('./assets/sound/congrats.mp3');
/**
* Play sound if sound is enabled
*/
const playSound = (sound) => {
if (gameState.soundEnabled) {
sound.currentTime = 0;
sound.play().catch(e => console.log('Audio play failed:', e));
}
};
// ============================================================================
// FUNCTIONAL PROGRAMMING CONCEPT: Pure Functions & Higher-Order Functions
// ============================================================================
// The following functions are pure functions - they don't modify external state
// and always return the same output for the same input
/**
* FUNCTIONAL PROGRAMMING CONCEPT (Chapter 11):
* This is a pure function that creates card data using map() and slice()
* It doesn't mutate any external state and returns a new array
*/
const createCardData = (numPairs) => {
const themeSymbols = CARD_SYMBOLS[gameState.theme] || CARD_SYMBOLS.default;
const selectedSymbols = themeSymbols.slice(0, numPairs);
const pairs = selectedSymbols.flatMap(symbol => [
{ id: Math.random(), symbol, matched: false },
{ id: Math.random(), symbol, matched: false }
]);
return shuffleArray(pairs);
};
/**
* Fisher-Yates shuffle algorithm - creates a new shuffled array
*/
const shuffleArray = (array) => {
const newArray = [...array];
for (let i = newArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArray[i], newArray[j]] = [newArray[j], newArray[i]]; // ES6 destructuring
}
return newArray;
};
/**
* Format seconds into MM:SS format - pure function
*/
const formatTime = (seconds) => {
const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
const secs = (seconds % 60).toString().padStart(2, '0');
return `${mins}:${secs}`; // ES6 template literal
};
// ============================================================================
// STORAGE HELPERS
// ============================================================================
const getTotalMoves = () => {
const rawValue = localStorage.getItem(TOTAL_MOVES_KEY);
const parsed = parseInt(rawValue, 10);
return Number.isNaN(parsed) ? 0 : parsed;
};
const updateTotalMovesDisplay = (value) => {
const totalMovesElement = document.getElementById('totalMoves');
if (totalMovesElement) {
totalMovesElement.textContent = value;
}
};
const incrementTotalMoves = () => {
const updated = getTotalMoves() + 1;
localStorage.setItem(TOTAL_MOVES_KEY, `${updated}`);
updateTotalMovesDisplay(updated);
};
const resetTotalMoves = () => {
localStorage.setItem(TOTAL_MOVES_KEY, '0');
updateTotalMovesDisplay(0);
};
const isGameWon = () => {
const totalPairs = DIFFICULTY_CONFIG[gameState.difficulty].pairs;
return gameState.matchedPairs === totalPairs;
};
const saveGameState = () => {
const stateToSave = {
difficulty: gameState.difficulty,
theme: gameState.theme,
moves: gameState.moves,
timer: gameState.timer,
matchedPairs: gameState.matchedPairs,
cards: gameState.cards.map(card => ({
symbol: card.symbol,
matched: card.matched,
faceUp: !!card.matched
})),
gameWon: isGameWon()
};
sessionStorage.setItem(SESSION_STATE_KEY, JSON.stringify(stateToSave));
};
const loadGameState = () => {
const savedState = sessionStorage.getItem(SESSION_STATE_KEY);
if (!savedState) {
return false;
}
try {
const parsedState = JSON.parse(savedState);
if (!parsedState || !Array.isArray(parsedState.cards)) {
return false;
}
const { pairs } = DIFFICULTY_CONFIG[parsedState.difficulty] || DIFFICULTY_CONFIG.easy;
if (parsedState.cards.length !== pairs * 2) {
return false;
}
gameState = {
...gameState,
difficulty: parsedState.difficulty || 'easy',
theme: parsedState.theme || 'default',
cards: parsedState.cards.map(card => ({
id: Math.random(),
symbol: card.symbol,
matched: !!card.matched,
faceUp: !!card.matched
})),
flippedCards: [],
matchedPairs: parsedState.matchedPairs || 0,
moves: parsedState.moves || 0,
timer: parsedState.timer || 0,
timerInterval: null,
isProcessing: false
};
return true;
} catch (error) {
return false;
}
};
// ============================================================================
// DOM MANIPULATION
// ============================================================================
/**
* DOM MANIPULATION EXAMPLE:
* This function manipulates the DOM by cloning the template card element
* and creating multiple card elements dynamically
*/
const renderGameBoard = () => {
const gameBoard = document.getElementById('gameBoard');
const cardTemplate = document.getElementById('cardTemplate');
// Clear existing board
gameBoard.innerHTML = '';
gameBoard.className = `game-board ${gameState.difficulty}`;
// Clone the single template card for each game card
gameState.cards.forEach((cardData, index) => {
// DOM MANIPULATION: Cloning template and modifying it
const cardElement = cardTemplate.cloneNode(true);
cardElement.id = `card-${index}`;
cardElement.style.display = 'block';
cardElement.dataset.index = index;
// Get the button element (card-inner)
const cardButton = cardElement.querySelector('.card-inner');
// Set ARIA label for screen readers
cardButton.setAttribute('aria-label', `Card ${index + 1}, face down`);
cardButton.setAttribute('tabindex', '0');
// Set the back face with the symbol or image
const cardBack = cardElement.querySelector('.card-back');
// Check if symbol is a URL or file path (image)
if (cardData.symbol.startsWith('http') || cardData.symbol.startsWith('./') || cardData.symbol.includes('.jpg') || cardData.symbol.includes('.png')) {
// Create an image element
cardBack.innerHTML = '';
const img = document.createElement('img');
img.src = cardData.symbol;
img.alt = getImageDescription(cardData.symbol);
img.className = 'card-image';
cardBack.appendChild(img);
} else {
// Use emoji as text
cardBack.textContent = cardData.symbol;
}
// EVENT HANDLING: Add click and keyboard event listeners
cardButton.addEventListener('click', handleCardClick);
cardButton.addEventListener('keydown', handleCardKeydown);
const isMatched = !!cardData.matched;
const isFaceUp = isMatched || !!cardData.faceUp;
if (isMatched) {
cardElement.classList.add('flipped', 'matched');
cardButton.setAttribute('aria-label', `Card ${index + 1}, matched`);
cardButton.setAttribute('aria-disabled', 'true');
} else if (isFaceUp) {
const description = cardData.symbol.includes('/') ?
getImageDescription(cardData.symbol) : cardData.symbol;
cardElement.classList.add('flipped');
cardButton.setAttribute('aria-label', `Card ${index + 1}, showing ${description}`);
}
gameBoard.appendChild(cardElement);
});
};
/**
* Get descriptive text from image filename for accessibility
*/
const getImageDescription = (imagePath) => {
const filename = imagePath.split('/').pop().replace('.jpg', '').replace('.png', '');
return filename.replace(/-/g, ' ').replace(/_/g, ' ');
};
/**
* Announce message to screen readers
*/
const announceToScreenReader = (message) => {
const announcer = document.getElementById('sr-announcements');
if (announcer) {
announcer.textContent = message;
// Clear after a delay to allow for new announcements
setTimeout(() => {
announcer.textContent = '';
}, 1000);
}
};
/**
* Handle arrow key navigation on game board
*/
const handleArrowKeyNavigation = (event) => {
// Only handle arrow keys
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) {
return;
}
const focusedCard = document.activeElement.closest('.card');
if (!focusedCard) return;
event.preventDefault();
const currentIndex = parseInt(focusedCard.dataset.index);
const { gridSize } = DIFFICULTY_CONFIG[gameState.difficulty];
const cols = gridSize;
const rows = Math.ceil(gameState.cards.length / cols);
let targetIndex = currentIndex;
switch(event.key) {
case 'ArrowUp':
targetIndex = currentIndex - cols;
break;
case 'ArrowDown':
targetIndex = currentIndex + cols;
break;
case 'ArrowLeft':
targetIndex = currentIndex - 1;
// Prevent wrapping to previous row
if (Math.floor(targetIndex / cols) !== Math.floor(currentIndex / cols)) {
targetIndex = currentIndex;
}
break;
case 'ArrowRight':
targetIndex = currentIndex + 1;
// Prevent wrapping to next row
if (Math.floor(targetIndex / cols) !== Math.floor(currentIndex / cols)) {
targetIndex = currentIndex;
}
break;
}
// Check if target is valid
if (targetIndex >= 0 && targetIndex < gameState.cards.length) {
const targetCard = document.getElementById(`card-${targetIndex}`);
if (targetCard) {
const targetButton = targetCard.querySelector('.card-inner');
targetButton.focus();
}
}
};
/**
* Update UI stats display
*/
const updateStats = () => {
document.getElementById('moves').textContent = gameState.moves;
document.getElementById('timer').textContent = formatTime(gameState.timer);
const totalPairs = DIFFICULTY_CONFIG[gameState.difficulty].pairs;
document.getElementById('pairs').textContent = `${gameState.matchedPairs}/${totalPairs}`;
};
// ============================================================================
// ES6 FEATURES
// ============================================================================
/**
* ES6 FEATURES DEMONSTRATED:
* - Arrow functions
* - const/let declarations
* - Template literals
* - Destructuring assignment
* - Spread operator
* - Default parameters
*/
// Timer management using arrow functions and closure
const startTimer = () => {
if (gameState.timerInterval) return;
// ES6: Arrow function with implicit this binding
gameState.timerInterval = setInterval(() => {
gameState.timer++;
updateStats();
saveGameState();
}, 1000);
};
const stopTimer = () => {
if (gameState.timerInterval) {
clearInterval(gameState.timerInterval);
gameState.timerInterval = null;
saveGameState();
}
};
// ============================================================================
// EVENT HANDLING
// ============================================================================
/**
* Handle keyboard events for accessibility (Enter/Space to flip card)
*/
const handleCardKeydown = (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
handleCardClick(event);
}
};
/**
* EVENT HANDLING EXAMPLE:
* This function handles the click event on cards
*/
const handleCardClick = (event) => {
if (gameState.isProcessing) return;
const cardButton = event.currentTarget;
const cardElement = cardButton.closest('.card');
const index = parseInt(cardElement.dataset.index);
const cardData = gameState.cards[index];
// Start timer on first move
if (gameState.moves === 0) {
startTimer();
announceToScreenReader('Game started');
}
// Ignore if card already flipped or matched
if (cardElement.classList.contains('flipped') ||
cardElement.classList.contains('matched')) {
return;
}
// Flip the card
cardElement.classList.add('flipped');
playSound(cardFlipSound);
cardData.faceUp = true;
// Update ARIA label to reflect flipped state
const description = cardData.symbol.includes('/') ?
getImageDescription(cardData.symbol) : cardData.symbol;
cardButton.setAttribute('aria-label', `Card ${index + 1}, showing ${description}`);
announceToScreenReader(`Card flipped, showing ${description}`);
gameState.flippedCards.push({ element: cardElement, data: cardData, index });
// Check for match when 2 cards are flipped
if (gameState.flippedCards.length === 2) {
gameState.moves++;
incrementTotalMoves();
updateStats();
saveGameState();
checkForMatch();
}
};
/**
* Check if two flipped cards match, and keep cards flipped on match
*/
const checkForMatch = () => {
gameState.isProcessing = true;
const [card1, card2] = gameState.flippedCards; // ES6 destructuring
if (card1.data.symbol === card2.data.symbol) {
// Match found!
playSound(cardMatchSound);
announceToScreenReader('Match found!');
setTimeout(() => {
// Mark as matched
card1.element.classList.add('matched');
card2.element.classList.add('matched');
card1.data.matched = true;
card2.data.matched = true;
card1.data.faceUp = true;
card2.data.faceUp = true;
// Update ARIA labels
const cardButton1 = card1.element.querySelector('.card-inner');
const cardButton2 = card2.element.querySelector('.card-inner');
cardButton1.setAttribute('aria-label', `Card ${card1.index + 1}, matched`);
cardButton2.setAttribute('aria-label', `Card ${card2.index + 1}, matched`);
cardButton1.setAttribute('aria-disabled', 'true');
cardButton2.setAttribute('aria-disabled', 'true');
//
gameState.matchedPairs++;
updateStats();
gameState.flippedCards = [];
gameState.isProcessing = false;
saveGameState();
// Check if game is won
checkGameWon();
}, 500);
} else {
// No match - flip back
playSound(cardFailSound);
announceToScreenReader('No match, cards flipping back');
setTimeout(() => {
card1.element.classList.remove('flipped');
card2.element.classList.remove('flipped');
card1.data.faceUp = false;
card2.data.faceUp = false;
// Reset ARIA labels
const cardButton1 = card1.element.querySelector('.card-inner');
const cardButton2 = card2.element.querySelector('.card-inner');
cardButton1.setAttribute('aria-label', `Card ${card1.index + 1}, face down`);
cardButton2.setAttribute('aria-label', `Card ${card2.index + 1}, face down`);
gameState.flippedCards = [];
gameState.isProcessing = false;
saveGameState();
}, 1000);
}
};
/**
* Check if all pairs have been matched
*/
const checkGameWon = () => {
const totalPairs = DIFFICULTY_CONFIG[gameState.difficulty].pairs;
if (gameState.matchedPairs === totalPairs) {
stopTimer();
saveGameState();
setTimeout(() => {
playSound(congratsSound);
showGameOverModal();
}, 500);
}
};
/**
* Show game over modal with stats
*/
const showGameOverModal = () => {
const modal = document.getElementById('gameOverModal');
document.getElementById('finalMoves').textContent = gameState.moves;
document.getElementById('finalTime').textContent = formatTime(gameState.timer);
modal.classList.add('show');
};
/**
* Hide game over modal
*/
const hideGameOverModal = () => {
const modal = document.getElementById('gameOverModal');
modal.classList.remove('show');
};
// ============================================================================
// GAME INITIALIZATION
// ============================================================================
/**
* Initialize a new game with current difficulty
*/
const initGame = () => {
stopTimer();
hideGameOverModal();
const { pairs } = DIFFICULTY_CONFIG[gameState.difficulty];
// Reset game state
gameState = {
...gameState, // ES6 spread operator
cards: createCardData(pairs).map(card => ({
...card,
faceUp: false
})),
flippedCards: [],
matchedPairs: 0,
moves: 0,
timer: 0,
timerInterval: null,
isProcessing: false
};
renderGameBoard();
updateStats();
updateTotalMovesDisplay(getTotalMoves());
saveGameState();
announceToScreenReader(`New ${gameState.difficulty} game started with ${pairs} pairs`);
// Flicker stats once
const statItems = document.querySelectorAll('.stat-item');
statItems.forEach(item => {
item.classList.add('flicker');
setTimeout(() => item.classList.remove('flicker'), 500);
});
};
/**
* Change difficulty level
*/
const changeDifficulty = (level) => {
gameState.difficulty = level;
updateDifficultyButtons(level);
initGame();
};
/**
* Update difficulty button UI state
*/
const updateDifficultyButtons = (level) => {
document.querySelectorAll('.btn-difficulty').forEach(btn => {
const isActive = btn.dataset.level === level;
btn.classList.toggle('active', isActive);
btn.setAttribute('aria-pressed', isActive);
});
};
/**
* Toggle sound effects on/off
*/
const toggleSound = () => {
gameState.soundEnabled = !gameState.soundEnabled;
// Update button UI and ARIA attributes
const soundBtn = document.getElementById('soundToggle');
soundBtn.textContent = gameState.soundEnabled ? '🔊 Sound On' : '🔇 Sound Off';
soundBtn.classList.toggle('sound-off', !gameState.soundEnabled);
soundBtn.setAttribute('aria-pressed', gameState.soundEnabled);
soundBtn.setAttribute('aria-label', `Sound effects ${gameState.soundEnabled ? 'on' : 'off'}`);
announceToScreenReader(`Sound effects turned ${gameState.soundEnabled ? 'on' : 'off'}`);
// Save preference to localStorage
localStorage.setItem('memoryGameSound', gameState.soundEnabled);
};
/**
* Load sound preference from localStorage
*/
const loadSoundPreference = () => {
const savedPref = localStorage.getItem('memoryGameSound');
if (savedPref !== null) {
gameState.soundEnabled = savedPref === 'true';
const soundBtn = document.getElementById('soundToggle');
soundBtn.textContent = gameState.soundEnabled ? '🔊 Sound On' : '🔇 Sound Off';
soundBtn.classList.toggle('sound-off', !gameState.soundEnabled);
soundBtn.setAttribute('aria-pressed', gameState.soundEnabled);
soundBtn.setAttribute('aria-label', `Sound effects ${gameState.soundEnabled ? 'on' : 'off'}`);
}
};
/**
* Change game theme
*/
const changeTheme = (theme) => {
gameState.theme = theme;
applyTheme(theme);
announceToScreenReader(`Theme changed to ${theme}`);
initGame();
};
/**
* Apply theme styles to the UI
*/
const applyTheme = (theme) => {
document.body.classList.remove('theme-default', 'theme-tropical', 'theme-beach', 'theme-sunset');
if (theme !== 'default') {
document.body.classList.add(`theme-${theme}`);
}
const themeSelect = document.getElementById('themeSelect');
if (themeSelect) {
themeSelect.value = theme;
}
};
// ============================================================================
// EVENT LISTENERS SETUP
// ============================================================================
document.addEventListener('DOMContentLoaded', () => {
// Reset button
document.getElementById('resetBtn').addEventListener('click', initGame);
// Reset total moves button
document.getElementById('resetTotalMovesBtn').addEventListener('click', resetTotalMoves);
// Play again button
document.getElementById('playAgainBtn').addEventListener('click', initGame);
// Sound toggle button
document.getElementById('soundToggle').addEventListener('click', toggleSound);
// Theme selector
document.getElementById('themeSelect').addEventListener('change', (e) => {
changeTheme(e.target.value);
});
// Difficulty buttons - using event delegation concept
document.querySelectorAll('.btn-difficulty').forEach(btn => {
btn.addEventListener('click', (e) => {
changeDifficulty(e.target.dataset.level);
});
});
// Arrow key navigation for game board
document.addEventListener('keydown', handleArrowKeyNavigation);
// Load preferences and initialize game on page load
loadSoundPreference();
updateTotalMovesDisplay(getTotalMoves());
const restored = loadGameState();
if (restored) {
applyTheme(gameState.theme);
updateDifficultyButtons(gameState.difficulty);
renderGameBoard();
updateStats();
updateTotalMovesDisplay(getTotalMoves());
if (gameState.moves > 0 && !isGameWon()) {
startTimer();
}
if (isGameWon()) {
showGameOverModal();
}
} else {
initGame();
}
window.addEventListener('storage', (event) => {
if (event.key === TOTAL_MOVES_KEY) {
updateTotalMovesDisplay(getTotalMoves());
}
});
});
// ============================================================================
// CODE EXPLANATIONS FOR ASSIGNMENT
// ============================================================================
/**
* 1. FUNCTIONAL PROGRAMMING CONCEPT (Chapter 11):
* - Lines 42-48: createCardData() function
* - This is a pure function that uses map(), flatMap(), and doesn't mutate state
* - It uses higher-order functions (map, flatMap) which are core FP concepts
* - The function returns a new array without side effects
*
* 2. DOM MANIPULATION:
* - Lines 80-103: renderGameBoard() function
* - Clones the single card template element and creates multiple cards
* - Uses cloneNode(), appendChild(), querySelector() for DOM manipulation
* - Dynamically creates the entire game board from one template element
*
* 3. EVENT HANDLING:
* - Lines 150-175: handleCardClick() function
* - Handles click events on cards
* - Lines 273-283: Event listeners setup using addEventListener
*
* 4. ES6 FEATURES:
* - Arrow functions throughout (=>)
* - const/let declarations instead of var
* - Template literals (`${variable}`)
* - Destructuring: const [card1, card2] = gameState.flippedCards;
* - Spread operator: ...gameState
* - Default parameters could be added if needed
*
* 5. IMPLEMENTED ENHANCEMENTS:
* a) Timer: Tracks game time in seconds, formatted as MM:SS
* b) Difficulty Levels: Three levels (Easy 4x4, Medium 6x6, Hard 8x8)
*/