-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1008 lines (837 loc) · 37.7 KB
/
script.js
File metadata and controls
1008 lines (837 loc) · 37.7 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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class MemoryGame {
constructor() {
this.staticImages = [];
this.userImages = [];
this.gameCards = [];
this.flippedCards = [];
this.matchedPairs = 0;
this.moves = 0;
this.score = 0;
this.timer = 0;
this.timerInterval = null;
this.gameStarted = false;
this.difficulty = 'medium';
this.initializeElements();
this.bindEvents();
this.loadStaticImages();
// Add resize handler for responsive layout
window.addEventListener('resize', () => {
if (this.gameCards.length > 0) {
this.setDynamicLayout(this.gameCards.length);
}
});
}
async loadStaticImages() {
// Try to load image pairs from the static images folder
// Each pair should be named like: image1a.jpg, image1b.jpg or image1a.png, image1b.png
const imageExtensions = ['jpg', 'png'];
this.staticImages = [];
for (let i = 1; i <= 50; i++) {
for (const ext of imageExtensions) {
const imageA = `images/image${i}a.${ext}`;
const imageB = `images/image${i}b.${ext}`;
// Try to load both images in the pair
const [resultA, resultB] = await Promise.allSettled([
this.tryLoadImage(imageA),
this.tryLoadImage(imageB)
]);
// If both images in the pair loaded successfully, add them as a set
if (resultA.status === 'fulfilled' && resultA.value &&
resultB.status === 'fulfilled' && resultB.value) {
this.staticImages.push({
setId: i,
imageA: resultA.value,
imageB: resultB.value
});
}
}
}
// No fallback - only use images from folder
}
tryLoadImage(src) {
return new Promise((resolve) => {
const img = new window.Image();
img.onload = () => {
resolve(src);
};
img.onerror = () => resolve(null);
img.src = src;
});
}
darkenColor(color, percent) {
const num = parseInt(color.replace("#", ""), 16);
const amt = Math.round(2.55 * percent);
const R = (num >> 16) - amt;
const G = (num >> 8 & 0x00FF) - amt;
const B = (num & 0x0000FF) - amt;
return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
(G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
(B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1);
}
playSuccessSound() {
try {
// Create audio context for generating sound
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create a happy ascending melody (like a celebration)
const melody = [
{ freq: 523.25, time: 0.0, duration: 0.15 }, // C5
{ freq: 659.25, time: 0.1, duration: 0.15 }, // E5
{ freq: 783.99, time: 0.2, duration: 0.15 }, // G5
{ freq: 1046.5, time: 0.3, duration: 0.25 } // C6 (octave higher)
];
melody.forEach((note) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(note.freq, audioContext.currentTime);
oscillator.type = 'triangle'; // Warmer, happier sound than sine
// Create bouncy envelope for happy sound
gainNode.gain.setValueAtTime(0, audioContext.currentTime + note.time);
gainNode.gain.linearRampToValueAtTime(0.15, audioContext.currentTime + note.time + 0.02);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + note.time + note.duration);
oscillator.start(audioContext.currentTime + note.time);
oscillator.stop(audioContext.currentTime + note.time + note.duration);
});
// Add a little sparkle effect with higher frequencies
const sparkle = [1318.5, 1568]; // E6, G6
sparkle.forEach((freq, index) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(freq, audioContext.currentTime);
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0, audioContext.currentTime + 0.4 + index * 0.05);
gainNode.gain.linearRampToValueAtTime(0.08, audioContext.currentTime + 0.42 + index * 0.05);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.55 + index * 0.05);
oscillator.start(audioContext.currentTime + 0.4 + index * 0.05);
oscillator.stop(audioContext.currentTime + 0.55 + index * 0.05);
});
} catch (error) {
// Silent fallback if audio context is not supported
console.log('Audio not supported');
}
}
playVictorySound() {
try {
// Create audio context for generating sound
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create an epic victory fanfare with multiple layers
const mainMelody = [
{ freq: 523.25, time: 0.0, duration: 0.3, vol: 0.25 }, // C5
{ freq: 659.25, time: 0.2, duration: 0.3, vol: 0.25 }, // E5
{ freq: 783.99, time: 0.4, duration: 0.3, vol: 0.25 }, // G5
{ freq: 1046.5, time: 0.6, duration: 0.4, vol: 0.3 }, // C6
{ freq: 1318.5, time: 1.0, duration: 0.3, vol: 0.25 }, // E6
{ freq: 1568.0, time: 1.3, duration: 0.4, vol: 0.25 }, // G6
{ freq: 2093.0, time: 1.7, duration: 0.6, vol: 0.3 } // C7 (final triumphant note)
];
// Play main melody with square wave for boldness
mainMelody.forEach((note) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(note.freq, audioContext.currentTime);
oscillator.type = 'square'; // Bold, triumphant sound
// Create powerful envelope
gainNode.gain.setValueAtTime(0, audioContext.currentTime + note.time);
gainNode.gain.linearRampToValueAtTime(note.vol, audioContext.currentTime + note.time + 0.05);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + note.time + note.duration);
oscillator.start(audioContext.currentTime + note.time);
oscillator.stop(audioContext.currentTime + note.time + note.duration);
});
// Add harmonies (fifths)
const harmonies = [
{ freq: 783.99, time: 0.0, duration: 0.3, vol: 0.15 }, // G5
{ freq: 987.77, time: 0.2, duration: 0.3, vol: 0.15 }, // B5
{ freq: 1174.7, time: 0.4, duration: 0.3, vol: 0.15 }, // D6
{ freq: 1568.0, time: 0.6, duration: 0.4, vol: 0.2 }, // G6
{ freq: 1976.0, time: 1.0, duration: 0.3, vol: 0.15 }, // B6
{ freq: 2349.3, time: 1.3, duration: 0.4, vol: 0.15 }, // D7
{ freq: 3136.0, time: 1.7, duration: 0.6, vol: 0.2 } // G7
];
harmonies.forEach((note) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(note.freq, audioContext.currentTime);
oscillator.type = 'triangle';
gainNode.gain.setValueAtTime(0, audioContext.currentTime + note.time);
gainNode.gain.linearRampToValueAtTime(note.vol, audioContext.currentTime + note.time + 0.05);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + note.time + note.duration);
oscillator.start(audioContext.currentTime + note.time);
oscillator.stop(audioContext.currentTime + note.time + note.duration);
});
// Add magical sparkle cascade
const sparkles = [];
for (let i = 0; i < 12; i++) {
sparkles.push({
freq: 1046.5 * Math.pow(2, Math.random() * 2), // Random notes in high range
time: 1.2 + i * 0.08,
duration: 0.15,
vol: 0.08
});
}
sparkles.forEach((note) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(note.freq, audioContext.currentTime);
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0, audioContext.currentTime + note.time);
gainNode.gain.linearRampToValueAtTime(note.vol, audioContext.currentTime + note.time + 0.02);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + note.time + note.duration);
oscillator.start(audioContext.currentTime + note.time);
oscillator.stop(audioContext.currentTime + note.time + note.duration);
});
// Add deep bass foundation
const bassLine = [130.8, 164.8, 196.0, 261.6]; // C3, E3, G3, C4
bassLine.forEach((freq, index) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(freq, audioContext.currentTime);
oscillator.type = 'sine';
const startTime = index * 0.6;
gainNode.gain.setValueAtTime(0, audioContext.currentTime + startTime);
gainNode.gain.linearRampToValueAtTime(0.15, audioContext.currentTime + startTime + 0.1);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + startTime + 0.5);
oscillator.start(audioContext.currentTime + startTime);
oscillator.stop(audioContext.currentTime + startTime + 0.5);
});
} catch (error) {
// Silent fallback if audio context is not supported
console.log('Audio not supported');
}
}
playFailureSound() {
try {
// Create audio context for generating sound
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create a simple "buzz" sound for failure
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
// Low frequency buzz sound
oscillator.frequency.setValueAtTime(150, audioContext.currentTime);
oscillator.type = 'square'; // Harsh, buzzer-like sound
// Quick envelope - very short duration
gainNode.gain.setValueAtTime(0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(0.1, audioContext.currentTime + 0.02);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.2);
} catch (error) {
// Silent fallback if audio context is not supported
console.log('Audio not supported');
}
}
initializeElements() {
this.imageUpload = document.getElementById('imageUpload');
this.uploadCount = document.getElementById('uploadCount');
this.startBtn = document.getElementById('startBtn');
this.resetBtn = document.getElementById('resetBtn');
this.gameBoard = document.getElementById('gameBoard');
this.scoreElement = document.getElementById('score');
this.movesElement = document.getElementById('moves');
this.timerElement = document.getElementById('timer');
this.gameOverModal = document.getElementById('gameOverModal');
this.finalScore = document.getElementById('finalScore');
this.finalMoves = document.getElementById('finalMoves');
this.finalTime = document.getElementById('finalTime');
}
bindEvents() {
this.imageUpload.addEventListener('change', (e) => this.handleImageUpload(e));
this.startBtn.addEventListener('click', () => this.startGame());
this.resetBtn.addEventListener('click', () => this.resetGame());
// Close modal when clicking outside
this.gameOverModal.addEventListener('click', (e) => {
if (e.target === this.gameOverModal) {
this.closeModal();
}
});
}
handleImageUpload(event) {
// Prevent upload during active game
if (this.gameStarted) {
event.target.value = ''; // Clear the file input
return;
}
const files = Array.from(event.target.files);
if (files.length === 0) return;
let loadedImages = 0;
const newImages = [];
files.forEach((file) => {
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
newImages.push(e.target.result);
loadedImages++;
if (loadedImages === files.length) {
this.userImages = [...this.userImages, ...newImages];
}
};
reader.readAsDataURL(file);
}
});
}
startGame() {
this.resetGameState();
// Clean up any existing celebration animations
this.cleanupCelebrationAnimations();
this.createGameCards();
this.renderGameBoard();
this.startTimer();
this.gameStarted = true;
this.startBtn.disabled = true;
// Disable upload functionality during game
const uploadBtn = document.querySelector('.upload-btn');
uploadBtn.disabled = true;
uploadBtn.style.opacity = '0.5';
uploadBtn.style.cursor = 'not-allowed';
}
resetGameState() {
this.gameCards = [];
this.flippedCards = [];
this.matchedPairs = 0;
this.moves = 0;
this.score = 0;
this.timer = 0;
this.gameStarted = false;
this.updateDisplay();
this.stopTimer();
}
createGameCards() {
// Create pairs from image sets and user images
this.gameCards = [];
let cardId = 0;
// Handle static image sets (pairs of different but related images)
this.staticImages.forEach((imageSet) => {
this.gameCards.push({
id: cardId++,
image: imageSet.imageA,
setId: imageSet.setId,
matched: false
});
this.gameCards.push({
id: cardId++,
image: imageSet.imageB,
setId: imageSet.setId,
matched: false
});
});
// Handle uploaded images (create identical pairs)
for (let i = 0; i < this.userImages.length; i++) {
const image = this.userImages[i];
this.gameCards.push({
id: cardId++,
image,
setId: `user_${i}`,
matched: false
});
this.gameCards.push({
id: cardId++,
image,
setId: `user_${i}`,
matched: false
});
}
// Shuffle the cards
this.shuffleArray(this.gameCards);
}
shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
renderGameBoard() {
this.gameBoard.innerHTML = '';
// Calculate dynamic layout based on card count
const cardCount = this.gameCards.length;
this.setDynamicLayout(cardCount);
this.gameCards.forEach((card, index) => {
const cardElement = this.createCardElement(card, index);
this.gameBoard.appendChild(cardElement);
});
}
setDynamicLayout(cardCount) {
const root = document.documentElement;
// Calculate optimal grid columns
let cols = 4;
if (cardCount <= 8) cols = 4;
else if (cardCount <= 16) cols = 4;
else if (cardCount <= 24) cols = 6;
else if (cardCount <= 36) cols = 6;
else if (cardCount <= 50) cols = 8;
else if (cardCount <= 72) cols = 9;
else cols = 10;
// Calculate card size based on screen width and number of columns
const screenWidth = window.innerWidth;
const maxBoardWidth = Math.min(screenWidth * 0.9, 1200);
const cardSize = Math.max(50, Math.min(120, (maxBoardWidth - (cols + 1) * 15) / cols));
// Calculate gap and padding based on card size
const gap = Math.max(5, Math.min(15, cardSize * 0.12));
const padding = Math.max(10, Math.min(20, cardSize * 0.15));
// Calculate board width and container width
const boardWidth = cols * cardSize + (cols - 1) * gap + padding * 2;
const containerWidth = boardWidth + 40; // Extra space for container padding
// Calculate font size based on card size
const fontSize = Math.max(0.8, Math.min(2, cardSize / 60));
// Set CSS variables
root.style.setProperty('--grid-columns', cols);
root.style.setProperty('--card-size', `${cardSize}px`);
root.style.setProperty('--card-gap', `${gap}px`);
root.style.setProperty('--board-padding', `${padding}px`);
root.style.setProperty('--board-width', `${boardWidth}px`);
root.style.setProperty('--container-width', `${containerWidth}px`);
root.style.setProperty('--card-radius', `${Math.max(6, cardSize * 0.1)}px`);
root.style.setProperty('--card-font-size', `${fontSize}em`);
}
createCardElement(card, index) {
const cardDiv = document.createElement('div');
cardDiv.className = 'card';
cardDiv.dataset.index = index;
const cardFront = document.createElement('div');
cardFront.className = 'card-front';
const backImg = document.createElement('img');
backImg.alt = 'גב קלף';
backImg.style.width = '100%';
backImg.style.height = '100%';
backImg.style.objectFit = 'cover';
// Try different image formats for card back
const cardBackFormats = ['png', 'jpg', 'jpeg'];
let formatIndex = 0;
const tryNextFormat = () => {
if (formatIndex < cardBackFormats.length) {
backImg.src = `images/card-back.${cardBackFormats[formatIndex]}`;
formatIndex++;
} else {
// All formats failed, use fallback
cardFront.removeChild(backImg);
cardFront.textContent = '?';
cardFront.style.display = 'flex';
cardFront.style.alignItems = 'center';
cardFront.style.justifyContent = 'center';
cardFront.style.fontSize = '2em';
cardFront.style.color = 'white';
}
};
backImg.onerror = tryNextFormat;
tryNextFormat(); // Start with first format
cardFront.appendChild(backImg);
const cardBack = document.createElement('div');
cardBack.className = 'card-back';
const img = document.createElement('img');
img.src = card.image;
img.alt = 'קלף זיכרון';
cardBack.appendChild(img);
cardDiv.appendChild(cardFront);
cardDiv.appendChild(cardBack);
cardDiv.addEventListener('click', () => this.flipCard(index));
return cardDiv;
}
flipCard(index) {
if (!this.gameStarted) return;
if (this.flippedCards.length >= 2) return;
if (this.gameCards[index].matched) return;
if (this.flippedCards.includes(index)) return;
const cardElement = this.gameBoard.children[index];
cardElement.classList.add('flipped');
this.flippedCards.push(index);
// Play flip sound immediately when card is flipped
this.playCardFlipSound();
if (this.flippedCards.length === 2) {
this.moves++;
this.updateDisplay();
// Check for immediate match and play sound right away
const [firstIndex, secondIndex] = this.flippedCards;
const firstCard = this.gameCards[firstIndex];
const secondCard = this.gameCards[secondIndex];
if (firstCard.setId === secondCard.setId) {
// Play success sound immediately when match is found
this.playSuccessSound();
} else {
// Play failure sound immediately when mismatch is detected
this.playFailureSound();
}
setTimeout(() => {
this.checkMatch();
}, 1000);
}
}
checkMatch() {
const [firstIndex, secondIndex] = this.flippedCards;
const firstCard = this.gameCards[firstIndex];
const secondCard = this.gameCards[secondIndex];
if (firstCard.setId === secondCard.setId) {
// Match found - mark cards as matched
this.gameCards[firstIndex].matched = true;
this.gameCards[secondIndex].matched = true;
const firstCardElement = this.gameBoard.children[firstIndex];
const secondCardElement = this.gameBoard.children[secondIndex];
firstCardElement.classList.add('matched');
secondCardElement.classList.add('matched');
this.flippedCards = [];
this.matchedPairs++;
this.updateScore(100);
if (this.matchedPairs === this.gameCards.length / 2) {
this.gameComplete();
}
} else {
// No match - flip cards back
setTimeout(() => {
const firstCardElement = this.gameBoard.children[firstIndex];
const secondCardElement = this.gameBoard.children[secondIndex];
firstCardElement.classList.remove('flipped');
secondCardElement.classList.remove('flipped');
this.flippedCards = [];
}, 500);
}
}
gameComplete() {
this.stopTimer();
this.gameStarted = false;
this.startBtn.disabled = false;
// Play victory sound when game is completed
this.playVictorySound();
// Start celebration animations
this.startCelebrationAnimations();
// Re-enable upload functionality when game completes
const uploadBtn = document.querySelector('.upload-btn');
uploadBtn.disabled = false;
uploadBtn.style.opacity = '';
uploadBtn.style.cursor = '';
// Calculate bonus score based on time and moves
const timeBonus = Math.max(0, 300 - this.timer);
const moveBonus = Math.max(0, (this.gameCards.length - this.moves) * 10);
this.score += timeBonus + moveBonus;
this.updateDisplay();
// Delay modal show to let animations start
setTimeout(() => {
this.showGameOverModal();
}, 1000);
}
startCelebrationAnimations() {
// Create confetti effect
this.createConfetti();
// Add pulsing effect to score
this.animateScoreCounter();
// Make all matched cards sparkle
this.sparkleMatchedCards();
// Add screen flash effect
this.createScreenFlash();
}
createConfetti() {
const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9', '#F8C471', '#82E0AA'];
const confettiContainer = document.createElement('div');
confettiContainer.className = 'confetti-container';
confettiContainer.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
z-index: 9999;
overflow: hidden;
`;
document.body.appendChild(confettiContainer);
// Create 50 confetti pieces
for (let i = 0; i < 50; i++) {
const confetti = document.createElement('div');
const color = colors[Math.floor(Math.random() * colors.length)];
const size = Math.random() * 10 + 5;
const startX = Math.random() * window.innerWidth;
const duration = Math.random() * 3 + 2;
const delay = Math.random() * 2;
confetti.style.cssText = `
position: absolute;
width: ${size}px;
height: ${size}px;
background: ${color};
left: ${startX}px;
top: -10px;
border-radius: ${Math.random() > 0.5 ? '50%' : '0'};
animation: confettiFall ${duration}s ${delay}s ease-out forwards;
transform: rotate(${Math.random() * 360}deg);
`;
confettiContainer.appendChild(confetti);
}
// Add CSS animation keyframes
if (!document.getElementById('confetti-styles')) {
const style = document.createElement('style');
style.id = 'confetti-styles';
style.textContent = `
@keyframes confettiFall {
0% {
transform: translateY(-10px) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(100vh) rotate(720deg);
opacity: 0;
}
}
@keyframes scoreGlow {
0%, 100% {
transform: scale(1);
color: inherit;
text-shadow: none;
}
50% {
transform: scale(1.2);
color: #FFD700;
text-shadow: 0 0 20px rgba(255, 215, 0, 0.8);
}
}
@keyframes cardSparkle {
0%, 100% {
filter: brightness(1) saturate(1);
transform: scale(1);
}
50% {
filter: brightness(1.3) saturate(1.5);
transform: scale(1.05);
}
}
@keyframes screenFlash {
0%, 100% { opacity: 0.1; }
50% { opacity: 0.3; }
}
`;
document.head.appendChild(style);
}
// Store reference to confetti container for cleanup on reset/new game
this.confettiContainer = confettiContainer;
// Create continuous confetti generation
this.confettiInterval = setInterval(() => {
if (this.confettiContainer && this.confettiContainer.parentNode) {
const confetti = document.createElement('div');
const color = colors[Math.floor(Math.random() * colors.length)];
const size = Math.random() * 10 + 5;
const startX = Math.random() * window.innerWidth;
const duration = Math.random() * 3 + 2;
confetti.style.cssText = `
position: absolute;
width: ${size}px;
height: ${size}px;
background: ${color};
left: ${startX}px;
top: -10px;
border-radius: ${Math.random() > 0.5 ? '50%' : '0'};
animation: confettiFall ${duration}s ease-out forwards;
transform: rotate(${Math.random() * 360}deg);
`;
this.confettiContainer.appendChild(confetti);
// Remove individual confetti pieces after they fall
setTimeout(() => {
if (confetti && confetti.parentNode) {
confetti.parentNode.removeChild(confetti);
}
}, duration * 1000 + 500);
}
}, 300);
}
animateScoreCounter() {
const scoreElement = this.scoreElement;
scoreElement.style.animation = 'scoreGlow 2s ease-in-out infinite';
}
sparkleMatchedCards() {
const matchedCards = document.querySelectorAll('.card.matched');
matchedCards.forEach((card, index) => {
setTimeout(() => {
card.style.animation = 'cardSparkle 1.5s ease-in-out infinite';
}, index * 100);
});
}
createScreenFlash() {
const flash = document.createElement('div');
flash.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: radial-gradient(circle, rgba(255,215,0,0.3) 0%, rgba(255,215,0,0) 70%);
pointer-events: none;
z-index: 9998;
animation: screenFlash 4s ease-in-out infinite;
`;
document.body.appendChild(flash);
// Store reference for cleanup on reset/new game
this.screenFlash = flash;
}
showGameOverModal() {
// Add celebratory content to modal
this.finalScore.textContent = this.score;
this.finalMoves.textContent = this.moves;
this.finalTime.textContent = this.formatTime(this.timer);
const modalContent = this.gameOverModal.querySelector('.modal-content');
// Add floating animation keyframe if not exists
if (!document.getElementById('modal-animations')) {
const style = document.createElement('style');
style.id = 'modal-animations';
style.textContent = `
@keyframes modalBounceIn {
0% {
transform: translate(-50%, -50%) scale(0.3);
opacity: 0;
}
50% {
transform: translate(-50%, -50%) scale(1.1);
}
100% {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
}
`;
document.head.appendChild(style);
}
// Animate modal entrance
modalContent.style.animation = 'modalBounceIn 0.6s ease-out';
this.gameOverModal.style.display = 'block';
}
closeModal() {
this.gameOverModal.style.display = 'none';
}
resetGame() {
this.resetGameState();
this.gameBoard.innerHTML = '';
this.startBtn.disabled = false;
// Clean up persistent celebration animations
this.cleanupCelebrationAnimations();
// Re-enable upload functionality
const uploadBtn = document.querySelector('.upload-btn');
uploadBtn.disabled = false;
uploadBtn.style.opacity = '';
uploadBtn.style.cursor = '';
}
cleanupCelebrationAnimations() {
// Stop confetti generation
if (this.confettiInterval) {
clearInterval(this.confettiInterval);
this.confettiInterval = null;
}
// Remove confetti container
if (this.confettiContainer && this.confettiContainer.parentNode) {
this.confettiContainer.parentNode.removeChild(this.confettiContainer);
this.confettiContainer = null;
}
// Remove screen flash
if (this.screenFlash && this.screenFlash.parentNode) {
this.screenFlash.parentNode.removeChild(this.screenFlash);
this.screenFlash = null;
}
// Reset score glow animation
if (this.scoreElement) {
this.scoreElement.style.animation = '';
}
// Reset card sparkle animations
const matchedCards = document.querySelectorAll('.card.matched');
matchedCards.forEach(card => {
card.style.animation = '';
});
}
startTimer() {
this.stopTimer();
this.timerInterval = setInterval(() => {
this.timer++;
this.updateDisplay();
}, 1000);
}
stopTimer() {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
}
formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
updateDisplay() {
this.scoreElement.textContent = this.score;
this.movesElement.textContent = this.moves;
this.timerElement.textContent = this.formatTime(this.timer);
}
playCardFlipSound() {
try {
// Create audio context for generating sound
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create a short, subtle "flip" sound
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
// Quick ascending tone for flip sound
oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(600, audioContext.currentTime + 0.05);
oscillator.type = 'triangle'; // Soft, pleasant sound
// Very quick envelope - short duration
gainNode.gain.setValueAtTime(0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(0.03, audioContext.currentTime + 0.01);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.08);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.08);
} catch (error) {
// Silent fallback if audio context is not supported
console.log('Audio not supported');
}
}
updateScore(points) {
this.score += points;
this.updateDisplay();
}
}
// Initialize the game when the page loads
document.addEventListener('DOMContentLoaded', () => {
const game = new MemoryGame();
});
// Add drag and drop functionality
document.addEventListener('DOMContentLoaded', () => {
const uploadArea = document.querySelector('.file-upload');
const fileInput = document.getElementById('imageUpload');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
uploadArea.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, unhighlight, false);
});
function highlight() {
uploadArea.style.background = '#f0f8ff';
uploadArea.style.border = '2px dashed #4CAF50';
uploadArea.style.borderRadius = '15px';
uploadArea.style.padding = '10px';
}
function unhighlight() {
uploadArea.style.background = '';
uploadArea.style.border = '';
uploadArea.style.borderRadius = '';
uploadArea.style.padding = '';
}
uploadArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
const dt = e.dataTransfer;