-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1819 lines (1556 loc) · 58.8 KB
/
script.js
File metadata and controls
1819 lines (1556 loc) · 58.8 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
'use strict';
/**
* ICS4UC Final Project
*
* Author: Adam Thompson-Sharpe
* Description: Chess!!
*/
/** @type {HTMLCanvasElement} */
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const rect = canvas.getBoundingClientRect();
const width = canvas.width;
const height = canvas.height;
const cellSize = width / 8;
// Sprite size is 4/5 of a cell
const spriteSize = 0.8 * cellSize;
const offset = (cellSize - spriteSize) / 2;
const darkColour = '#773f1a';
const lightColour = '#c6a992';
const highlightColour = 'rgba(230, 126, 34, 0.8)';
/** Whether the board has been rotated */
let flipped = false;
/** Boolean to track active turn */
let whiteTurn = true;
/** The ID of the active timer, returned by `setInterval` */
let activeTimer = 0;
let activeTimerColour = 'white';
let lastTimerUpdate = 0;
// Player timers, in seconds
let whiteTime = 600;
let blackTime = 600;
/** Whether a piece is currently selected */
let pieceHighlighted = false;
let highlightedRow = -1;
let highlightedCol = -1;
/** Whether an important dialog is open */
let dialogOpen = false;
// --- Types for IntelliSense ---
/** @typedef {"white" | "black"} Team */
/** @typedef {(Piece | null)[][]} BoardArray */
/** @typedef {[row: number, col: number]} Move */
/**
* Convert seconds to a minutes:seconds format
* @param {number} fullSeconds
*/
function secondsToTime(fullSeconds) {
fullSeconds = Math.ceil(fullSeconds);
if (fullSeconds <= 0) return '0:00';
const minutes = Math.floor(fullSeconds / 60);
// Round up to avoid the appearance of the timer suddenly skipping a second
const seconds = (fullSeconds % 60)
// Make sure that seconds are always two digits
.toString().padStart(2, '0');
return `${minutes}:${seconds}`;
}
/**
* Start the timer for a given player
* @param {TeamName} colour
*/
function startTimer(colour) {
const now = Date.now();
// Clear any old timers
if (activeTimer) {
clearInterval(activeTimer);
activeTimer = 0;
}
// Take into account untracked milliseconds since last update
if (lastTimerUpdate) {
if (activeTimerColour === 'white') whiteTime -= (now - lastTimerUpdate) / 1000;
else blackTime -= (now - lastTimerUpdate) / 1000;
}
activeTimerColour = colour;
const topTime = document.querySelector(`.player-bar.top .player-bar__time`);
const bottomTime = document.querySelector(`.player-bar.bottom .player-bar__time`);
// Set timer content for both players with respect to board flip
if (flipped) {
topTime.innerText = secondsToTime(whiteTime);
bottomTime.innerText = secondsToTime(blackTime);
} else {
topTime.innerText = secondsToTime(blackTime);
bottomTime.innerText = secondsToTime(whiteTime);
}
// Start ticking new timer for the relevant player
if (colour === 'white') {
// This is a function so that if the board flips in the middle of a timeout,
// the correct new timer will always be returned
const timer = () => flipped ? topTime : bottomTime;
// If there is a non-round amount of time left, wait that time before starting the timer
const timeLeft = whiteTime % 1;
setTimeout(() => {
// Round off time
whiteTime = Math.floor(whiteTime);
timer().innerText = secondsToTime(whiteTime);
lastTimerUpdate = Date.now();
// Start regular timer if there is not another one
if (!activeTimer) activeTimer = setInterval(() => {
whiteTime--;
timer().innerText = secondsToTime(whiteTime);
lastTimerUpdate = Date.now();
checkTimer();
}, 1000);
}, timeLeft * 1000);
} else {
// This is a function so that if the board flips in the middle of a timeout,
// the correct new timer will always be returned
const timer = () => flipped ? bottomTime : topTime;
// If there is a non-round amount of time left, wait that time before starting the timer
const timeLeft = blackTime % 1;
setTimeout(() => {
// Round off time
blackTime = Math.floor(blackTime);
timer().innerText = secondsToTime(blackTime);
lastTimerUpdate = Date.now();
// Start regular timer if there is not another active one
if (!activeTimer) activeTimer = setInterval(() => {
blackTime--;
timer().innerText = secondsToTime(blackTime);
lastTimerUpdate = Date.now();
checkTimer();
}, 1000);
}, timeLeft * 1000);
}
}
/** Stop the active timers */
function stopTimer() {
clearInterval(activeTimer);
activeTimer = 0;
lastTimerUpdate = 0;
const topTimer = document.querySelector('.player-bar.top .player-bar__time');
const bottomTimer = document.querySelector('.player-bar.bottom .player-bar__time');
// Update timer contents
if (!flipped) {
topTimer.innerText = secondsToTime(blackTime);
bottomTimer.innerText = secondsToTime(whiteTime);
} else {
topTimer.innerText = secondsToTime(whiteTime);
bottomTimer.innerText = secondsToTime(blackTime);
}
}
/** Stop and reset the active timers */
function resetTimer() {
whiteTime = 600;
blackTime = 600;
stopTimer();
}
/** Check if the game should end by time */
function checkTimer() {
if (whiteTime <= 0) endGame('black', 'time');
else if (blackTime <= 0) endGame('white', 'time');
}
function flipBoard() {
flipped = !flipped;
// Swap the player names
const topPlayer = document.querySelector('.player-bar.top .player-bar__name');
const bottomPlayer = document.querySelector('.player-bar.bottom .player-bar__name');
const topName = topPlayer.innerText;
topPlayer.innerText = bottomPlayer.innerText;
bottomPlayer.innerText = topName;
// Swap the timer contents (can otherwise temporarily show the wrong timer if the board is flipped twice in the same second)
const topTimer = document.querySelector('.player-bar.top .player-bar__time');
const bottomTimer = document.querySelector('.player-bar.bottom .player-bar__time');
const topTimerText = topTimer.innerText;
topTimer.innerText = bottomTimer.innerText;
bottomTimer.innerText = topTimerText;
// Fix timer
if (activeTimer) startTimer(whiteTurn ? 'white' : 'black');
}
function updateTurnIndicator() {
const activeTeam = whiteTurn ? 'white' : 'black';
const indicator = document.querySelector('.turn-indicator');
const indicatorText = document.querySelector('.turn-indicator__text');
// Remove old classes
indicator.classList.remove('turn-white');
indicator.classList.remove('turn-black');
indicatorText.classList.remove('turn-white');
indicatorText.classList.remove('turn-black');
// Add new classes and update text
indicator.classList.add(`turn-${activeTeam}`);
indicatorText.classList.add(`turn-${activeTeam}`);
// Capitalize the first letter of the colour
indicatorText.innerText = `${activeTeam[0].toUpperCase()}${activeTeam.slice(1)} to move`;
}
/**
* Utility function to check whether a given location is the same team.
* Only used in areas where it gets difficult to read
* by rewriting the check manually
* @param {readonly Board} board
* @param {number} row
* @param {number} col
* @param {Team} team
*/
function checkTeam(board, row, col, team) {
return board[row][col]?.colour === team;
}
/**
* Get the opposite team of the input
* @param {Team} team
* @returns {Team}
*/
function opposite(team) {
if (team === 'black') return 'white';
return 'black';
}
/**
* Get the direction a team's pawn should move.
* -1 (upwards) for white, 1 (downwards) for black
* @param {Team} team
*/
function movementDirection(team) {
if (team === 'black') return 1;
return -1;
}
/**
* Convert a row and column to (x, y) coordinates.
* @param {number} row
* @param {number} col
*/
function indexToCoords(row, col) {
return [col * cellSize, row * cellSize];
}
function offsetIndexToCoords(row, col) {
return indexToCoords(row, col).map(coord => coord + offset);
}
/**
* Convert (x, y) coordinates to a row and column
* @param {number} x
* @param {number} y
*/
function coordsToIndex(x, y) {
return [Math.floor(y / cellSize), Math.floor(x / cellSize)];
}
/**
* Recursive function!
* Get valid coordinates in a given direction.
* Returns valid coords for empty pieces until either the end of the board
* or an enemy piece is reached (including the enemy piece as a valid move)
* @param {BoardArray} board
* @param {number} startRow Where to start movement
* @param {number} startCol Where to start movement
* @param {number} rowDirection The direction of travel (i.e. +/- 1)
* @param {number} colDirection The direction of travel (i.e. +/- 1)
* @param {Team} team
*/
function coordsInLine(board, startRow, startCol, rowDirection, colDirection, team) {
// Move in the direction indicated by parameters
startRow += rowDirection;
startCol += colDirection;
// Check if location is out of bounds
if (startRow < 0 || startRow > 7 || startCol < 0 || startCol > 7) return [];
// Check if location is empty
if (!board[startRow][startCol]) {
// Return the found location as valid and recuse to find more
return [[startRow, startCol], ...coordsInLine(board, startRow, startCol, rowDirection, colDirection, team)];
}
// Check if there is an enemy piece
if (board[startRow][startCol].colour !== team) {
// Return *only* the found location (cannot go past this piece)
return [[startRow, startCol]];
}
// No moves found
return [];
}
/**
* Given a piece, return the moves that would be possible for a rook (horizontals)
* @param {Piece} piece
* @param {BoardArray} board
* @param {number} row
* @param {number} col
* @return {Move[]}
*/
function getRookMoves(piece, board, row, col) {
// Get valid moves for each horizontal direction
const moves = [
...coordsInLine(board, row, col, 1, 0, piece.colour),
...coordsInLine(board, row, col, -1, 0, piece.colour),
...coordsInLine(board, row, col, 0, 1, piece.colour),
...coordsInLine(board, row, col, 0, -1, piece.colour),
];
return moves;
}
/**
* Given a piece, return the moves that would be possible for a bishop (diagonals)
* @param {Piece} piece
* @param {BoardArray} board
* @param {number} row
* @param {number} col
* @return {Move[]}
*/
function getBishopMoves(piece, board, row, col) {
// Get valid moves for each horizontal direction
const moves = [
...coordsInLine(board, row, col, 1, 1, piece.colour),
...coordsInLine(board, row, col, -1, 1, piece.colour),
...coordsInLine(board, row, col, 1, -1, piece.colour),
...coordsInLine(board, row, col, -1, -1, piece.colour),
];
return moves;
}
/** Draw the chess board's squares */
function drawSquares() {
// Draw the squares
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if ((i + j) % 2 === 0) ctx.fillStyle = lightColour;
else ctx.fillStyle = darkColour;
ctx.fillRect(i * cellSize, j * cellSize, cellSize, cellSize);
}
}
ctx.font = '600 20px Arial';
ctx.fillStyle = '#ffffff';
// Add row labels
for (let i = 0; i <= 8; i++) {
// Make the colour the opposite of the current square
if (i % 2 === 0) ctx.fillStyle = darkColour;
else ctx.fillStyle = lightColour;
// Invert row numbering if required
const text = flipped ? i + 1 : 8 - i;
ctx.fillText(text, 10, (i * cellSize) + 25);
}
// Add column labels
for (let j = 0; j <= 8; j++) {
// Make the colour the opposite of the current square
if (j % 2 === 0) ctx.fillStyle = lightColour;
else ctx.fillStyle = darkColour;
// Invert letters of columns if required
const charCode = flipped ? 97 + 7 - j : 97 + j;
ctx.fillText(String.fromCharCode(charCode), (j * cellSize) + 80, height - 10);
}
}
/**
* Convert the canvas click location to a row and column.
* Passed coordinates should be relative to the canvas, not the entire page
*/
function canvasToIndex(x, y) {
return [Math.floor(y / cellSize), Math.floor(x / cellSize)];
}
/**
* Check whether a row and column is out of bounds on the board
* @param {number} row
* @param {number} col
*/
function outOfBounds(row, col) {
return row < 0 || row > 7 || col < 0 || col > 7;
}
/**
* Takes in an array of pairs and returns a list with only one occurence of each.
* Required since two different arrays are not equal (`===`) to each other
* @param {readonly T[]} arr
* @returns {T[]}
* @template {[any, any]} T Array type
*/
function uniquePairs(arr) {
return arr.filter(([left, right], index) =>
// Find the (first) index of the pair in the original array that contains these two points.
// If that index matches this one, keep the item
arr.findIndex(([otherLeft, otherRight]) => left === otherLeft && right === otherRight) === index);
}
/**
* Convert a row index to the chess notation number.
* This also happens to work the other way around
*/
function rowToNotation(row) {
return 8 - row;
}
/** Convert a column index to the chess notation letter */
function colToNotation(col) {
return String.fromCharCode(97 + col);
}
/** Convert a chess notation letter to the column index */
function notationToCol(notation) {
return notation.charCodeAt(0) - 97;
}
/** Convert a row and column to the notation for it (i.e. 0, 0 -> a1) */
function moveToNotation(row, col) {
return `${colToNotation(col)}${rowToNotation(row)}`;
}
/**
* The opposite of {@link moveToNotation}
* @returns {Move}
*/
function notationToMove(notation) {
const col = notation[0];
const row = notation[1];
return [rowToNotation(parseInt(row)), notationToCol(col)];
}
/**
* Find the location and value of a piece on the board of a given class
* @param {BoardArray} board
* @param {TeamName} colour The colour to match
* @param {T} baseClass The class that must be extended, such as {@link King}
* @returns {[piece: InstanceType<T>, row: number, col: number]}
* @template {typeof Piece} T Class type
*/
function findPiece(board, colour, baseClass = King) {
const isPiece = piece => piece instanceof baseClass && piece.colour === colour;
const row = board.findIndex(row => row.some(isPiece));
const col = board[row].findIndex(isPiece);
const piece = board[row][col];
return [piece, row, col];
}
/**
* Get a reference to all pieces on the board of a given class and colour.
* This function, unlike {@link findPiece}, does not return coordinates
* @param {BoardArray} board
* @param {TeamName} colour The colour to match
* @param {T} baseClass The class that must be extended, such as {@link King}
* @returns {Array<[piece: InstanceType<T>, row: number, col: number]>}
* @template {typeof Piece} T Class type
*/
function findPieces(board, colour, baseClass) {
const isPiece = piece => piece instanceof baseClass && piece.colour === colour;
return Array.from(board.entries())
// Filter out rows without the target piece
.filter(([, row]) => row.some(isPiece))
// Iterate over rows and flatten the final array
.flatMap(([i, row]) =>
// Iterate over pieces in the row
Array.from(row.entries())
// Only include target pieces
.filter(([, piece]) => isPiece(piece))
// Pair pieces with their row and column
.map(([j, piece]) => [piece, i, j]));
}
/**
* Convert a moves list to an HTML table
* @param {readonly string[]} moves
*/
function movesToTable(moves) {
let table = '<table class="moves__table"><tbody>';
let firstMove;
let moveNumber = 1;
for (const [i, move] of moves.entries()) {
if (i % 2 === 0) {
firstMove = move;
continue;
}
// Add each move to the table
table += `<tr class="moves__row"><td class="moves__number">${moveNumber}.</td><td class="moves__move">${firstMove}</td><td class="moves__move">${move}</td></tr>`;
moveNumber++;
firstMove = null;
}
// If there is a lone white move, add it without a black move
if (firstMove) table += `<tr class="moves__row"><td class="moves__number">${moveNumber}.</td><td class="moves__move">${firstMove}</td><td class="moves__move"></td></tr>`;
// Close the table
table += '</tbody></table>';
return table;
}
/**
* Set the colour of the pieces in the promotion box
* @param {Team} colour
*/
function setPromotionTeam(colour) {
const queenImage = document.querySelector('#promote-queen > img');
const rookImage = document.querySelector('#promote-rook > img');
const knightImage = document.querySelector('#promote-knight > img');
const bishopImage = document.querySelector('#promote-bishop > img');
queenImage.src = `images/queen_${colour}.png`;
rookImage.src = `images/rook_${colour}.png`;
knightImage.src = `images/knight_${colour}.png`;
bishopImage.src = `images/bishop_${colour}.png`;
}
/**
* Open the pawn promotion dialog.
* This is an **asynchronous function**, and returns a {@link Promise}
* which resolves when a button is selected
* @returns {Promise<typeof Piece>}
*/
function getPromotion() {
return new Promise(resolve => {
// Show dialog
dialogOpen = true;
document.querySelector('#promotion-dialog').showModal();
// Set up listeners
const queenBtn = document.querySelector('#promote-queen');
const rookBtn = document.querySelector('#promote-rook');
const knightBtn = document.querySelector('#promote-knight');
const bishopBtn = document.querySelector('#promote-bishop');
let queenListener = null;
let rookListener = null;
let knightListener = null;
let bishopListener = null;
/**
* Create an event listener that calls the callback for a provided piece.
* After it's called, it will also clear the listeners for the other buttons
* to avoid any unintended glitches
* @param {typeof Piece} piece Piece to construct
*/
const createButtonListener = piece => () => {
// Clear listeners
queenBtn.removeEventListener('click', queenListener);
rookBtn.removeEventListener('click', rookListener);
knightBtn.removeEventListener('click', knightListener);
bishopBtn.removeEventListener('click', bishopListener);
// Close dialog
dialogOpen = false;
document.querySelector('#promotion-dialog').close();
// Return the piece to construct
resolve(piece);
}
// Register listeners
queenListener = createButtonListener(Queen);
queenBtn.addEventListener('click', queenListener);
rookListener = createButtonListener(Rook);
rookBtn.addEventListener('click', rookListener);
knightListener = createButtonListener(Knight);
knightBtn.addEventListener('click', knightListener);
bishopListener = createButtonListener(Bishop);
bishopBtn.addEventListener('click', bishopListener);
});
}
/**
* Get a list of potential valid moves in a square around a given row and column
* @param {BoardArray} board
* @param {number} row
* @param {number} col
* @param {Team} colour The colour of the active piece
*/
function movesAround(board, row, col, colour) {
/** @type {Move[]} */
const moves = [];
for (let checkRow = row - 1; checkRow <= row + 1; checkRow++) {
for (let checkCol = col - 1; checkCol <= col + 1; checkCol++) {
// Don't bother checking the active square
if (checkRow === row && checkCol === col) continue;
// Make sure that the coordinate is on the board
if (outOfBounds(checkRow, checkCol)) continue;
// If the square is empty or taken by an *enemy* piece, allow the move
if (!board[checkRow][checkCol] || board[checkRow][checkCol].colour !== colour) {
moves.push([checkRow, checkCol]);
}
}
}
return moves;
}
/**
* Check if a piece is neighbouring a piece of a given type.
* Used for {@link King#getMoves}
* @param {BoardArray} board
* @param {number} row
* @param {number} col
* @param {Team} colour The colour of the active piece
* @param {typeof Piece} piece The piece to check against
*/
function nextToPiece(board, row, col, colour, piece) {
const moves = movesAround(board, row, col, colour);
return moves.some(([row, col]) => board[row][col] instanceof piece)
}
/**
* End the game for a provided reason (i.e. checkmate, stalemate, or time)
* @param {Team | null} winner
* @param {string} reason
*/
function endGame(winner, reason) {
stopTimer();
const whitePfp = document.querySelector('#end-white-img');
const blackPfp = document.querySelector('#end-black-img');
whitePfp.classList.remove('winner');
blackPfp.classList.remove('winner');
if (winner) {
document.querySelector('#end-winner').innerText = `${winner[0].toUpperCase()}${winner.slice(1)} wins`;
// Update green outline on the icon of the winner
if (winner === 'white') whitePfp.classList.add('winner');
else blackPfp.classList.add('winner');
} else {
document.querySelector('#end-winner').innerText = 'Draw';
}
// Update win reason and show dialog
document.querySelector('#end-reason').innerText = reason;
dialogOpen = true;
document.querySelector('#end-dialog').showModal();
}
async function resetGame(updateTurn = true) {
// Rest timers and board state
resetTimer();
flipped = false;
board = new Board();
await redraw();
// Reset turn if desired
if (updateTurn) whiteTurn = true;
updateTurnIndicator();
// Deselect pieces
pieceHighlighted = false;
highlightedRow = -1;
highlightedCol = -1;
// Clear movelist
document.querySelector('.moves').innerHTML = '';
// Close all dialogs
dialogOpen = false;
document.querySelectorAll('dialog').forEach(dialog => dialog.close());
}
class Board {
/** @type {BoardArray} */
pieces;
/** @type {string[]} */
moves = [];
constructor() {
this.pieces = [
[new Rook('black'), new Knight('black'), new Bishop('black'), new Queen('black'), new King('black'), new Bishop('black'), new Knight('black'), new Rook('black')],
[new Pawn('black'), new Pawn('black'), new Pawn('black'), new Pawn('black'), new Pawn('black'), new Pawn('black'), new Pawn('black'), new Pawn('black')],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
[new Pawn('white'), new Pawn('white'), new Pawn('white'), new Pawn('white'), new Pawn('white'), new Pawn('white'), new Pawn('white'), new Pawn('white')],
[new Rook('white'), new Knight('white'), new Bishop('white'), new Queen('white'), new King('white'), new Bishop('white'), new Knight('white'), new Rook('white')],
];
}
/**
* Load a board from FEN
* @param {string} fen
* @see {@link <https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation>}
*/
static fromFen(fen) {
const board = new this();
// Empty 8x8 board
board.pieces = [];
const split = fen.split(' ');
if (split.length !== 6) throw new TypeError('FEN notation should have six parts');
// Separate each piece of the FEN string
let [pieces, colour, castling, enPassant, halfMoves, fullMoves] = split;
// (halfmoves are unused)
// halfMoves = parseInt(halfMoves);
fullMoves = parseInt(fullMoves);
// Determine whose turn it is
colour = colour === 'w' ? 'white' : 'black';
whiteTurn = (colour === 'white');
// Previous moves cannot be known from a loaded FEN string
board.moves = new Array((fullMoves - 1) * 2).fill('--');
// If it is black to move, add one more unknown move for white
if (colour === 'black') board.moves.push('--');
const ranks = pieces.split('/');
// Place the pieces on the board according to the state
for (const [i, rank] of ranks.entries()) {
board.pieces.push([]);
let offset = 0;
for (const [j, piece] of rank.split('').entries()) {
// If the letter is uppercase, then the team is white
const team = (piece.toUpperCase() === piece) ? 'white' : 'black';
const col = j + offset;
switch (piece.toUpperCase()) {
case 'R':
board.pieces[i][col] = new Rook(team);
break;
case 'N':
board.pieces[i][col] = new Knight(team);
break;
case 'B':
board.pieces[i][col] = new Bishop(team);
break;
case 'Q':
board.pieces[i][col] = new Queen(team);
break;
case 'K':
board.pieces[i][col] = new King(team);
break;
case 'P':
board.pieces[i][col] = new Pawn(team);
break;
default:
// See if this is a number
if ('1' > piece || piece > '8')
throw new TypeError('Unknown piece ' + piece);
const empty = parseInt(piece);
// Variable `i` is already taken
for (let count = 0; count < empty; count++) {
board.pieces[i].push(null);
}
offset += empty - 1;
}
}
}
// Update whether pawns have moved
const whitePawns = findPieces(board.pieces, 'white', Pawn);
const blackPawns = findPieces(board.pieces, 'black', Pawn);
// If the pawns are not in their starting row, they have moved
whitePawns.filter(([, row]) => row !== 6).forEach(([pawn]) => pawn.hasMoved = true);
blackPawns.filter(([, row]) => row !== 1).forEach(([pawn]) => pawn.hasMoved = true);
// Update pawn for en passant square
if (enPassant !== '-') {
const [row, col] = notationToMove(enPassant);
// Figure out where the target piece must be based on the active player
const epPawn = whiteTurn ? board.pieces[row + 1][col] : board.pieces[row - 1][col];
if (!epPawn) throw new Error('Failed to find en passant pawn from FEN');
// Mark the pawn as just having moved two, allowing en passant
epPawn.movedTwo = true;
}
// ----- Whether castling is allowed -----
const whiteKingside = castling.includes('K');
const whiteQueenside = castling.includes('Q');
const blackKingside = castling.includes('k');
const blackQueenside = castling.includes('q');
const [whiteKing] = findPiece(board.pieces, 'white');
const [blackKing] = findPiece(board.pieces, 'black');
const whiteRooks = findPieces(board.pieces, 'white', Rook);
const blackRooks = findPieces(board.pieces, 'black', Rook);
// If a king can't castle in any direction, then we can't be sure what the reason is.
// This code just assumes that all pieces have moved, which will invalidate later castling availability checks
// --- White ---
if (!whiteKingside && !whiteQueenside) {
whiteKing.hasMoved = true;
whiteRooks.forEach(([rook]) => rook.hasMoved = true);
}
if (!whiteKingside) {
// Make sure that the kingside rook is not marked as able to castle
const kingsideRook = board.pieces[7][7];
if (kingsideRook && kingsideRook instanceof Rook) {
kingsideRook.hasMoved = true;
}
}
if (!whiteQueenside) {
// Make sure that the queenside rook is not marked as able to castle
const queensideRook = board.pieces[7][0];
if (queensideRook && queensideRook instanceof Rook) {
queensideRook.hasMoved = true;
}
}
// --- Black ---
if (!blackKingside && !blackQueenside) {
blackKing.hasMoved = true;
blackRooks.forEach(([rook]) => rook.hasMoved = true);
}
if (!blackKingside) {
// Make sure that the kingside rook is not marked as able to castle
const kingsideRook = board.pieces[0][7];
if (kingsideRook && kingsideRook instanceof Rook) {
kingsideRook.hasMoved = true;
}
}
if (!blackQueenside) {
// Make sure that the queenside rook is not marked as able to castle
const queensideRook = board.pieces[0][0];
if (queensideRook && queensideRook instanceof Rook) {
queensideRook.hasMoved = true;
}
}
return board;
}
/**
* Get the FEN description of the current board.
* Note that the halfmove counter is not properly changed since this game does not use it
* @see {@link <https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation>}
*/
toFen() {
const fenRows = [];
let fenTurn = whiteTurn ? 'w' : 'b';
let whiteKingside = true;
let whiteQueenside = true;
let blackKingside = true;
let blackQueenside = true;
// Get the FEN description of each row
for (const row of this.pieces) {
let currentRow = '';
let currentEmpty = 0;
// Add the number for empty columns to the currentRow
const addEmptyCols = () => {
if (currentEmpty) {
currentRow += currentEmpty;
currentEmpty = 0;
}
};
// Iterate over pieces and add their respective letters to the row
for (const piece of row) {
if (!piece) {
currentEmpty++;
continue;
}
addEmptyCols();
let letter = piece.letter || 'P';
if (piece.colour === 'black') letter = letter.toLowerCase();
currentRow += letter;
}
addEmptyCols();
fenRows.push(currentRow);
}
// Check castling availability
const [whiteKing, whiteRow, whiteCol] = findPiece(board.pieces, 'white');
const [blackKing, blackRow, blackCol] = findPiece(board.pieces, 'black');
// If the king has moved, no castling is possible
if (whiteKing.hasMoved || whiteRow !== 7 || whiteCol !== 4) {
whiteKingside = false;
whiteQueenside = false;
} else {
// Kingside castle
const kingsideRook = this.pieces[7][7];
if (!kingsideRook || !(kingsideRook instanceof Rook) || kingsideRook.hasMoved) {
whiteKingside = false;
}
// Queenside castle
const queensideRook = this.pieces[7][0];
if (!queensideRook || !(queensideRook instanceof Rook) || queensideRook.hasMoved) {
whiteQueenside = false;
}
}
// If the king has moved, no castling is possible
if (blackKing.hasMoved || blackRow !== 0 || blackCol !== 4) {
blackKingside = false;
blackQueenside = false;
} else {
// Kingside castle
const kingsideRook = this.pieces[0][7];
if (!kingsideRook || !(kingsideRook instanceof Rook) || kingsideRook.hasMoved) {
blackKingside = false;
}
// Queenside castle
const queensideRook = this.pieces[0][0];
if (!queensideRook || !(queensideRook instanceof Rook) || queensideRook.hasMoved) {
blackQueenside = false;
}
}
// Check en passant
let epSquare = '-';
const pawns = findPieces(this.pieces, whiteTurn ? 'white' : 'black', Pawn);
// Label to allow for breaking out of this for loop
epCheck:
for (const [pawn, row, col] of pawns) {
const moves = pawn.getMovesChecked(this.pieces, row, col);
// If a pawn can move diagonally to an empty square, it must be doing en passant
for (const [moveRow, moveCol] of moves) {
if (Math.abs(moveRow - row) === 1 && Math.abs(moveCol - col) === 1 && !this.pieces[moveRow][moveCol]) {
// Set the en passant square and break out of the outer loop
epSquare = moveToNotation(moveRow, moveCol);
break epCheck;
}
}
}
let castlingFen = '';
if (whiteKingside) castlingFen += 'K';
if (whiteQueenside) castlingFen += 'Q';
if (blackKingside) castlingFen += 'k';
if (blackQueenside) castlingFen += 'q';
if (!castlingFen) castlingFen = '-';
const fullMoves = Math.floor((this.moves.length) / 2 + 1);
return `${fenRows.join('/')} ${fenTurn} ${castlingFen} ${epSquare} 0 ${fullMoves}`;
}
/**
* Draw the pieces to the board.
* Asynchronous because of {@link Piece#draw}
* @param {CanvasRenderingContext2D} ctx
*/
async drawPieces(ctx) {
// Iterate backwards over rows if the board is flipped
const rowEntries = flipped
? this.pieces.slice().reverse().entries()
: this.pieces.entries();
// A list of async promises for pieces that are queued for drawing
const drawPromises = [];
for (const [i, row] of rowEntries) {
// Iterate backwards over columns if the board is flipped
const colEntries = flipped
? row.slice().reverse().entries()
: row.entries();
for (const [j, piece] of colEntries) {
if (!piece) continue;