-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgames.js
More file actions
1694 lines (1438 loc) · 54.1 KB
/
Copy pathgames.js
File metadata and controls
1694 lines (1438 loc) · 54.1 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
// Games Module - Handles all game functionality
class GamesManager {
constructor() {
this.currentGame = null;
this.gameTimers = {};
this.gameData = {
stats: {
totalGamesPlayed: 0,
gameStreak: 0,
totalScore: 0,
averageTime: 0
},
games: {
'8queens': { bestScore: 0, attempts: 0, completed: 0 },
'sudoku': { completed: 0, bestTime: null },
'colorpattern': { bestLevel: 0, bestScore: 0 },
'2048': { highScore: 0, bestTile: 0 },
'memory': { bestMoves: null, completed: 0 },
'snake': { highScore: 0, longest: 0 }
},
recentGames: [],
achievements: []
};
this.loadGameData();
this.initializeGames();
}
// Initialize all games
initializeGames() {
// Use enhanced 8 Queens with Colors implementation if available
if (typeof EightQueensGameEnhanced !== 'undefined') {
this.queens = new EightQueensGameEnhanced();
} else {
this.queens = new EightQueensGame();
}
this.sudoku = new SudokuGame();
this.colorPattern = new ColorPatternGame();
this.game2048 = new Game2048();
this.memory = new MemoryGame();
this.snake = new SnakeGame();
this.updateGameStats();
this.loadRecentGames();
}
// Start a specific game
startGame(gameType) {
console.log('Starting game:', gameType);
switch(gameType) {
case '8queens':
this.openModal('queensGameModal');
this.queens.startGame();
break;
case 'sudoku':
this.openModal('sudokuGameModal');
this.sudoku.startGame();
break;
case 'colorpattern':
this.openModal('colorPatternGameModal');
this.colorPattern.startGame();
break;
case '2048':
this.openModal('2048GameModal');
this.game2048.startGame();
break;
case 'memory':
this.openModal('memoryGameModal');
this.memory.startGame();
break;
case 'snake':
this.openModal('snakeGameModal');
this.snake.startGame();
break;
}
this.currentGame = gameType;
this.startGameTimer(gameType);
}
// Game timer functionality
startGameTimer(gameType) {
if (this.gameTimers[gameType]) {
clearInterval(this.gameTimers[gameType].interval);
}
this.gameTimers[gameType] = {
startTime: Date.now(),
interval: null
};
// Start timer display for applicable games
if (['8queens', 'sudoku', 'memory'].includes(gameType)) {
const timerElement = document.getElementById(`${gameType === '8queens' ? 'queens' : gameType}Timer`);
if (timerElement) {
this.gameTimers[gameType].interval = setInterval(() => {
const elapsed = Math.floor((Date.now() - this.gameTimers[gameType].startTime) / 1000);
timerElement.textContent = this.formatTime(elapsed);
}, 1000);
}
}
}
// Stop game timer
stopGameTimer(gameType) {
if (this.gameTimers[gameType]) {
clearInterval(this.gameTimers[gameType].interval);
const elapsed = Math.floor((Date.now() - this.gameTimers[gameType].startTime) / 1000);
delete this.gameTimers[gameType];
return elapsed;
}
return 0;
}
// Format time display
formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
// Game completion handler
onGameComplete(gameType, result) {
const elapsed = this.stopGameTimer(gameType);
// Update game-specific stats
this.updateGameStats(gameType, result, elapsed);
// Add to recent games
this.addRecentGame(gameType, result, elapsed);
// Update UI
this.updateGameStatsDisplay();
// Save data
this.saveGameData();
console.log(`Game ${gameType} completed:`, result);
}
// Update game statistics
updateGameStats(gameType = null, result = null, elapsed = 0) {
if (gameType && result) {
this.gameData.stats.totalGamesPlayed++;
// Update game-specific stats
const gameStats = this.gameData.games[gameType];
if (result.won) {
gameStats.completed++;
if (elapsed > 0 && (!gameStats.bestTime || elapsed < gameStats.bestTime)) {
gameStats.bestTime = elapsed;
}
}
if (result.score) {
this.gameData.stats.totalScore += result.score;
if (result.score > gameStats.highScore) {
gameStats.highScore = result.score;
}
}
// Update game-specific metrics
if (gameType === '8queens') {
gameStats.attempts++;
if (result.score && result.score > gameStats.bestScore) {
gameStats.bestScore = result.score;
}
} else if (gameType === 'colorpattern') {
if (result.level > gameStats.bestLevel) {
gameStats.bestLevel = result.level;
}
if (result.score > gameStats.bestScore) {
gameStats.bestScore = result.score;
}
} else if (gameType === '2048') {
if (result.bestTile > gameStats.bestTile) {
gameStats.bestTile = result.bestTile;
}
} else if (gameType === 'memory') {
if (!gameStats.bestMoves || result.moves < gameStats.bestMoves) {
gameStats.bestMoves = result.moves;
}
} else if (gameType === 'snake') {
if (result.length > gameStats.longest) {
gameStats.longest = result.length;
}
}
}
// Calculate average time
const totalCompletedGames = Object.values(this.gameData.games)
.reduce((sum, game) => sum + game.completed, 0);
if (totalCompletedGames > 0) {
this.gameData.stats.averageTime = Math.floor(
this.gameData.stats.totalScore / totalCompletedGames
);
}
}
// Update game stats display
updateGameStatsDisplay() {
const stats = this.gameData.stats;
const games = this.gameData.games;
// Update overview stats
document.getElementById('totalGamesPlayed').textContent = stats.totalGamesPlayed;
document.getElementById('gameStreak').textContent = stats.gameStreak;
document.getElementById('totalScore').textContent = stats.totalScore;
document.getElementById('averageTime').textContent = this.formatTime(stats.averageTime);
// Update individual game stats
const queensBestScoreEl = document.getElementById('queens-best-score');
if (queensBestScoreEl) {
queensBestScoreEl.textContent = `Best Score: ${games['8queens'].bestScore || '--'}`;
}
const queensAttemptsEl = document.getElementById('queens-attempts');
if (queensAttemptsEl) {
queensAttemptsEl.textContent = `Attempts: ${games['8queens'].attempts}`;
}
document.getElementById('sudoku-completed').textContent =
`Completed: ${games.sudoku.completed}`;
document.getElementById('sudoku-best-time').textContent =
`Best: ${games.sudoku.bestTime ? this.formatTime(games.sudoku.bestTime) : '--'}`;
document.getElementById('colorpattern-best-level').textContent =
`Best Level: ${games.colorpattern.bestLevel}`;
document.getElementById('colorpattern-best-score').textContent =
`Best Score: ${games.colorpattern.bestScore}`;
document.getElementById('2048-high-score').textContent =
`High Score: ${games['2048'].highScore}`;
document.getElementById('2048-best-tile').textContent =
`Best Tile: ${games['2048'].bestTile}`;
document.getElementById('memory-best-moves').textContent =
`Best: ${games.memory.bestMoves ? games.memory.bestMoves + ' moves' : '-- moves'}`;
document.getElementById('memory-completed').textContent =
`Completed: ${games.memory.completed}`;
document.getElementById('snake-high-score').textContent =
`High Score: ${games.snake.highScore}`;
document.getElementById('snake-longest').textContent =
`Longest: ${games.snake.longest}`;
}
// Add recent game
addRecentGame(gameType, result, elapsed) {
const recentGame = {
type: gameType,
result: result,
elapsed: elapsed,
timestamp: new Date().toISOString()
};
this.gameData.recentGames.unshift(recentGame);
if (this.gameData.recentGames.length > 10) {
this.gameData.recentGames.pop();
}
}
// Load recent games display
loadRecentGames() {
const container = document.getElementById('recentGamesList');
if (!container) return;
if (this.gameData.recentGames.length === 0) {
container.innerHTML = '<p>No recent games yet. Start playing to see your game history!</p>';
return;
}
container.innerHTML = this.gameData.recentGames.map(game => `
<div class="recent-game-item">
<div class="game-name">${this.getGameDisplayName(game.type)}</div>
<div class="game-result">${game.result.won ? '🏆 Won' : '❌ Lost'}</div>
<div class="game-time">${this.formatTime(game.elapsed)}</div>
<div class="game-date">${new Date(game.timestamp).toLocaleDateString()}</div>
</div>
`).join('');
}
// Get game display name
getGameDisplayName(gameType) {
const names = {
'8queens': '8 Queens',
'sudoku': 'Sudoku',
'colorpattern': 'Color Pattern',
'2048': '2048',
'memory': 'Memory Cards',
'snake': 'Snake'
};
return names[gameType] || gameType;
}
// Modal functionality
openModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'block';
}
}
closeModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'none';
}
// Stop any running game timer
Object.keys(this.gameTimers).forEach(gameType => {
this.stopGameTimer(gameType);
});
}
// Data persistence
saveGameData() {
localStorage.setItem('gamesData', JSON.stringify(this.gameData));
}
loadGameData() {
const saved = localStorage.getItem('gamesData');
if (saved) {
this.gameData = { ...this.gameData, ...JSON.parse(saved) };
}
}
}
// 8 Queens Game Implementation
class EightQueensGame {
constructor() {
this.board = Array(8).fill().map(() => Array(8).fill(false));
this.queens = [];
this.conflicts = 0;
}
startGame() {
this.reset();
this.renderBoard();
this.setupEventListeners();
}
reset() {
this.board = Array(8).fill().map(() => Array(8).fill(false));
this.queens = [];
this.conflicts = 0;
this.updateProgress();
}
renderBoard() {
const boardElement = document.getElementById('queensBoard');
if (!boardElement) return;
boardElement.innerHTML = '';
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const square = document.createElement('div');
square.className = `queens-square ${(row + col) % 2 === 0 ? 'light' : 'dark'}`;
square.dataset.row = row;
square.dataset.col = col;
if (this.board[row][col]) {
square.classList.add('queen');
square.textContent = '♛';
}
if (this.isConflict(row, col)) {
square.classList.add('conflict');
}
square.addEventListener('click', () => this.handleSquareClick(row, col));
boardElement.appendChild(square);
}
}
}
handleSquareClick(row, col) {
if (this.board[row][col]) {
// Remove queen
this.board[row][col] = false;
this.queens = this.queens.filter(q => q.row !== row || q.col !== col);
} else {
// Add queen
this.board[row][col] = true;
this.queens.push({ row, col });
}
this.calculateConflicts();
this.renderBoard();
this.updateProgress();
this.checkWin();
}
isConflict(row, col) {
if (!this.board[row][col]) return false;
for (let queen of this.queens) {
if (queen.row === row && queen.col === col) continue;
// Check row, column, and diagonals
if (queen.row === row || queen.col === col ||
Math.abs(queen.row - row) === Math.abs(queen.col - col)) {
return true;
}
}
return false;
}
calculateConflicts() {
this.conflicts = 0;
for (let queen of this.queens) {
if (this.isConflict(queen.row, queen.col)) {
this.conflicts++;
}
}
this.conflicts = Math.floor(this.conflicts / 2); // Each conflict is counted twice
}
updateProgress() {
document.getElementById('queensPlaced').textContent = this.queens.length;
document.getElementById('queensConflicts').textContent = this.conflicts;
}
checkWin() {
if (this.queens.length === 8 && this.conflicts === 0) {
window.gamesManager.onGameComplete('8queens', { won: true, score: 100 });
alert('Congratulations! You solved the 8 Queens puzzle!');
this.reset();
}
}
setupEventListeners() {
document.getElementById('queensResetBtn').onclick = () => {
this.reset();
this.renderBoard();
};
document.getElementById('queensSolveBtn').onclick = () => {
this.autoSolve();
};
document.getElementById('queensHintBtn').onclick = () => {
this.showHint();
};
}
autoSolve() {
this.reset();
// Simple backtracking solution
this.solveRecursive(0);
this.renderBoard();
this.updateProgress();
}
solveRecursive(col) {
if (col >= 8) return true;
for (let row = 0; row < 8; row++) {
if (this.isSafe(row, col)) {
this.board[row][col] = true;
this.queens.push({ row, col });
if (this.solveRecursive(col + 1)) return true;
this.board[row][col] = false;
this.queens.pop();
}
}
return false;
}
isSafe(row, col) {
for (let queen of this.queens) {
if (queen.row === row ||
Math.abs(queen.row - row) === Math.abs(queen.col - col)) {
return false;
}
}
return true;
}
showHint() {
// Find a safe position for the next queen
for (let col = 0; col < 8; col++) {
if (this.queens.some(q => q.col === col)) continue;
for (let row = 0; row < 8; row++) {
if (this.isSafe(row, col)) {
alert(`Try placing a queen at row ${row + 1}, column ${col + 1}`);
return;
}
}
}
alert('No safe positions available. Try removing some queens first.');
}
}
// Sudoku Game Implementation
class SudokuGame {
constructor() {
this.board = Array(9).fill().map(() => Array(9).fill(0));
this.solution = Array(9).fill().map(() => Array(9).fill(0));
this.given = Array(9).fill().map(() => Array(9).fill(false));
this.selectedCell = null;
}
startGame() {
this.generatePuzzle();
this.renderBoard();
this.setupEventListeners();
}
generatePuzzle() {
// Generate a complete valid Sudoku board
this.board = Array(9).fill().map(() => Array(9).fill(0));
this.fillBoard();
this.solution = this.board.map(row => [...row]);
// Remove numbers based on difficulty
const difficulty = document.getElementById('sudokuDifficulty').value;
const cellsToRemove = difficulty === 'easy' ? 40 : difficulty === 'medium' ? 50 : 60;
this.given = Array(9).fill().map(() => Array(9).fill(true));
for (let i = 0; i < cellsToRemove; i++) {
let row, col;
do {
row = Math.floor(Math.random() * 9);
col = Math.floor(Math.random() * 9);
} while (!this.given[row][col]);
this.board[row][col] = 0;
this.given[row][col] = false;
}
}
fillBoard() {
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (this.board[row][col] === 0) {
const shuffled = [...numbers].sort(() => Math.random() - 0.5);
for (let num of shuffled) {
if (this.isValidMove(row, col, num)) {
this.board[row][col] = num;
if (this.fillBoard()) return true;
this.board[row][col] = 0;
}
}
return false;
}
}
}
return true;
}
renderBoard() {
const boardElement = document.getElementById('sudokuBoard');
if (!boardElement) return;
boardElement.innerHTML = '';
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
const cell = document.createElement('div');
cell.className = 'sudoku-cell';
cell.dataset.row = row;
cell.dataset.col = col;
if (this.given[row][col]) {
cell.classList.add('given');
cell.textContent = this.board[row][col];
} else if (this.board[row][col] !== 0) {
cell.textContent = this.board[row][col];
}
if (this.selectedCell && this.selectedCell.row === row && this.selectedCell.col === col) {
cell.classList.add('selected');
}
// Add visual feedback for invalid numbers
if (!this.given[row][col] && this.board[row][col] !== 0) {
if (!this.isValidMove(row, col, this.board[row][col])) {
cell.classList.add('invalid');
} else {
cell.classList.add('valid-user');
}
}
cell.addEventListener('click', () => this.selectCell(row, col));
boardElement.appendChild(cell);
}
}
}
selectCell(row, col) {
if (this.given[row][col]) return;
this.selectedCell = { row, col };
this.highlightRelatedCells(row, col);
this.highlightSameNumbers(row, col);
this.renderBoard();
}
highlightRelatedCells(row, col) {
// Clear previous highlights
document.querySelectorAll('.sudoku-cell.related, .sudoku-cell.same-number, .sudoku-cell.box-highlight').forEach(cell => {
cell.classList.remove('related', 'same-number', 'box-highlight');
});
// Highlight row, column, and 3x3 box
for (let i = 0; i < 9; i++) {
// Highlight row
const rowCell = document.querySelector(`[data-row="${row}"][data-col="${i}"]`);
if (rowCell && i !== col) rowCell.classList.add('related');
// Highlight column
const colCell = document.querySelector(`[data-row="${i}"][data-col="${col}"]`);
if (colCell && i !== row) colCell.classList.add('related');
}
// Highlight 3x3 box with stronger highlighting
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let r = boxRow; r < boxRow + 3; r++) {
for (let c = boxCol; c < boxCol + 3; c++) {
if (r !== row || c !== col) {
const boxCell = document.querySelector(`[data-row="${r}"][data-col="${c}"]`);
if (boxCell) {
// Check if already highlighted as row/column
if (!boxCell.classList.contains('related')) {
boxCell.classList.add('box-highlight');
}
}
}
}
}
}
// Highlight cells with the same number as selected cell
highlightSameNumbers(row, col) {
const selectedNumber = this.board[row][col];
if (selectedNumber === 0) return;
// Find all cells with the same number
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (this.board[r][c] === selectedNumber && (r !== row || c !== col)) {
const cell = document.querySelector(`[data-row="${r}"][data-col="${c}"]`);
if (cell) {
cell.classList.add('same-number');
}
}
}
}
}
enterNumber(num) {
if (!this.selectedCell) return;
const { row, col } = this.selectedCell;
if (this.given[row][col]) return;
// Clear error highlights from previous attempt
document.querySelectorAll('.sudoku-cell.error').forEach(cell => {
cell.classList.remove('error');
});
this.board[row][col] = num;
// Check if this move creates conflicts
if (num !== 0 && !this.isValidMove(row, col, num)) {
const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
if (cell) {
cell.classList.add('error');
// Show error message briefly
this.showErrorMessage(`Invalid move! ${num} already exists in this row, column, or box.`);
// Remove error class after animation
setTimeout(() => {
cell.classList.remove('error');
}, 2000);
}
} else if (num !== 0) {
// Valid move feedback
this.showSuccessMessage('Good move!');
}
this.renderBoard();
this.checkWin();
}
isValidMove(row, col, num) {
// Check row
for (let c = 0; c < 9; c++) {
if (c !== col && this.board[row][c] === num) return false;
}
// Check column
for (let r = 0; r < 9; r++) {
if (r !== row && this.board[r][col] === num) return false;
}
// Check 3x3 box
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let r = boxRow; r < boxRow + 3; r++) {
for (let c = boxCol; c < boxCol + 3; c++) {
if ((r !== row || c !== col) && this.board[r][c] === num) return false;
}
}
return true;
}
checkWin() {
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (this.board[row][col] === 0) return false;
if (!this.isValidMove(row, col, this.board[row][col])) return false;
}
}
window.gamesManager.onGameComplete('sudoku', { won: true, score: 500 });
alert('Congratulations! You completed the Sudoku puzzle!');
}
setupEventListeners() {
// Number pad buttons
document.querySelectorAll('#sudokuGameModal .number-btn').forEach(btn => {
btn.addEventListener('click', () => {
const num = parseInt(btn.dataset.number);
this.enterNumber(num);
});
});
// Game control buttons
document.getElementById('sudokuNewBtn').onclick = () => {
this.startGame();
};
document.getElementById('sudokuCheckBtn').onclick = () => {
this.checkBoard();
};
document.getElementById('sudokuHintBtn').onclick = () => {
this.showHint();
};
// Difficulty change
document.getElementById('sudokuDifficulty').onchange = () => {
this.startGame();
};
// Keyboard input support
document.addEventListener('keydown', (e) => {
if (document.getElementById('sudokuGameModal').style.display === 'block' && this.selectedCell) {
const num = parseInt(e.key);
if (num >= 1 && num <= 9) {
this.enterNumber(num);
} else if (e.key === 'Delete' || e.key === 'Backspace') {
this.enterNumber(0);
} else if (e.key === 'Escape') {
this.selectedCell = null;
this.clearHighlights();
this.renderBoard();
}
}
});
}
// Clear all highlights
clearHighlights() {
document.querySelectorAll('.sudoku-cell.related, .sudoku-cell.same-number, .sudoku-cell.box-highlight').forEach(cell => {
cell.classList.remove('related', 'same-number', 'box-highlight');
});
}
// Show error message
showErrorMessage(message) {
this.showMessage(message, 'error');
}
// Show success message
showSuccessMessage(message) {
this.showMessage(message, 'success');
}
// Show temporary message
showMessage(message, type = 'info') {
// Create message element if it doesn't exist
let messageEl = document.getElementById('sudokuMessage');
if (!messageEl) {
messageEl = document.createElement('div');
messageEl.id = 'sudokuMessage';
messageEl.className = 'sudoku-message';
const gameArea = document.querySelector('#sudokuGameModal .game-area');
if (gameArea) gameArea.appendChild(messageEl);
}
messageEl.textContent = message;
messageEl.className = `sudoku-message ${type}`;
messageEl.style.display = 'block';
// Hide after 2 seconds
setTimeout(() => {
messageEl.style.display = 'none';
}, 2000);
}
checkBoard() {
let errors = 0;
document.querySelectorAll('.sudoku-cell').forEach(cell => {
cell.classList.remove('error');
});
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (this.board[row][col] !== 0 && !this.isValidMove(row, col, this.board[row][col])) {
const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
if (cell) {
cell.classList.add('error');
errors++;
}
}
}
}
// Show results with better feedback
if (errors === 0) {
// Flash all cells green briefly
document.querySelectorAll('.sudoku-cell').forEach(cell => {
cell.style.background = '#d5f4e6';
});
setTimeout(() => {
this.renderBoard();
}, 500);
alert('🎉 Perfect! No errors found!');
} else {
alert(`⚠️ Found ${errors} error(s). Check the highlighted red cells.`);
// Remove error highlighting after 5 seconds
setTimeout(() => {
document.querySelectorAll('.sudoku-cell.error').forEach(cell => {
cell.classList.remove('error');
});
}, 5000);
}
}
showHint() {
if (!this.selectedCell) {
this.showErrorMessage('💡 Please select an empty cell first to get a hint.');
return;
}
const { row, col } = this.selectedCell;
if (this.given[row][col]) {
this.showErrorMessage('💡 This cell already contains the correct number.');
return;
}
if (this.board[row][col] !== 0) {
this.showErrorMessage('💡 This cell is already filled. Clear it first or select an empty cell.');
return;
}
const correctNumber = this.solution[row][col];
// Highlight the cell with hint styling
const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
if (cell) {
cell.classList.add('hint');
cell.textContent = correctNumber;
// Remove hint after 3 seconds
setTimeout(() => {
cell.classList.remove('hint');
if (this.board[row][col] === 0) {
cell.textContent = '';
}
}, 3000);
}
this.showSuccessMessage(`💡 Hint: The correct number for this cell is ${correctNumber}`);
}
}
// Color Pattern Game Implementation
class ColorPatternGame {
constructor() {
this.sequence = [];
this.playerSequence = [];
this.level = 1;
this.score = 0;
this.isPlaying = false;
this.isPlayerTurn = false;
this.colors = [
{ name: 'red', color: '#e74c3c', sound: 'C' },
{ name: 'blue', color: '#3498db', sound: 'D' },
{ name: 'green', color: '#2ecc71', sound: 'E' },
{ name: 'yellow', color: '#f1c40f', sound: 'F' }
];
}
startGame() {
this.sequence = [];
this.playerSequence = [];
this.level = 1;
this.score = 0;
this.isPlaying = true;
this.isPlayerTurn = false;
this.renderBoard();
this.updateDisplay();
this.setupEventListeners();
setTimeout(() => {
this.nextLevel();
}, 1000);
}
renderBoard() {
const boardElement = document.getElementById('colorPatternBoard');
if (!boardElement) return;
boardElement.innerHTML = this.colors.map((color, index) => `
<div class="color-button"
data-color="${index}"
style="background-color: ${color.color}">
<span class="color-name">${color.name}</span>
</div>
`).join('');
}
updateDisplay() {
document.getElementById('colorPatternLevel').textContent = `Level: ${this.level}`;
document.getElementById('colorPatternScore').textContent = `Score: ${this.score}`;
document.getElementById('colorPatternStatus').textContent = this.getStatusMessage();
}
getStatusMessage() {
if (!this.isPlaying) return 'Press Start to play';
if (!this.isPlayerTurn) return 'Watch the pattern...';
return `Your turn! Repeat ${this.sequence.length} colors`;
}
nextLevel() {
this.isPlayerTurn = false;
this.playerSequence = [];
// Add new color to sequence
const newColor = Math.floor(Math.random() * this.colors.length);
this.sequence.push(newColor);
this.updateDisplay();
this.playSequence();
}
playSequence() {
let index = 0;
const playNext = () => {
if (index < this.sequence.length) {
this.flashButton(this.sequence[index], () => {
index++;
setTimeout(playNext, 600);
});
} else {
// Sequence finished, player's turn
this.isPlayerTurn = true;
this.updateDisplay();
}
};
this.sequenceTimeout = setTimeout(playNext, 500);
}
flashButton(colorIndex, callback) {
const button = document.querySelector(`[data-color="${colorIndex}"]`);
if (!button) {
if (callback) callback();
return;
}
button.classList.add('active');
button.style.pointerEvents = 'none'; // Prevent clicks during flash
setTimeout(() => {
button.classList.remove('active');
button.style.pointerEvents = 'auto'; // Re-enable clicks
if (callback) callback();
}, 400);
}
handlePlayerInput(colorIndex) {
if (!this.isPlayerTurn || !this.isPlaying) return;