-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
734 lines (637 loc) · 20.5 KB
/
script.js
File metadata and controls
734 lines (637 loc) · 20.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
// Game Configuration
const config = {
emojiArray: [
"🐶",
"🐱",
"🐻",
"🐼",
"🐨",
"🦁",
"🐯",
"🦊",
"🐸",
"🐵",
"🦄",
"🐷",
"🐮",
"🐹",
"🐭",
"🐰",
"🦋",
"🐢",
"🐠",
"🐙",
"🦀",
"🐳",
"🦉",
"🐦",
"🦇",
"🐝",
"🦄",
"🦕",
"🦖",
"🐊",
],
singlePlayer: {
initialCards: 6,
maxCards: 20,
cardsIncrement: 2,
initialMoves: 10,
movesIncrement: 3,
baseScore: 100,
bonusMultiplier: 1.5,
},
twoPlayer: {
initialCards: 12,
maxCards: 24,
},
sounds: {
flipVolume: 0.3,
matchVolume: 0.5,
winVolume: 0.7,
loseVolume: 0.7,
levelUpVolume: 0.6,
},
animations: {
flipDuration: 600,
matchDelay: 500,
noMatchDelay: 1000,
},
};
// Game State
const gameState = {
currentPage: "home",
singlePlayer: {
level: 1,
movesLeft: 0,
totalMoves: 0,
matchedPairs: 0,
totalPairs: 0,
score: 0,
cards: [],
flippedCards: [],
isPaused: false,
timer: null,
timeLimit: 0,
timeLeft: 0,
},
twoPlayer: {
currentPlayer: 1,
player1Score: 0,
player2Score: 0,
cards: [],
flippedCards: [],
canFlip: true,
consecutiveMatches: 0,
},
highScores: JSON.parse(localStorage.getItem("memoryGameHighScores")) || {
singlePlayer: { level: 1, score: 0 },
twoPlayer: { player1: 0, player2: 0 },
},
soundEnabled: true,
lastCardIndex: -1, // To prevent double-clicking the same card
};
// DOM Elements
const pages = {
home: document.getElementById("home-page"),
singlePlayer: document.getElementById("single-player-page"),
twoPlayer: document.getElementById("two-player-page"),
gameOver: document.getElementById("game-over-page"),
};
const buttons = {
singlePlayer: document.getElementById("single-player-btn"),
twoPlayer: document.getElementById("two-player-btn"),
howToPlay: document.getElementById("how-to-play-btn"),
spPause: document.getElementById("sp-pause-btn"),
spReset: document.getElementById("sp-reset-btn"),
spHome: document.getElementById("sp-home-btn"),
tpReset: document.getElementById("tp-reset-btn"),
tpHome: document.getElementById("tp-home-btn"),
playAgain: document.getElementById("play-again-btn"),
goHome: document.getElementById("go-home-btn"),
resume: document.getElementById("resume-btn"),
quit: document.getElementById("quit-btn"),
closeInstructions: document.getElementById("close-instructions-btn"),
confirmYes: document.getElementById("confirm-yes"),
confirmNo: document.getElementById("confirm-no"),
};
const gameElements = {
currentLevel: document.getElementById("current-level"),
movesLeft: document.getElementById("moves-left"),
currentScore: document.getElementById("current-score"),
levelProgress: document.getElementById("level-progress"),
spGameBoard: document.getElementById("sp-game-board"),
currentPlayer: document.getElementById("current-player"),
player1Score: document.getElementById("player1-score"),
player2Score: document.getElementById("player2-score"),
tpGameBoard: document.getElementById("tp-game-board"),
resultMessage: document.getElementById("result-message"),
levelReached: document.getElementById("level-reached"),
scoreAchieved: document.getElementById("score-achieved"),
movesUsed: document.getElementById("moves-used"),
winnerDisplay: document.getElementById("winner-display"),
highScoreMessage: document.getElementById("high-score-message"),
confirmMessage: document.getElementById("confirm-message"),
};
const modals = {
pause: document.getElementById("pause-modal"),
howToPlay: document.getElementById("how-to-play-modal"),
confirm: document.getElementById("confirm-modal"),
};
const sounds = {
flip: document.getElementById("flip-sound"),
match: document.getElementById("match-sound"),
win: document.getElementById("win-sound"),
lose: document.getElementById("lose-sound"),
levelUp: document.getElementById("level-up-sound"),
};
// Initialize game
function init() {
setSoundVolumes();
setupEventListeners();
showPage("home");
}
// Set up event listeners
function setupEventListeners() {
// Navigation buttons
buttons.singlePlayer.addEventListener("click", () => startSinglePlayerGame());
buttons.twoPlayer.addEventListener("click", () => startTwoPlayerGame());
buttons.howToPlay.addEventListener("click", () => showModal("howToPlay"));
buttons.spHome.addEventListener("click", () => confirmLeaveGame());
buttons.tpHome.addEventListener("click", () => confirmLeaveGame());
buttons.playAgain.addEventListener("click", playAgain);
buttons.goHome.addEventListener("click", () => showPage("home"));
buttons.closeInstructions.addEventListener("click", () =>
hideModal("howToPlay")
);
// Game control buttons
buttons.spPause.addEventListener("click", togglePause);
buttons.spReset.addEventListener("click", () => confirmResetGame());
buttons.tpReset.addEventListener("click", () => confirmResetGame());
buttons.resume.addEventListener("click", togglePause);
buttons.quit.addEventListener("click", () => {
togglePause();
confirmLeaveGame();
});
// Confirmation modal buttons
buttons.confirmYes.addEventListener("click", handleConfirmYes);
buttons.confirmNo.addEventListener("click", handleConfirmNo);
// Handle window resize
window.addEventListener("resize", handleWindowResize);
}
// Set sound volumes
function setSoundVolumes() {
sounds.flip.volume = config.sounds.flipVolume;
sounds.match.volume = config.sounds.matchVolume;
sounds.win.volume = config.sounds.winVolume;
sounds.lose.volume = config.sounds.loseVolume;
sounds.levelUp.volume = config.sounds.levelUpVolume;
}
// Show specific page
function showPage(pageName) {
// Hide all pages
Object.values(pages).forEach((page) => {
page.classList.remove("active");
});
// Show requested page
pages[pageName].classList.add("active");
gameState.currentPage = pageName;
// Reset any game state if going to home
if (pageName === "home") {
resetGameState();
}
}
// Show modal
function showModal(modalName) {
modals[modalName].classList.add("active");
}
// Hide modal
function hideModal(modalName) {
modals[modalName].classList.remove("active");
}
// Confirm before leaving game
function confirmLeaveGame() {
gameElements.confirmMessage.textContent =
"Are you sure you want to leave the game? Your progress will be lost.";
showModal("confirm");
}
// Confirm before resetting game
function confirmResetGame() {
gameElements.confirmMessage.textContent =
"Are you sure you want to reset the game?";
showModal("confirm");
}
// Handle confirmation yes
function handleConfirmYes() {
hideModal("confirm");
if (gameElements.confirmMessage.textContent.includes("leave")) {
showPage("home");
} else {
if (gameState.currentPage === "singlePlayer") {
resetSinglePlayerGame();
} else {
resetTwoPlayerGame();
}
}
}
// Handle confirmation no
function handleConfirmNo() {
hideModal("confirm");
}
// Reset all game state
function resetGameState() {
// Clear any ongoing timers
if (gameState.singlePlayer.timer) {
clearInterval(gameState.singlePlayer.timer);
}
// Reset single player state
gameState.singlePlayer = {
level: 1,
movesLeft: 0,
totalMoves: 0,
matchedPairs: 0,
totalPairs: 0,
score: 0,
cards: [],
flippedCards: [],
isPaused: false,
timer: null,
timeLimit: 0,
timeLeft: 0,
};
// Reset two player state
gameState.twoPlayer = {
currentPlayer: 1,
player1Score: 0,
player2Score: 0,
cards: [],
flippedCards: [],
canFlip: true,
consecutiveMatches: 0,
};
gameState.lastCardIndex = -1;
}
// Handle window resize
function handleWindowResize() {
// Adjust card sizes based on window width
const cardElements = document.querySelectorAll(".card");
const cardSize = calculateCardSize();
cardElements.forEach((card) => {
card.style.width = `${cardSize}px`;
card.style.height = `${cardSize}px`;
});
}
// Calculate optimal card size based on window width
function calculateCardSize() {
const minCardSize = 70;
const maxCardSize = 120;
const windowWidth = window.innerWidth;
if (windowWidth < 480) return minCardSize;
if (windowWidth < 768) return 80;
if (windowWidth < 1024) return 100;
return maxCardSize;
}
// Single Player Game Functions
function startSinglePlayerGame() {
resetGameState();
gameState.singlePlayer.level = 1;
gameState.singlePlayer.score = 0;
gameState.singlePlayer.totalMoves = 0;
setupSinglePlayerLevel();
showPage("singlePlayer");
}
function setupSinglePlayerLevel() {
const level = gameState.singlePlayer.level;
// Calculate number of cards for this level
const cardCount = Math.min(
config.singlePlayer.initialCards +
(level - 1) * config.singlePlayer.cardsIncrement,
config.singlePlayer.maxCards
);
// Set moves for this level
gameState.singlePlayer.movesLeft =
config.singlePlayer.initialMoves +
(level - 1) * config.singlePlayer.movesIncrement;
gameState.singlePlayer.totalPairs = cardCount / 2;
gameState.singlePlayer.matchedPairs = 0;
gameState.singlePlayer.flippedCards = [];
gameState.lastCardIndex = -1;
// Update UI
gameElements.currentLevel.textContent = level;
gameElements.movesLeft.textContent = gameState.singlePlayer.movesLeft;
gameElements.currentScore.textContent = gameState.singlePlayer.score;
gameElements.levelProgress.style.width = "0%";
// Create cards
createCards(gameElements.spGameBoard, cardCount, handleSinglePlayerCardClick);
}
function handleSinglePlayerCardClick(card, index) {
// Prevent multiple clicks on the same card
if (index === gameState.lastCardIndex) return;
gameState.lastCardIndex = index;
if (gameState.singlePlayer.isPaused) return;
if (gameState.singlePlayer.flippedCards.length >= 2) return;
if (card.classList.contains("flipped") || card.classList.contains("matched"))
return;
// Play flip sound
playSound(sounds.flip);
// Flip card
card.classList.add("flipped");
gameState.singlePlayer.flippedCards.push({ card, index });
// Check for match if two cards are flipped
if (gameState.singlePlayer.flippedCards.length === 2) {
const [card1, card2] = gameState.singlePlayer.flippedCards;
// Decrement moves
gameState.singlePlayer.movesLeft--;
gameState.singlePlayer.totalMoves++;
gameElements.movesLeft.textContent = gameState.singlePlayer.movesLeft;
// Check for match
if (card1.card.textContent === card2.card.textContent) {
// Match found
playSound(sounds.match);
gameState.singlePlayer.matchedPairs++;
// Calculate score for this match
const baseScore =
config.singlePlayer.baseScore * gameState.singlePlayer.level;
const bonusScore = Math.floor(
baseScore *
((gameState.singlePlayer.movesLeft /
(config.singlePlayer.initialMoves +
(gameState.singlePlayer.level - 1) *
config.singlePlayer.movesIncrement)) *
config.singlePlayer.bonusMultiplier)
);
gameState.singlePlayer.score += baseScore + bonusScore;
gameElements.currentScore.textContent = gameState.singlePlayer.score;
// Update progress
const progress =
(gameState.singlePlayer.matchedPairs /
gameState.singlePlayer.totalPairs) *
100;
gameElements.levelProgress.style.width = `${progress}%`;
// Mark cards as matched
setTimeout(() => {
card1.card.classList.add("matched");
card2.card.classList.add("matched");
gameState.singlePlayer.flippedCards = [];
gameState.lastCardIndex = -1;
// Check if level is complete
if (
gameState.singlePlayer.matchedPairs ===
gameState.singlePlayer.totalPairs
) {
levelComplete();
}
}, config.animations.matchDelay);
} else {
// No match
setTimeout(() => {
card1.card.classList.remove("flipped");
card2.card.classList.remove("flipped");
gameState.singlePlayer.flippedCards = [];
gameState.lastCardIndex = -1;
// Check if moves are exhausted
if (gameState.singlePlayer.movesLeft <= 0) {
setTimeout(() => gameOver(false), config.animations.noMatchDelay);
}
}, config.animations.noMatchDelay);
}
}
}
function levelComplete() {
// Play win sound
playSound(sounds.levelUp);
// Update high score if needed
if (gameState.singlePlayer.score > gameState.highScores.singlePlayer.score) {
gameState.highScores.singlePlayer.score = gameState.singlePlayer.score;
gameState.highScores.singlePlayer.level = gameState.singlePlayer.level;
localStorage.setItem(
"memoryGameHighScores",
JSON.stringify(gameState.highScores)
);
}
// Advance to next level after delay
setTimeout(() => {
gameState.singlePlayer.level++;
setupSinglePlayerLevel();
}, 1500);
}
function resetSinglePlayerGame() {
setupSinglePlayerLevel();
}
function togglePause() {
gameState.singlePlayer.isPaused = !gameState.singlePlayer.isPaused;
if (gameState.singlePlayer.isPaused) {
showModal("pause");
} else {
hideModal("pause");
}
}
// Two Player Game Functions
function startTwoPlayerGame() {
resetGameState();
gameState.twoPlayer.currentPlayer = 1;
gameState.twoPlayer.player1Score = 0;
gameState.twoPlayer.player2Score = 0;
// Update UI
gameElements.currentPlayer.textContent = gameState.twoPlayer.currentPlayer;
gameElements.player1Score.textContent = gameState.twoPlayer.player1Score;
gameElements.player2Score.textContent = gameState.twoPlayer.player2Score;
// Create cards
createCards(
gameElements.tpGameBoard,
config.twoPlayer.initialCards,
handleTwoPlayerCardClick
);
showPage("twoPlayer");
}
function handleTwoPlayerCardClick(card, index) {
// Prevent multiple clicks on the same card
if (index === gameState.lastCardIndex) return;
gameState.lastCardIndex = index;
if (!gameState.twoPlayer.canFlip) return;
if (gameState.twoPlayer.flippedCards.length >= 2) return;
if (card.classList.contains("flipped") || card.classList.contains("matched"))
return;
// Play flip sound
playSound(sounds.flip);
// Flip card
card.classList.add("flipped");
gameState.twoPlayer.flippedCards.push({ card, index });
// Check for match if two cards are flipped
if (gameState.twoPlayer.flippedCards.length === 2) {
gameState.twoPlayer.canFlip = false;
const [card1, card2] = gameState.twoPlayer.flippedCards;
// Check for match
if (card1.card.textContent === card2.card.textContent) {
// Match found
playSound(sounds.match);
gameState.twoPlayer.consecutiveMatches++;
// Update score for current player
if (gameState.twoPlayer.currentPlayer === 1) {
gameState.twoPlayer.player1Score++;
gameElements.player1Score.textContent =
gameState.twoPlayer.player1Score;
} else {
gameState.twoPlayer.player2Score++;
gameElements.player2Score.textContent =
gameState.twoPlayer.player2Score;
}
// Mark cards as matched
setTimeout(() => {
card1.card.classList.add("matched");
card2.card.classList.add("matched");
gameState.twoPlayer.flippedCards = [];
gameState.lastCardIndex = -1;
gameState.twoPlayer.canFlip = true;
// Check if game is complete
const totalPairs = config.twoPlayer.initialCards / 2;
const totalMatched =
gameState.twoPlayer.player1Score + gameState.twoPlayer.player2Score;
if (totalMatched === totalPairs) {
setTimeout(() => gameOver(true), config.animations.matchDelay);
} else if (gameState.twoPlayer.consecutiveMatches >= 1) {
// Player gets another turn if they made a match
gameState.twoPlayer.canFlip = true;
}
}, config.animations.matchDelay);
} else {
// No match - switch players
setTimeout(() => {
card1.card.classList.remove("flipped");
card2.card.classList.remove("flipped");
gameState.twoPlayer.flippedCards = [];
gameState.lastCardIndex = -1;
gameState.twoPlayer.consecutiveMatches = 0;
// Switch player
gameState.twoPlayer.currentPlayer =
gameState.twoPlayer.currentPlayer === 1 ? 2 : 1;
gameElements.currentPlayer.textContent =
gameState.twoPlayer.currentPlayer;
gameState.twoPlayer.canFlip = true;
}, config.animations.noMatchDelay);
}
}
}
function resetTwoPlayerGame() {
startTwoPlayerGame();
}
// Common Game Functions
function createCards(boardElement, cardCount, clickHandler) {
// Clear existing cards
boardElement.innerHTML = "";
// Create pairs of emojis
const emojis = [...config.emojiArray]
.sort(() => 0.5 - Math.random())
.slice(0, cardCount / 2);
const cardValues = [...emojis, ...emojis].sort(() => 0.5 - Math.random());
// Create card elements
cardValues.forEach((value, index) => {
const card = document.createElement("div");
card.className = "card";
card.dataset.index = index;
// Set card size based on window width
const cardSize = calculateCardSize();
card.style.width = `${cardSize}px`;
card.style.height = `${cardSize}px`;
const cardFront = document.createElement("div");
cardFront.className = "card-face card-front";
cardFront.textContent = value;
const cardBack = document.createElement("div");
cardBack.className = "card-face card-back";
card.appendChild(cardFront);
card.appendChild(cardBack);
card.addEventListener("click", () => clickHandler(card, index));
boardElement.appendChild(card);
});
}
function playSound(soundElement) {
if (!gameState.soundEnabled) return;
soundElement.currentTime = 0;
soundElement.play().catch((e) => {
console.log("Audio play failed:", e);
// Auto-play was prevented, disable sounds for this session
gameState.soundEnabled = false;
});
}
// Game Over Functions
function gameOver(isTwoPlayer) {
if (isTwoPlayer) {
// Determine winner
let winner;
let isNewHighScore = false;
if (gameState.twoPlayer.player1Score > gameState.twoPlayer.player2Score) {
winner = "Player 1";
if (
gameState.twoPlayer.player1Score >
gameState.highScores.twoPlayer.player1
) {
gameState.highScores.twoPlayer.player1 =
gameState.twoPlayer.player1Score;
isNewHighScore = true;
}
} else if (
gameState.twoPlayer.player2Score > gameState.twoPlayer.player1Score
) {
winner = "Player 2";
if (
gameState.twoPlayer.player2Score >
gameState.highScores.twoPlayer.player2
) {
gameState.highScores.twoPlayer.player2 =
gameState.twoPlayer.player2Score;
isNewHighScore = true;
}
} else {
winner = "It's a tie!";
}
// Save high scores if needed
if (isNewHighScore) {
localStorage.setItem(
"memoryGameHighScores",
JSON.stringify(gameState.highScores)
);
}
// Play appropriate sound
if (winner.includes("1") || winner.includes("2")) {
playSound(sounds.win);
}
// Update UI
gameElements.resultMessage.textContent = "Game Completed!";
gameElements.winnerDisplay.textContent = `Winner: ${winner}`;
gameElements.levelReached.textContent = "";
gameElements.movesUsed.textContent = "";
if (isNewHighScore) {
gameElements.highScoreMessage.textContent = "New High Score!";
} else {
gameElements.highScoreMessage.textContent = "";
}
} else {
// Single player game over
playSound(sounds.lose);
gameElements.resultMessage.textContent = "Game Over";
gameElements.levelReached.textContent = `Level Reached: ${gameState.singlePlayer.level}`;
gameElements.scoreAchieved.textContent = `Score: ${gameState.singlePlayer.score}`;
gameElements.movesUsed.textContent = `Total Moves: ${gameState.singlePlayer.totalMoves}`;
gameElements.winnerDisplay.textContent = "";
if (
gameState.singlePlayer.score === gameState.highScores.singlePlayer.score
) {
gameElements.highScoreMessage.textContent = "🏆 High Score! 🏆";
} else {
gameElements.highScoreMessage.textContent = "";
}
}
showPage("gameOver");
}
function playAgain() {
if (
gameState.currentPage === "singlePlayer" ||
gameElements.resultMessage.textContent.includes("Single Player")
) {
startSinglePlayerGame();
} else {
startTwoPlayerGame();
}
}
// Initialize the game when DOM is loaded
document.addEventListener("DOMContentLoaded", init);