-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1101 lines (928 loc) · 34.2 KB
/
script.js
File metadata and controls
1101 lines (928 loc) · 34.2 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
// Game Constants and Configuration
const PIECE_TYPES = {
RAJA: 'king',
MANTRI: 'queen',
RATHA: 'rook',
GAJA: 'bishop',
ASHVA: 'knight',
PADATI: 'pawn'
};
const BOT_CONFIGS = {
beginner: { depth: 1, elo: 800, name: "Beginner Bot" },
intermediate: { depth: 2, elo: 1200, name: "Intermediate Bot" },
advanced: { depth: 3, elo: 1600, name: "Advanced Bot" },
expert: { depth: 4, elo: 2000, name: "Expert Bot" }
};
const THEMES = {
modern: { light: '#f0d9b5', dark: '#b58863' },
classic: { light: '#f0d0a0', dark: '#a07855' },
dark: { light: '#8ca2ad', dark: '#4a6572' }
};
// Game State
let gameState = {
board: [],
currentPlayer: 'white',
selectedPiece: null,
validMoves: [],
moveHistory: [],
moveNotation: [],
gameOver: false,
winner: null,
check: false,
checkmate: false,
stalemate: false,
boardFlipped: false,
moveHistoryVisible: true,
lastMove: null,
draggingPiece: null,
dragOffset: { x: 0, y: 0 },
// Settings
soundEnabled: true,
musicEnabled: false,
currentTheme: 'modern',
colorBlindMode: false,
// Game configuration
opponent: 'human',
botDifficulty: 'intermediate',
ruleSet: 'jump',
// Timers
timerWhite: 600,
timerBlack: 600,
timerInterval: null,
lastTimerUpdate: Date.now(),
// Stats
playerStats: {
elo: 1200,
wins: 0,
losses: 0,
draws: 0
},
// Achievements
achievements: [
{ name: "First Win", description: "Win your first game", unlocked: false },
{ name: "Checkmate Master", description: "Deliver 10 checkmates", unlocked: false },
{ name: "Pawn Promoter", description: "Promote 5 pawns", unlocked: false },
{ name: "Bot Slayer", description: "Defeat all bot levels", unlocked: false }
]
};
// Initialize the game
function initGame() {
loadStats();
createBoard();
setupPieces();
startTimer();
updateDisplay();
showMessage("Game started! White's turn.");
}
function createBoard() {
const board = document.getElementById('chess-board');
const coordinates = document.getElementById('board-coordinates');
// Clear existing board
board.innerHTML = '';
coordinates.innerHTML = '';
// Create files coordinates (a-h)
const filesContainer = document.createElement('div');
filesContainer.className = 'coord-files';
filesContainer.style.gridTemplateColumns = 'repeat(8, 1fr)';
filesContainer.style.display = 'grid';
filesContainer.style.marginBottom = '5px';
for (let i = 0; i < 8; i++) {
const file = document.createElement('div');
file.className = 'coord-file';
file.textContent = String.fromCharCode(97 + (gameState.boardFlipped ? 7 - i : i));
filesContainer.appendChild(file);
}
// Create ranks coordinates (1-8)
const ranksContainer = document.createElement('div');
ranksContainer.className = 'coord-ranks';
ranksContainer.style.display = 'flex';
ranksContainer.style.flexDirection = 'column';
ranksContainer.style.gap = 'calc(100% / 8 - 1em)';
ranksContainer.style.position = 'absolute';
ranksContainer.style.left = '-25px';
ranksContainer.style.top = '0';
ranksContainer.style.height = '100%';
ranksContainer.style.justifyContent = 'space-around';
for (let i = 0; i < 8; i++) {
const rank = document.createElement('div');
rank.className = 'coord-rank';
rank.textContent = gameState.boardFlipped ? (i + 1) : (8 - i);
ranksContainer.appendChild(rank);
}
coordinates.appendChild(filesContainer);
coordinates.appendChild(ranksContainer);
// Create squares
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const square = document.createElement('div');
square.className = 'square';
square.dataset.row = row;
square.dataset.col = col;
// Set square color based on theme and position
const isLight = (row + col) % 2 === 0;
square.classList.add(isLight ? 'light' : 'dark');
// Add event listeners
square.addEventListener('click', () => handleSquareClick(row, col));
square.addEventListener('dragover', handleDragOver);
square.addEventListener('drop', (e) => handleDrop(e, row, col));
board.appendChild(square);
}
}
}
function setupPieces() {
// Clear existing pieces
gameState.board = Array(8).fill().map(() => Array(8).fill(null));
// Setup pawns
for (let col = 0; col < 8; col++) {
gameState.board[1][col] = { type: PIECE_TYPES.PADATI, color: 'black', row: 1, col: col };
gameState.board[6][col] = { type: PIECE_TYPES.PADATI, color: 'white', row: 6, col: col };
}
// Setup back rows
const backRow = [
PIECE_TYPES.RATHA, PIECE_TYPES.ASHVA, PIECE_TYPES.GAJA, PIECE_TYPES.MANTRI,
PIECE_TYPES.RAJA, PIECE_TYPES.GAJA, PIECE_TYPES.ASHVA, PIECE_TYPES.RATHA
];
for (let col = 0; col < 8; col++) {
gameState.board[0][col] = { type: backRow[col], color: 'black', row: 0, col: col };
gameState.board[7][col] = { type: backRow[col], color: 'white', row: 7, col: col };
}
renderPieces();
}
function renderPieces() {
// Clear all pieces from board
document.querySelectorAll('.piece').forEach(piece => piece.remove());
// Render pieces
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece) {
const square = getSquareElement(row, col);
if (square) {
const pieceElement = createPieceElement(piece, row, col);
square.appendChild(pieceElement);
}
}
}
}
// Highlight last move
highlightLastMove();
// Highlight check
if (gameState.check) {
highlightCheck();
}
}
function createPieceElement(piece, row, col) {
const pieceElement = document.createElement('div');
pieceElement.className = `piece ${piece.color} ${piece.type}`;
pieceElement.textContent = getPieceSymbol(piece.type);
pieceElement.draggable = true;
pieceElement.addEventListener('dragstart', (e) => handleDragStart(e, piece, row, col));
pieceElement.addEventListener('click', (e) => {
e.stopPropagation();
handlePieceClick(row, col);
});
return pieceElement;
}
function getPieceSymbol(type) {
const symbols = {
[PIECE_TYPES.RAJA]: 'K',
[PIECE_TYPES.MANTRI]: 'Q',
[PIECE_TYPES.RATHA]: 'R',
[PIECE_TYPES.GAJA]: 'B',
[PIECE_TYPES.ASHVA]: 'N',
[PIECE_TYPES.PADATI]: 'P'
};
return symbols[type] || '?';
}
function getSquareElement(row, col) {
if (gameState.boardFlipped) {
row = 7 - row;
col = 7 - col;
}
return document.querySelector(`.square[data-row="${row}"][data-col="${col}"]`);
}
// Event Handlers
function handleSquareClick(row, col) {
if (gameState.gameOver) return;
if (gameState.selectedPiece) {
// Try to move to this square
const [selectedRow, selectedCol] = gameState.selectedPiece;
if (isValidMove(selectedRow, selectedCol, row, col)) {
makeMove(selectedRow, selectedCol, row, col);
clearSelection();
} else {
// Select different piece or clear selection
const piece = gameState.board[row][col];
if (piece && piece.color === gameState.currentPlayer) {
selectPiece(row, col);
} else {
clearSelection();
}
}
} else {
// Select piece if it's the player's turn
const piece = gameState.board[row][col];
if (piece && piece.color === gameState.currentPlayer) {
selectPiece(row, col);
}
}
}
function handlePieceClick(row, col) {
if (gameState.gameOver) return;
const piece = gameState.board[row][col];
if (piece && piece.color === gameState.currentPlayer) {
selectPiece(row, col);
}
}
function handleDragStart(e, piece, row, col) {
if (gameState.gameOver || piece.color !== gameState.currentPlayer) {
e.preventDefault();
return;
}
gameState.draggingPiece = { piece, row, col };
e.dataTransfer.setData('text/plain', ''); // Required for Firefox
e.dataTransfer.effectAllowed = 'move';
// Add visual feedback
setTimeout(() => {
e.target.style.opacity = '0.4';
}, 0);
}
function handleDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
}
function handleDrop(e, targetRow, targetCol) {
e.preventDefault();
if (!gameState.draggingPiece) return;
const { piece, row: fromRow, col: fromCol } = gameState.draggingPiece;
gameState.draggingPiece = null;
// Reset opacity
document.querySelectorAll('.piece').forEach(p => p.style.opacity = '1');
if (isValidMove(fromRow, fromCol, targetRow, targetCol)) {
makeMove(fromRow, fromCol, targetRow, targetCol);
}
clearSelection();
}
function selectPiece(row, col) {
gameState.selectedPiece = [row, col];
gameState.validMoves = getValidMoves(row, col);
// Update visual selection
clearHighlights();
highlightSelectedSquare();
highlightValidMoves();
}
function clearSelection() {
gameState.selectedPiece = null;
gameState.validMoves = [];
clearHighlights();
}
function clearHighlights() {
document.querySelectorAll('.square').forEach(square => {
square.classList.remove('selected', 'valid-move');
});
}
function highlightSelectedSquare() {
if (gameState.selectedPiece) {
const [row, col] = gameState.selectedPiece;
const square = getSquareElement(row, col);
if (square) square.classList.add('selected');
}
}
function highlightValidMoves() {
gameState.validMoves.forEach(([row, col]) => {
const square = getSquareElement(row, col);
if (square) square.classList.add('valid-move');
});
}
function highlightLastMove() {
if (gameState.lastMove) {
const [from, to] = gameState.lastMove;
[from, to].forEach(([row, col]) => {
const square = getSquareElement(row, col);
if (square) square.classList.add('last-move');
});
}
}
function highlightCheck() {
// Find king in check and highlight its square
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.type === PIECE_TYPES.RAJA && piece.color === gameState.currentPlayer) {
const square = getSquareElement(row, col);
if (square) square.classList.add('check');
break;
}
}
}
}
// Move Validation and Game Logic
function isValidMove(fromRow, fromCol, toRow, toCol) {
return gameState.validMoves.some(([r, c]) => r === toRow && c === toCol);
}
function getValidMoves(row, col) {
const piece = gameState.board[row][col];
if (!piece) return [];
const rawMoves = getRawMoves(row, col);
return rawMoves.filter(([r, c]) => !wouldBeInCheck(piece, r, c));
}
function getRawMoves(row, col) {
const piece = gameState.board[row][col];
if (!piece) return [];
const moves = [];
switch (piece.type) {
case PIECE_TYPES.RAJA: // King
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const newRow = row + dr;
const newCol = col + dc;
if (isInBoard(newRow, newCol)) {
const target = gameState.board[newRow][newCol];
if (!target || target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
}
break;
case PIECE_TYPES.MANTRI: // Minister/Queen
for (const [dr, dc] of [[-1, -1], [-1, 1], [1, -1], [1, 1]]) {
const newRow = row + dr;
const newCol = col + dc;
if (isInBoard(newRow, newCol)) {
const target = gameState.board[newRow][newCol];
if (!target || target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
break;
case PIECE_TYPES.RATHA: // Chariot/Rook
for (const [dr, dc] of [[0, 1], [1, 0], [0, -1], [-1, 0]]) {
for (let i = 1; i < 8; i++) {
const newRow = row + dr * i;
const newCol = col + dc * i;
if (!isInBoard(newRow, newCol)) break;
const target = gameState.board[newRow][newCol];
if (!target) {
moves.push([newRow, newCol]);
} else {
if (target.color !== piece.color) {
moves.push([newRow, newCol]);
}
break;
}
}
}
break;
case PIECE_TYPES.GAJA: // Elephant/Bishop
if (gameState.ruleSet === 'jump') {
for (const [dr, dc] of [[-2, -2], [-2, 2], [2, -2], [2, 2]]) {
const newRow = row + dr;
const newCol = col + dc;
if (isInBoard(newRow, newCol)) {
const target = gameState.board[newRow][newCol];
if (!target || target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
} else {
// Non-jump mode - check intermediate square
for (const [dr, dc] of [[-2, -2], [-2, 2], [2, -2], [2, 2]]) {
const midRow = row + dr / 2;
const midCol = col + dc / 2;
const newRow = row + dr;
const newCol = col + dc;
if (isInBoard(newRow, newCol) && isInBoard(midRow, midCol) &&
!gameState.board[midRow][midCol]) {
const target = gameState.board[newRow][newCol];
if (!target || target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
}
break;
case PIECE_TYPES.ASHVA: // Horse/Knight
for (const [dr, dc] of [[-2, -1], [-2, 1], [-1, -2], [-1, 2],
[1, -2], [1, 2], [2, -1], [2, 1]]) {
const newRow = row + dr;
const newCol = col + dc;
if (isInBoard(newRow, newCol)) {
const target = gameState.board[newRow][newCol];
if (!target || target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
break;
case PIECE_TYPES.PADATI: // Pawn
const direction = piece.color === 'white' ? -1 : 1;
const newRow = row + direction;
// Forward move
if (isInBoard(newRow, col) && !gameState.board[newRow][col]) {
moves.push([newRow, col]);
}
// Captures
for (const dc of [-1, 1]) {
const newCol = col + dc;
if (isInBoard(newRow, newCol)) {
const target = gameState.board[newRow][newCol];
if (target && target.color !== piece.color) {
moves.push([newRow, newCol]);
}
}
}
break;
}
return moves;
}
function wouldBeInCheck(piece, newRow, newCol) {
const oldRow = piece.row;
const oldCol = piece.col;
const captured = gameState.board[newRow][newCol];
// Make temporary move
gameState.board[oldRow][oldCol] = null;
gameState.board[newRow][newCol] = { ...piece, row: newRow, col: newCol };
const inCheck = isInCheck(piece.color);
// Undo temporary move
gameState.board[oldRow][oldCol] = piece;
gameState.board[newRow][newCol] = captured;
return inCheck;
}
function isInCheck(color) {
let kingPos = null;
// Find king
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.type === PIECE_TYPES.RAJA && piece.color === color) {
kingPos = [row, col];
break;
}
}
if (kingPos) break;
}
if (!kingPos) return false;
const opponent = color === 'white' ? 'black' : 'white';
// Check if any opponent piece can capture the king
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.color === opponent) {
const moves = getRawMoves(row, col);
if (moves.some(([r, c]) => r === kingPos[0] && c === kingPos[1])) {
return true;
}
}
}
}
return false;
}
function isCheckmate(color) {
if (!isInCheck(color)) return false;
// Check if any move can get out of check
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.color === color) {
const moves = getValidMoves(row, col);
if (moves.length > 0) return false;
}
}
}
return true;
}
function isStalemate(color) {
if (isInCheck(color)) return false;
// Check if any legal move exists
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.color === color) {
const moves = getValidMoves(row, col);
if (moves.length > 0) return false;
}
}
}
return true;
}
function makeMove(fromRow, fromCol, toRow, toCol) {
const piece = gameState.board[fromRow][fromCol];
const captured = gameState.board[toRow][toCol];
// Update board
gameState.board[toRow][toCol] = { ...piece, row: toRow, col: toCol };
gameState.board[fromRow][fromCol] = null;
// Handle pawn promotion
if (piece.type === PIECE_TYPES.PADATI && (toRow === 0 || toRow === 7)) {
gameState.board[toRow][toCol].type = PIECE_TYPES.MANTRI;
showMessage("Pawn promoted to Minister!");
}
// Update game state
gameState.lastMove = [[fromRow, fromCol], [toRow, toCol]];
gameState.moveHistory.push({ from: [fromRow, fromCol], to: [toRow, toCol], captured });
// Add move notation
const notation = getMoveNotation(fromRow, fromCol, toRow, toCol, !!captured);
gameState.moveNotation.push(notation);
// Switch turns
gameState.currentPlayer = gameState.currentPlayer === 'white' ? 'black' : 'white';
// Check game state
gameState.check = isInCheck(gameState.currentPlayer);
if (gameState.check) {
gameState.checkmate = isCheckmate(gameState.currentPlayer);
if (gameState.checkmate) {
gameState.gameOver = true;
gameState.winner = gameState.currentPlayer === 'white' ? 'black' : 'white';
showMessage(`Checkmate! ${gameState.winner} wins!`);
endGame();
} else {
showMessage("Check!");
}
} else {
gameState.stalemate = isStalemate(gameState.currentPlayer);
if (gameState.stalemate) {
gameState.gameOver = true;
showMessage("Stalemate! Game is a draw.");
endGame();
}
}
// Update display
updateDisplay();
// Bot move
if (!gameState.gameOver && gameState.opponent === 'bot' && gameState.currentPlayer === 'black') {
setTimeout(makeBotMove, 500);
}
}
function getMoveNotation(fromRow, fromCol, toRow, toCol, captured) {
const piece = gameState.board[toRow][toCol];
const files = 'abcdefgh';
const ranks = '87654321';
const fromSquare = `${files[fromCol]}${ranks[fromRow]}`;
const toSquare = `${files[toCol]}${ranks[toRow]}`;
const pieceSymbols = {
[PIECE_TYPES.RAJA]: 'K',
[PIECE_TYPES.MANTRI]: 'Q',
[PIECE_TYPES.RATHA]: 'R',
[PIECE_TYPES.GAJA]: 'B',
[PIECE_TYPES.ASHVA]: 'N',
[PIECE_TYPES.PADATI]: ''
};
const symbol = pieceSymbols[piece.type];
const captureSymbol = captured ? 'x' : '';
if (piece.type === PIECE_TYPES.PADATI) {
return captured ? `${fromSquare[0]}x${toSquare}` : toSquare;
} else {
return `${symbol}${captureSymbol}${toSquare}`;
}
}
function makeBotMove() {
const allMoves = [];
// Get all possible moves
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.color === 'black') {
const moves = getValidMoves(row, col);
moves.forEach(move => {
allMoves.push({ from: [row, col], to: move });
});
}
}
}
if (allMoves.length > 0) {
// Simple bot: choose random move for now
// In a real implementation, you'd use minimax with the configured depth
const randomMove = allMoves[Math.floor(Math.random() * allMoves.length)];
makeMove(...randomMove.from, ...randomMove.to);
}
}
// UI Functions
function updateDisplay() {
// Update turn indicator
document.getElementById('turn-indicator').textContent = `Turn: ${gameState.currentPlayer.charAt(0).toUpperCase() + gameState.currentPlayer.slice(1)}`;
// Update opponent info
const opponentInfo = document.getElementById('opponent-info');
if (gameState.opponent === 'bot') {
opponentInfo.textContent = `Opponent: ${BOT_CONFIGS[gameState.botDifficulty].name}`;
} else {
opponentInfo.textContent = 'Opponent: Human';
}
// Update timers
document.getElementById('timer-white').textContent = `White: ${formatTime(gameState.timerWhite)}`;
document.getElementById('timer-black').textContent = `Black: ${formatTime(gameState.timerBlack)}`;
// Update game status
const statusElement = document.getElementById('game-status');
if (gameState.checkmate) {
statusElement.textContent = `Checkmate! ${gameState.winner} wins!`;
statusElement.style.color = '#28a745';
} else if (gameState.stalemate) {
statusElement.textContent = 'Stalemate! Draw!';
statusElement.style.color = '#ffc107';
} else if (gameState.check) {
statusElement.textContent = 'Check!';
statusElement.style.color = '#dc3545';
} else {
statusElement.textContent = 'Game in progress';
statusElement.style.color = '#6c757d';
}
// Update move count
document.getElementById('move-count').textContent = `Moves: ${gameState.moveNotation.length}`;
// Update move history
updateMoveHistory();
// Re-render pieces
renderPieces();
}
function updateMoveHistory() {
const moveList = document.getElementById('move-list');
moveList.innerHTML = '';
for (let i = 0; i < gameState.moveNotation.length; i += 2) {
const moveNumber = Math.floor(i / 2) + 1;
const whiteMove = gameState.moveNotation[i] || '';
const blackMove = gameState.moveNotation[i + 1] || '';
const moveElement = document.createElement('div');
moveElement.className = 'move-pair';
moveElement.textContent = `${moveNumber}. ${whiteMove} ${blackMove}`;
moveList.appendChild(moveElement);
}
// Scroll to bottom
moveList.scrollTop = moveList.scrollHeight;
}
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}
function showMessage(message, duration = 3000) {
const messageElement = document.getElementById('game-message');
messageElement.textContent = message;
messageElement.classList.remove('hidden');
setTimeout(() => {
messageElement.classList.add('hidden');
}, duration);
}
// Timer Functions
function startTimer() {
gameState.lastTimerUpdate = Date.now();
gameState.timerInterval = setInterval(updateTimers, 1000);
}
function updateTimers() {
if (gameState.gameOver) {
clearInterval(gameState.timerInterval);
return;
}
const now = Date.now();
const elapsed = Math.floor((now - gameState.lastTimerUpdate) / 1000);
gameState.lastTimerUpdate = now;
if (gameState.currentPlayer === 'white') {
gameState.timerWhite = Math.max(0, gameState.timerWhite - elapsed);
if (gameState.timerWhite === 0) {
gameState.gameOver = true;
gameState.winner = 'black';
showMessage("White lost on time!");
endGame();
}
} else {
gameState.timerBlack = Math.max(0, gameState.timerBlack - elapsed);
if (gameState.timerBlack === 0) {
gameState.gameOver = true;
gameState.winner = 'white';
showMessage("Black lost on time!");
endGame();
}
}
updateDisplay();
}
function endGame() {
clearInterval(gameState.timerInterval);
// Update stats
if (gameState.winner === 'white') {
gameState.playerStats.wins++;
} else if (gameState.winner === 'black') {
gameState.playerStats.losses++;
} else {
gameState.playerStats.draws++;
}
saveStats();
// Show analysis screen
setTimeout(showAnalysisScreen, 1000);
}
function showAnalysisScreen() {
const modal = document.getElementById('analysis-screen');
const resultElement = document.getElementById('game-result');
const moveListElement = document.getElementById('full-move-list');
if (gameState.checkmate) {
resultElement.textContent = `Final Result: ${gameState.winner} wins by checkmate!`;
} else if (gameState.stalemate) {
resultElement.textContent = 'Final Result: Draw by stalemate!';
} else {
resultElement.textContent = 'Final Result: Game ended!';
}
// Show full move history
moveListElement.textContent = gameState.moveNotation.join(' ');
modal.classList.remove('hidden');
}
// Game Control Functions
function resetGame() {
clearInterval(gameState.timerInterval);
// Reset game state
gameState = {
...gameState,
board: [],
currentPlayer: 'white',
selectedPiece: null,
validMoves: [],
moveHistory: [],
moveNotation: [],
gameOver: false,
winner: null,
check: false,
checkmate: false,
stalemate: false,
lastMove: null,
draggingPiece: null,
timerWhite: 600,
timerBlack: 600,
lastTimerUpdate: Date.now()
};
// Close modals
document.querySelectorAll('.modal').forEach(modal => modal.classList.add('hidden'));
// Reinitialize game
initGame();
}
function undoMove() {
if (gameState.moveHistory.length === 0) {
showMessage("No moves to undo!");
return;
}
const lastMove = gameState.moveHistory.pop();
const { from, to, captured } = lastMove;
// Restore piece to original position
const piece = gameState.board[to[0]][to[1]];
gameState.board[from[0]][from[1]] = { ...piece, row: from[0], col: from[1] };
gameState.board[to[0]][to[1]] = captured;
// Remove last move notation
gameState.moveNotation.pop();
// Switch turn back
gameState.currentPlayer = gameState.currentPlayer === 'white' ? 'black' : 'white';
// Update last move
if (gameState.moveHistory.length > 0) {
const prevMove = gameState.moveHistory[gameState.moveHistory.length - 1];
gameState.lastMove = [prevMove.from, prevMove.to];
} else {
gameState.lastMove = null;
}
// Reset game over state
gameState.gameOver = false;
gameState.check = false;
gameState.checkmate = false;
gameState.stalemate = false;
// Restart timer if it was stopped
if (!gameState.timerInterval) {
startTimer();
}
updateDisplay();
showMessage("Move undone!");
}
function showHint() {
if (gameState.gameOver || gameState.currentPlayer !== 'white') {
showMessage("No hints available!");
return;
}
// Find first available move
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = gameState.board[row][col];
if (piece && piece.color === 'white') {
const moves = getValidMoves(row, col);
if (moves.length > 0) {
selectPiece(row, col);
showMessage("Hint shown! Selected piece highlighted.");
return;
}
}
}
}
showMessage("No valid moves found!");
}
function flipBoard() {
gameState.boardFlipped = !gameState.boardFlipped;
createBoard();
renderPieces();
showMessage(`Board ${gameState.boardFlipped ? 'flipped' : 'orientation reset'}!`);
}
function toggleMoveHistory() {
gameState.moveHistoryVisible = !gameState.moveHistoryVisible;
const panel = document.getElementById('move-history-panel');
panel.style.display = gameState.moveHistoryVisible ? 'block' : 'none';
}
// Screen Management
function showScreen(screenId) {
// Hide all screens
document.querySelectorAll('.screen').forEach(screen => {
screen.classList.remove('active');
});
// Show target screen
document.getElementById(screenId).classList.add('active');
// Special handling for game screen
if (screenId === 'game-screen') {
initGame();
}
}
function startGame(opponent, difficulty = 'intermediate') {
gameState.opponent = opponent;
gameState.botDifficulty = difficulty;
showScreen('game-screen');
}
function startTutorial() {
gameState.opponent = 'human';
showScreen('game-screen');
showMessage("Welcome to Chaturanga Tutorial! Select a piece to see valid moves.");
}
// Settings Functions