-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.js
1198 lines (1039 loc) · 43.3 KB
/
chess.js
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";
// https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript
const PieceTypeEnum = {
"Pawn": "p",
"Knight": "h", // Useng the "h" for "horse", since "k" is the king
"Bishop": "b",
"Rook": "r",
"King": "k",
"Queen": "q"
};
const PlayerEnum = {
"White": "1",
"Black": "2",
};
const GameStateEnum = {
"SelectPiece": 0,
"SelectDestination": 1,
"GameOver": 2
};
// Make enums immutable
Object.freeze(PieceTypeEnum);
Object.freeze(PlayerEnum);
Object.freeze(GameStateEnum);
const piecesUnicode = {};
piecesUnicode[PlayerEnum.White] = {};
piecesUnicode[PlayerEnum.White][PieceTypeEnum.Pawn] = "♙";
piecesUnicode[PlayerEnum.White][PieceTypeEnum.Knight] = "♘";
piecesUnicode[PlayerEnum.White][PieceTypeEnum.Bishop] = "♗";
piecesUnicode[PlayerEnum.White][PieceTypeEnum.Rook] = "♖";
piecesUnicode[PlayerEnum.White][PieceTypeEnum.King] = "♔";
piecesUnicode[PlayerEnum.White][PieceTypeEnum.Queen] = "♕";
piecesUnicode[PlayerEnum.Black] = {};
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.Pawn] = "♟";
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.Knight] = "♞";
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.Bishop] = "♝";
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.Rook] = "♜";
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.King] = "♚";
piecesUnicode[PlayerEnum.Black][PieceTypeEnum.Queen] = "♛";
deepFreeze(piecesUnicode);
/** Contains the playable chessboard configurations. */
const chessboardsList = {
_8x8Standard: [
["r2", "h2", "b2", "q2", "k2", "b2", "h2", "r2"],
["p2", "p2", "p2", "p2", "p2", "p2", "p2", "p2"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
["p1", "p1", "p1", "p1", "p1", "p1", "p1", "p1"],
["r1", "h1", "b1", "q1", "k1", "b1", "h1", "r1"]
],
_6x6SimplerNoKnights: [
["r2", "b2", "q2", "k2", "b2", "r2"],
["p2", "p2", "p2", "p2", "p2", "p2"],
[" ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " "],
["p1", "p1", "p1", "p1", "p1", "p1"],
["r1", "b1", "q1", "k1", "b1", "r1"]
],
_5x5BabyChess: [
["k2", "q2", "b2", "h2", "r2"],
["p2", "p2", "p2", "p2", "p2"],
[" ", " ", " ", " ", " "],
["p1", "p1", "p1", "p1", "p1"],
["r1", "h1", "b1", "q1", "k1"]
],
_4x5Silverman: [
["r2", "q2", "k2", "r2"],
["p2", "p2", "p2", "p2"],
[" ", " ", " ", " "],
["p1", "p1", "p1", "p1"],
["r1", "q1", "k1", "r1"]
]
};
deepFreeze(chessboardsList);
/** Represents an empty cell in a chessboard matrix. */
const EMPTY_CELL = " ";
class PossibleMove {
constructor(row, col, isEnemy) {
this.row = row;
this.col = col;
this.isEnemy = isEnemy;
this.putsOwnKingInCheck = false;
}
setIllegal() {
this.putsOwnKingInCheck = true;
}
}
class Chess {
constructor() {
this.MIN_ROWS = 2;
this.MIN_COLS = 2;
}
/**
* Sets game variables to their initial state.
* @param {*} chessboard The chessboard configuration to use.
* @param {*} aiEnabled Determines if the opponent will be controlled by AI.
* @param {*} chessboard Determines which pieces are controlled by AI.
*/
startGame(chessboard, aiEnabled, aiColor) {
this.chessboard = chessboard;
this.numRows = chessboard.length;
this.numCols = chessboard[0].length;
this.MAX_ROW = this.numRows - 1;
this.MAX_COL = this.numCols - 1;
this.aiEnabled = aiEnabled;
this.aiColor = aiColor;
// White is always the first to move
this.activePlayer = PlayerEnum.White;
this.gameState = GameStateEnum.SelectPiece;
this.selectedPiece = { row: -1, col: -1 };
}
/** Returns the opponent of a specific player. */
getEnemy(player) {
return (player === PlayerEnum.White) ? PlayerEnum.Black : PlayerEnum.White;
}
// ******************
// CHESSBOARD
// ******************
/** Returns true if the row and column indexes passed as arguments
* are in-bounds in the chessboard matrix. */
inBounds(row, col) {
return (row >= 0 && row <= this.MAX_ROW && col >= 0 && col <= this.MAX_COL);
}
/** Returns an object containing data for a specific piece,
* or undefined if parameters are not valid. */
pieceAt(row, col) {
if(!this.inBounds(row, col)) {
return undefined;
} else {
if(this.chessboard[row][col] === EMPTY_CELL) {
return EMPTY_CELL;
} else {
return {
type: this.chessboard[row][col][0],
owner: this.chessboard[row][col][1]
};
}
}
}
// ******************
// TURN HANDLING
// ******************
changeTurn() {
if(!this.isAITurn())
setPlayerPiecesSelectable(this.activePlayer, false);
this.gameState = GameStateEnum.SelectPiece;
this.activePlayer = this.getEnemy(this.activePlayer);
this.startActivePlayerTurn();
}
// TODO: this should not be inside the Chess class (apart from AI turn stuff)
startActivePlayerTurn() {
setPlayerTurnText(this.activePlayer);
if(this.isAITurn())
performAITurn(this.activePlayer);
else
setPlayerPiecesSelectable(this.activePlayer, true);
}
isAITurn() {
return this.aiEnabled && this.activePlayer === this.aiColor;
}
handleCellSelected(row, col) {
if(this.gameState === GameStateEnum.GameOver)
return;
if(this.gameState === GameStateEnum.SelectPiece) {
if(this.pieceAt(row, col) !== EMPTY_CELL) {
if(this.pieceAt(row, col).owner === this.activePlayer) {
if(!this.isAITurn())
handleSelectedOwnPiece(row, col, this.getPossibleMovesForPiece(row, col));
this.selectedPiece.row = row;
this.selectedPiece.col = col;
this.gameState = GameStateEnum.SelectDestination;
}
}
} else if(this.gameState === GameStateEnum.SelectDestination) {
// If user clicks again on the piece they're trying to move, do nothing
if(row === this.selectedPiece.row && col === this.selectedPiece.col) {
return;
}
let arrPossibleMoves = this.getPossibleMovesForPiece(this.selectedPiece.row, this.selectedPiece.col);
if(!this.isAITurn())
handleSelectedDestinationForPiece(this.selectedPiece.row, this.selectedPiece.col, arrPossibleMoves);
let isValidMove = false;
// Check if the selected piece can be moved in the clicked cell
for(let i=0; i<arrPossibleMoves.length; i++) {
if(arrPossibleMoves[i].row === row
&& arrPossibleMoves[i].col === col
&& !arrPossibleMoves[i].putsOwnKingInCheck) {
isValidMove = true;
break;
}
}
if(isValidMove) {
this.chessboard[row][col] = this.chessboard[this.selectedPiece.row][this.selectedPiece.col];
this.chessboard[this.selectedPiece.row][this.selectedPiece.col] = EMPTY_CELL;
handlePieceMoved(this.selectedPiece.row, this.selectedPiece.col, row, col);
// Check if this move involves pawn promotion
let piece = this.pieceAt(row, col);
if(piece.type === PieceTypeEnum.Pawn) {
let promotionWhite = (piece.owner === PlayerEnum.White && row === 0)
let promotionBlack = (piece.owner === PlayerEnum.Black && row === this.MAX_ROW);
if(promotionWhite || promotionBlack) {
let promotionType = PieceTypeEnum.Queen;
// TODO allow choosing what piece to promote to
this.chessboard[row][col] = `${promotionType}${piece.owner}`;
handlePiecePromoted(row, col, piece.owner, promotionType);
}
}
let enemyPlayer = this.getEnemy(this.activePlayer);
let enemyKingInCheck = this.isKingInCheck(enemyPlayer);
if(this.hasLegalMoves(enemyPlayer)) {
if(enemyKingInCheck) {
handleTurnEnd(this.activePlayer, "check");
} else {
handleTurnEnd(this.activePlayer, "");
}
} else {
this.gameState = GameStateEnum.GameOver;
if(enemyKingInCheck) {
handleTurnEnd(this.activePlayer, "checkmate");
}
else {
handleTurnEnd(this.activePlayer, "stalemate");
}
}
if(this.gameState !== GameStateEnum.GameOver) {
this.changeTurn();
}
} else {
this.gameState = GameStateEnum.SelectPiece;
this.handleCellSelected(row, col);
}
}
}
// ****************************
// PIECES MOVEMENT HANDLING
// ****************************
/**
* Returns an array representing all the possible moves for a specific piece.
* @param {*} row
* @param {*} col
* @param {boolean} checkLegal Determines whether to check if moves are valid.
* Prevents the function from calling itselt infinitely when performing the validation check.
*/
getPossibleMovesForPiece(row, col, checkLegal = true) {
if(!this.inBounds(row, col)) {
console.error("Invalid row or column value");
return undefined;
}
let pieceToMove = this.pieceAt(row, col);
if(pieceToMove === EMPTY_CELL) {
console.error("Cannot get moves for an empty cell");
return null;
}
let arrMoves = [];
switch(pieceToMove.type) {
case PieceTypeEnum.Pawn: arrMoves = this.getPawnMoves(row, col); break;
case PieceTypeEnum.Knight: arrMoves = this.getKnightMoves(row, col); break;
case PieceTypeEnum.Bishop: arrMoves = this.getBishopMoves(row, col); break;
case PieceTypeEnum.Rook: arrMoves = this.getRookMoves(row, col); break;
case PieceTypeEnum.King: arrMoves = this.getKingMoves(row, col); break;
case PieceTypeEnum.Queen: arrMoves = this.getRookMoves(row, col).concat(this.getBishopMoves(row, col)); break;
default: console.error("Unrecognized piece type: " + pieceToMove.type);
}
if(checkLegal) {
for(let i = 0; i < arrMoves.length; i++) {
if(this.doesMovePutKingInCheck(row, col, arrMoves[i].row, arrMoves[i].col)) {
arrMoves[i].setIllegal();
}
}
}
return arrMoves;
}
/** Returns whether moving a piece on a certain square puts its king in check. */
doesMovePutKingInCheck(pieceRow, pieceCol, destRow, destCol) {
let pieceOwner = this.chessboard[pieceRow][pieceCol][1];
let destinationCellContents = this.chessboard[destRow][destCol];
// Move piece on destination square
this.chessboard[destRow][destCol] = this.chessboard[pieceRow][pieceCol];
this.chessboard[pieceRow][pieceCol] = EMPTY_CELL;
let kingInCheck = this.isKingInCheck(pieceOwner);
// This function uses the original chessboard to avoid creating
// a copy of the chessboard matrix on every call
this.chessboard[pieceRow][pieceCol] = this.chessboard[destRow][destCol];
this.chessboard[destRow][destCol] = destinationCellContents;
return kingInCheck;
}
/** Returns whether a king can be captured by an enemy piece. */
isKingInCheck(kingOwner) {
let arrPossibleMoves;
let enemyRow, enemyCol;
for (let r = 0; r <= this.MAX_ROW; r++) {
for (let c = 0; c <= this.MAX_COL; c++) {
// For every piece on the chessboard...
if (this.pieceAt(r, c) !== EMPTY_CELL) {
// ...owned by the king's enemy...
if (this.pieceAt(r, c).owner !== kingOwner) {
// Last parameter is false because is doesn't matter
// if the enemy will put their king to risk,
// if they capture the enemy king they win
arrPossibleMoves = this.getPossibleMovesForPiece(r, c, false);
// ...check all the cells that piece can be moved to
for (let i = 0; i < arrPossibleMoves.length; i++) {
// If the piece can capture another piece...
if (arrPossibleMoves[i].isEnemy) {
enemyRow = arrPossibleMoves[i].row;
enemyCol = arrPossibleMoves[i].col;
// ...and that piece is the king...
if (this.pieceAt(enemyRow, enemyCol).type === PieceTypeEnum.King) {
return true;
}
}
}
}
}
}
}
return false;
}
// TODO: this is used only to differentiate checkmate from stalemate,
// should find a way to recycle other functions to do this
/**
* Returns whether a player has legal moves.
* @param {*} player Player to check.
*/
hasLegalMoves(player) {
let arrPossibleMoves, piece;
for (let r = 0; r <= this.MAX_ROW; r++) {
for (let c = 0; c <= this.MAX_COL; c++) {
piece = this.pieceAt(r, c);
// For every piece on the chessboard...
if (piece !== EMPTY_CELL) {
// ...owned by a specific player...
if (piece.owner === player) {
// Get all possible moves for the piece...
arrPossibleMoves = this.getPossibleMovesForPiece(r, c);
for (let i = 0; i < arrPossibleMoves.length; i++) {
// If this piece has a legal move...
if(!arrPossibleMoves[i].putsOwnKingInCheck) {
return true;
}
}
}
}
}
}
return false;
}
// *******************
// PIECES MOVEMENT
// *******************
getPawnMoves(row, col) {
let pieceToMove = this.pieceAt(row, col);
// White pawns can only go up, black pawns can only go down
let direction = (pieceToMove.owner === PlayerEnum.White) ? -1 : 1;
let arrMoves = [];
let targetCell;
let r = row + (1 * direction);
// If pawn can go one step forward
if(this.inBounds(r, col)) {
// If cell forward-left has enemy
if(col > 0) {
targetCell = this.pieceAt(r, col-1);
if(targetCell !== EMPTY_CELL && targetCell.owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, col-1, true));
}
}
// If cell forward-right has enemy
if(col < this.MAX_COL) {
targetCell = this.pieceAt(r, col+1);
if(targetCell !== EMPTY_CELL && targetCell.owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, col+1, true));
}
}
// If cell forward is free
targetCell = this.pieceAt(r, col);
if(targetCell === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, col, false));
// TODO This will have to be changed when implementing custom chessboard
let startingRow = (pieceToMove.owner === PlayerEnum.White) ? this.MAX_ROW-1 : 1;
// If the pawn is at its starting position and has two free cells fprward
if(row === startingRow) {
r = row + 2 * direction;
if(this.pieceAt(r, col) === EMPTY_CELL)
arrMoves.push(new PossibleMove(r, col, false));
}
}
}
return arrMoves;
}
getKnightMoves(row, col) {
let arrMoves = [];
let pieceToMove = this.pieceAt(row, col);
let target;
const knightCheck = (r, c) => {
if(this.inBounds(r, c)) {
target = this.pieceAt(r, c);
if(target === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(target.owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
}
knightCheck(row-2, col-1); // Up left
knightCheck(row-2, col+1); // Up right
knightCheck(row+2, col-1); // Bottom left
knightCheck(row+2, col+1); // Bottom right
knightCheck(row+1, col-2); // Left up
knightCheck(row-1, col-2); // Left down
knightCheck(row+1, col+2); // Right up
knightCheck(row-1, col+2); // Right down
return arrMoves;
}
getBishopMoves(row, col) {
let arrMoves = [];
let pieceToMove = this.pieceAt(row, col);
let r, c;
// Up-left
r = row-1;
c = col-1;
while(this.inBounds(r, c)) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else {
if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
// This is not a free cell, so the piece cannot move anymore in this direction
break;
}
r--, c--;
}
// Up-right
r = row-1;
c = col+1;
while(this.inBounds(r, c)) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else {
if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
break;
}
r--, c++;
}
// Bottom-left
r = row+1;
c = col-1;
while(this.inBounds(r, c)) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else {
if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
break;
}
r++, c--;
}
// Bottom-right
r = row+1;
c = col+1;
while(this.inBounds(r, c)) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else {
if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
break;
}
r++, c++;
}
return arrMoves;
}
// TODO: this does not use pieceAt
// TODO: measure performance between pieceAt and getType(r, c) and getOwner(r, c) and using an object matrix instead of string matrix
getRookMoves(row, col) {
let arrMoves = [];
let pieceToMove = this.pieceAt(row, col);
let r, c;
// Bottom
r = row+1;
while(r <= this.MAX_ROW) {
// If cell is empty
if(this.chessboard[r][col] === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, col, false));
} else {
// If cell contains an enemy unit
if(this.chessboard[r][col][1] !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, col, true));
}
// In any case this cell is not empty, so the rook
// cannot move beyond this point in this direction
break;
}
r++;
}
// Top
r = row-1;
while(r >= 0) {
if(this.chessboard[r][col] === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, col, false));
} else {
if(this.chessboard[r][col][1] !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, col, true));
}
break;
}
r--;
}
// Right
c = col+1;
while(c <= this.MAX_COL) {
if(this.chessboard[row][c] === EMPTY_CELL) {
arrMoves.push(new PossibleMove(row, c, false));
} else {
if(this.chessboard[row][c][1] !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(row, c, true));
}
break;
}
c++;
}
// Left
c = col-1;
while(c >= 0) {
if(this.chessboard[row][c] === EMPTY_CELL) {
arrMoves.push(new PossibleMove(row, c, false));
} else {
if(this.chessboard[row][c][1] !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(row, c, true));
}
break;
}
c--;
}
return arrMoves;
}
getKingMoves(row, col) {
let arrMoves = [];
let pieceToMove = this.pieceAt(row, col);
let r, c;
r = row-1;
if(r >= 0) {
// Up
c = col;
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
// Up left
c = col-1;
if(c >= 0) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
// Up right
c = col+1;
if(c <= this.MAX_COL) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
}
r = row+1;
if(r <= this.MAX_ROW) {
// Bottom
c = col;
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
// Bottom left
c = col-1;
if(c >= 0) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
// Bottom right
c = col+1;
if(c <= this.MAX_COL) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
}
// Left
r = row;
c = col-1;
if(c >= 0) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
// Right
c = col+1;
if(c <= this.MAX_COL) {
if(this.pieceAt(r, c) === EMPTY_CELL) {
arrMoves.push(new PossibleMove(r, c, false));
} else if(this.pieceAt(r, c).owner !== pieceToMove.owner) {
arrMoves.push(new PossibleMove(r, c, true));
}
}
return arrMoves;
}
}
let optionsForm;
let btnMenuOpen
let btnMenuClose
let gridContainer;
let messageTurnElem;
let messageWarningElem;
let chess = new Chess();
document.body.onload = function() {
messageTurnElem = document.getElementById("msg-turn");
messageWarningElem = document.getElementById("msg-warning");
gridContainer = document.getElementById("grid-container");
optionsForm = document.querySelector("form");
btnMenuOpen = document.getElementById("btn-menu-open");
btnMenuClose = document.getElementById("btn-menu-close");
optionsForm.onsubmit = handleMenuFormSubmit;
btnMenuOpen.onclick = () => { setOptionsFormActive(true); };
btnMenuClose.onclick = () => { setOptionsFormActive(false); };
document.getElementById("opponent-choice-human").onclick = () => {
document.getElementById("menu-section-color").classList.add("hidden");
};
document.getElementById("opponent-choice-ai").onclick = () => {
document.getElementById("menu-section-color").classList.remove("hidden");
};
}
/** Makes an object completely immutable. */
// Object.freeze() works on an object's properties,
// but if the properties are also objects they're still mutable.
// For example, if a chessboard matrix if frozen,
// chessboard[0] is immutable, but chessboard[0][0] is not.
// Note: arrays in JS are an extension of (and in fact are) objects
function deepFreeze(obj) {
if(typeof(obj) !== "object")
return;
Object.freeze(obj);
Object.keys(obj).forEach((key) => {
deepFreeze(obj[key]);
});
}
/** Creates a mutable copy of a matrix frozen with deepFreeze(). */
// Using slice() returns an "unfrozen" copy of an array,
// but if deepFreeze was used, its properties (elements) are still frozen.
// Returns a copy because there's no built-in way to "unfreeze" an object.
function getMatrixUnfrozenCopy(chessboard) {
let matrix = [];
chessboard.forEach((row, i) => {
matrix.push([]);
row.forEach((col) => {
matrix[i].push(col);
});
});
return matrix;
}
function setOptionsFormActive(display) {
if(display) {
btnMenuOpen.classList.add("hidden");
btnMenuClose.classList.remove("hidden");
optionsForm.classList.remove("hidden");
gridContainer.classList.add("hidden");
document.getElementById("messages-container").classList.add("hidden");
} else {
btnMenuOpen.classList.remove("hidden");
btnMenuClose.classList.add("hidden");
optionsForm.classList.add("hidden");
gridContainer.classList.remove("hidden");
document.getElementById("messages-container").classList.remove("hidden");
}
}
function handleMenuFormSubmit(event) {
event.preventDefault();
let form = event.currentTarget;
setOptionsFormActive(false);
let choicePlayerColor, choiceAIEnabled, choiceChessboard;
// https://stackoverflow.com/a/26236365
// https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries
for(const input of form.elements) {
if(input.name === "options-chessboard") {
switch(input.value) {
case "chessboard-standard": choiceChessboard = chessboardsList._8x8Standard; break;
case "chessboard-6x6NoKnights": choiceChessboard = chessboardsList._6x6SimplerNoKnights; break;
case "chessboard-5x5babychess": choiceChessboard = chessboardsList._5x5BabyChess; break;
case "chessboard-4x5Silverman": choiceChessboard = chessboardsList._4x5Silverman; break;
default: console.error(`Option ${input.value} not recognized.`); break;
}
} else if(input.type == "radio" && input.checked) {
switch(input.name) {
case "options-opponent":
switch(input.id) {
case "opponent-choice-human": choiceAIEnabled = false; break;
case "opponent-choice-ai": choiceAIEnabled = true; break;
default: console.error(`Option ${input.id} not recognized.`); break;
}
break;
case "options-color":
switch(input.id) {
case "color-choice-white": choicePlayerColor = PlayerEnum.White; break;
case "color-choice-black": choicePlayerColor = PlayerEnum.Black; break;
default: console.error(`Option ${input.id} not recognized.`); break;
}
break;
default:
console.error(`Option ${input.name} not recognized.`);
break;
}
}
}
let aiColor = chess.getEnemy(choicePlayerColor);
// arrays are a reference type, we want to pass a copy
// Since the original chessboardList object is deeply frozen, slice() is not enough
let mutableChessboard = getMatrixUnfrozenCopy(choiceChessboard);
chess.startGame(mutableChessboard, choiceAIEnabled, aiColor);
initUI();
// TODO this should be done by Chess class, but UI have to be initialized first...
chess.startActivePlayerTurn();
}
function initUI() {
// TODO: chessboard.numRows
let table = createChessboardTableHTML(chess.numRows, chess.numCols);
// Makes sure the element is empty when restarting game
gridContainer.innerHTML = "";
gridContainer.appendChild(table);
messageWarningElem.innerText = "";
}
function createChessboardTableHTML(numRows, numCols) {
let table = document.createElement("table");
// Determines color of the first cell in the row. It's initialized
// with TRUE because the top-left cell in the chessboard should be white
let isFirstCellInRowWhite = true;
for(let row = 0; row < numRows; row++) {
let tr = document.createElement("tr");
for(let col = 0; col < numCols; col++) {
let td = document.createElement("td");
// This makes it easier to recognize which cell was clicked
td.id = coordsToId(row, col);
td.onclick = handleHTMLCellClick;
let piece = chess.pieceAt(row, col);
if(piece !== EMPTY_CELL) {
let span = document.createElement("span");
span.innerText = piecesUnicode[piece.owner][piece.type];
if(piece.owner === PlayerEnum.White) {
span.className = "piece-white";
} else {
span.className = "piece-black";
}
td.appendChild(span);
}
// Makes cells with an even column index black or white
if(isFirstCellInRowWhite)
td.className = col % 2 === 0 ? "cell-white" : "cell-black";
else
td.className = col % 2 === 0 ? "cell-black" : "cell-white";
tr.appendChild(td);
}
table.appendChild(tr);
isFirstCellInRowWhite = !isFirstCellInRowWhite;
}
return table;
}
// Retrieves row and column index from the clicked cell's id
function handleHTMLCellClick(e) {
// https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
let idArray = e.currentTarget.id.split("-");
let row = Number(idArray[1]);
let col = Number(idArray[2]);
chess.handleCellSelected(row, col);
}
// ***********************
// UI HANDLERS
// ***********************
function handleSelectedOwnPiece(row, col, possibleMoves) {
//console.log(`Selected cell ${row}-${col}. Piece type: ${pieceAt(row, col).type}`);
setSelectionMarkerActive(row, col, true);
setDisplayDestinationActive(possibleMoves, true);
}
function handleSelectedDestinationForPiece(pieceRow, pieceCol, possibleMoves) {
setSelectionMarkerActive(pieceRow, pieceCol, false);
setDisplayDestinationActive(possibleMoves, false);
}
function handlePieceMoved(pieceRow, pieceCol, targetRow, targetCol) {
// This is not a big issue, but consider reading this - https://stackoverflow.com/a/2305677
let selectedPieceHTMLCell = getHTMLCellByCoords(pieceRow, pieceCol)
getHTMLCellByCoords(targetRow, targetCol).innerHTML = selectedPieceHTMLCell.innerHTML;
selectedPieceHTMLCell.innerHTML = "";
}
// Visually replaces a pawn with another piece
function handlePiecePromoted(row, col, pieceColor, promotionType) {
getHTMLCellByCoords(row, col).firstChild.innerText = piecesUnicode[pieceColor][promotionType];
}
function handleTurnEnd(activePlayer, turnEndType) {
switch(turnEndType) {
case "":
messageWarningElem.innerText = "";
break;
case "check":
// The "⚠" emoji defaults to text on some browsers
// (i.e. Chrome on Windows 10), unless followed by U+FE0F
// which forces it to be displayed as emoji
// https://emojipedia.org/emoji/%E2%9A%A0/
// https://emojipedia.org/variation-selector-16/
messageWarningElem.innerHTML = (activePlayer === PlayerEnum.White)
? "⚠️ Black king check! ⚠️"
: "⚠️ White king check! ⚠️";
break;
case "checkmate":
messageTurnElem.innerText = (activePlayer === PlayerEnum.White)
? "🏆 White wins! 🏆"
: "🏆 Black wins! 🏆";
messageWarningElem.innerText = "Checkmate.";
break;
case "stalemate":
messageTurnElem.innerText = "🤝 It's a draw! 🤝";
messageWarningElem.innerText = (activePlayer === PlayerEnum.White)
? "Stalemate. Black cannot move."
: "Stalemate. White cannot move.";
break;
default:
console.error("Unrecognized game over type.");
}
}
// ***********************
// UI HELPERS
// ***********************
/** Shows a message saying which player should move. */
function setPlayerTurnText(player) {
if(player === PlayerEnum.White)
messageTurnElem.innerText = "⚪ White's turn ⚪";
else
messageTurnElem.innerText = "⚫ Black's turn ⚫";
}
function setSelectionMarkerActive(row, col, display) {
if(!chess.inBounds(row, col)) {
console.error("Invalid arguments.");
return;
}
let cellElement = getHTMLCellByCoords(row, col);
if(display)
cellElement.classList.add("cell-selected");
else
cellElement.classList.remove("cell-selected");
}
function setPlayerPiecesSelectable(player, selectable) {
for(let r = 0; r <= chess.MAX_ROW; r++) {
for(let c = 0; c <= chess.MAX_COL; c++) {
let piece = chess.pieceAt(r, c);
if(piece != EMPTY_CELL && piece.owner === player) {
if(selectable)
getHTMLCellByCoords(r, c).classList.add("cell-selectable");