1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
4 import { ArrayFun
} from "@/utils/array";
5 import { randInt
, shuffle
} from "@/utils/alea";
7 // class "PiPo": Piece + Position
8 export const PiPo
= class PiPo
{
9 // o: {piece[p], color[c], posX[x], posY[y]}
18 export const Move
= class Move
{
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
23 this.appear
= o
.appear
;
24 this.vanish
= o
.vanish
;
25 this.start
= o
.start
? o
.start : { x: o
.vanish
[0].x
, y: o
.vanish
[0].y
};
26 this.end
= o
.end
? o
.end : { x: o
.appear
[0].x
, y: o
.appear
[0].y
};
30 // NOTE: x coords = top to bottom; y = left to right
31 // (from white player perspective)
32 export const ChessRules
= class ChessRules
{
37 // Some variants don't have flags:
38 static get HasFlags() {
43 static get HasCastle() {
47 // Pawns specifications
48 static get PawnSpecs() {
50 directions: { 'w': -1, 'b': 1 },
51 initShift: { w: 1, b: 1 },
54 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
56 captureBackward: false,
61 // En-passant captures need a stack of squares:
62 static get HasEnpassant() {
66 // Some variants cannot have analyse mode
67 static get CanAnalyze() {
70 // Patch: issues with javascript OOP, objects can't access static fields.
75 // Some variants show incomplete information,
76 // and thus show only a partial moves list or no list at all.
77 static get ShowMoves() {
84 // Sometimes moves must remain hidden until game ends
85 static get SomeHiddenMoves() {
88 get someHiddenMoves() {
89 return V
.SomeHiddenMoves
;
92 // Generally true, unless the variant includes random effects
93 static get CorrConfirm() {
97 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
102 // Some variants always show the same orientation
103 static get CanFlip() {
110 // For (generally old) variants without checkered board
111 static get Monochrome() {
115 // Some games are drawn unusually (bottomr right corner is black)
116 static get DarkBottomRight() {
120 // Some variants require lines drawing
124 // Draw all inter-squares lines
125 for (let i
= 0; i
<= V
.size
.x
; i
++)
126 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
127 for (let j
= 0; j
<= V
.size
.y
; j
++)
128 lines
.push([[0, j
], [V
.size
.x
, j
]]);
134 // In some variants, the player who repeat a position loses
135 static get LoseOnRepetition() {
139 // Some variants use click infos:
144 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
149 static get IMAGE_EXTENSION() {
150 // All pieces should be in the SVG format
154 // Turn "wb" into "B" (for FEN)
155 static board2fen(b
) {
156 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
159 // Turn "p" into "bp" (for board)
160 static fen2board(f
) {
161 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
164 // Check if FEN describes a board situation correctly
165 static IsGoodFen(fen
) {
166 const fenParsed
= V
.ParseFen(fen
);
168 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
170 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
171 // 3) Check moves count
172 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
175 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
177 // 5) Check enpassant
180 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
187 // Is position part of the FEN a priori correct?
188 static IsGoodPosition(position
) {
189 if (position
.length
== 0) return false;
190 const rows
= position
.split("/");
191 if (rows
.length
!= V
.size
.x
) return false;
192 let kings
= { "k": 0, "K": 0 };
193 for (let row
of rows
) {
195 for (let i
= 0; i
< row
.length
; i
++) {
196 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
197 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
199 const num
= parseInt(row
[i
], 10);
200 if (isNaN(num
)) return false;
204 if (sumElts
!= V
.size
.y
) return false;
206 // Both kings should be on board. Exactly one per color.
207 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
212 static IsGoodTurn(turn
) {
213 return ["w", "b"].includes(turn
);
217 static IsGoodFlags(flags
) {
218 // NOTE: a little too permissive to work with more variants
219 return !!flags
.match(/^[a-z]{4,4}$/);
222 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
223 static IsGoodEnpassant(enpassant
) {
224 if (enpassant
!= "-") {
225 const ep
= V
.SquareToCoords(enpassant
);
226 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
231 // 3 --> d (column number to letter)
232 static CoordToColumn(colnum
) {
233 return String
.fromCharCode(97 + colnum
);
236 // d --> 3 (column letter to number)
237 static ColumnToCoord(column
) {
238 return column
.charCodeAt(0) - 97;
242 static SquareToCoords(sq
) {
244 // NOTE: column is always one char => max 26 columns
245 // row is counted from black side => subtraction
246 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
247 y: sq
[0].charCodeAt() - 97
252 static CoordsToSquare(coords
) {
253 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
256 // Path to pieces (standard ones in pieces/ folder)
261 // Path to promotion pieces (usually the same)
263 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
266 // Aggregates flags into one object
268 return this.castleFlags
;
272 disaggregateFlags(flags
) {
273 this.castleFlags
= flags
;
276 // En-passant square, if any
277 getEpSquare(moveOrSquare
) {
278 if (!moveOrSquare
) return undefined;
279 if (typeof moveOrSquare
=== "string") {
280 const square
= moveOrSquare
;
281 if (square
== "-") return undefined;
282 return V
.SquareToCoords(square
);
284 // Argument is a move:
285 const move = moveOrSquare
;
286 const s
= move.start
,
290 Math
.abs(s
.x
- e
.x
) == 2 &&
291 // Next conditions for variants like Atomic or Rifle, Recycle...
292 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
293 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
300 return undefined; //default
303 // Can thing on square1 take thing on square2
304 canTake([x1
, y1
], [x2
, y2
]) {
305 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
308 // Is (x,y) on the chessboard?
309 static OnBoard(x
, y
) {
310 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
313 // Used in interface: 'side' arg == player color
314 canIplay(side
, [x
, y
]) {
315 return this.turn
== side
&& this.getColor(x
, y
) == side
;
318 // On which squares is color under check ? (for interface)
320 const color
= this.turn
;
322 this.underCheck(color
)
323 // kingPos must be duplicated, because it may change:
324 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
332 // Setup the initial random (asymmetric) position
333 static GenRandInitFen(randomness
) {
336 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
338 let pieces
= { w: new Array(8), b: new Array(8) };
340 // Shuffle pieces on first (and last rank if randomness == 2)
341 for (let c
of ["w", "b"]) {
342 if (c
== 'b' && randomness
== 1) {
343 pieces
['b'] = pieces
['w'];
348 let positions
= ArrayFun
.range(8);
350 // Get random squares for bishops
351 let randIndex
= 2 * randInt(4);
352 const bishop1Pos
= positions
[randIndex
];
353 // The second bishop must be on a square of different color
354 let randIndex_tmp
= 2 * randInt(4) + 1;
355 const bishop2Pos
= positions
[randIndex_tmp
];
356 // Remove chosen squares
357 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
358 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
360 // Get random squares for knights
361 randIndex
= randInt(6);
362 const knight1Pos
= positions
[randIndex
];
363 positions
.splice(randIndex
, 1);
364 randIndex
= randInt(5);
365 const knight2Pos
= positions
[randIndex
];
366 positions
.splice(randIndex
, 1);
368 // Get random square for queen
369 randIndex
= randInt(4);
370 const queenPos
= positions
[randIndex
];
371 positions
.splice(randIndex
, 1);
373 // Rooks and king positions are now fixed,
374 // because of the ordering rook-king-rook
375 const rook1Pos
= positions
[0];
376 const kingPos
= positions
[1];
377 const rook2Pos
= positions
[2];
379 // Finally put the shuffled pieces in the board array
380 pieces
[c
][rook1Pos
] = "r";
381 pieces
[c
][knight1Pos
] = "n";
382 pieces
[c
][bishop1Pos
] = "b";
383 pieces
[c
][queenPos
] = "q";
384 pieces
[c
][kingPos
] = "k";
385 pieces
[c
][bishop2Pos
] = "b";
386 pieces
[c
][knight2Pos
] = "n";
387 pieces
[c
][rook2Pos
] = "r";
388 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
390 // Add turn + flags + enpassant
392 pieces
["b"].join("") +
393 "/pppppppp/8/8/8/8/PPPPPPPP/" +
394 pieces
["w"].join("").toUpperCase() +
395 " w 0 " + flags
+ " -"
399 // "Parse" FEN: just return untransformed string data
400 static ParseFen(fen
) {
401 const fenParts
= fen
.split(" ");
403 position: fenParts
[0],
405 movesCount: fenParts
[2]
408 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
409 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
413 // Return current fen (game state)
416 this.getBaseFen() + " " +
417 this.getTurnFen() + " " +
419 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
420 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
425 // Omit movesCount, only variable allowed to differ
427 this.getBaseFen() + "_" +
429 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
430 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
434 // Position part of the FEN string
436 const format
= (count
) => {
437 // if more than 9 consecutive free spaces, break the integer,
438 // otherwise FEN parsing will fail.
439 if (count
<= 9) return count
;
440 // Currently only boards of size up to 11 or 12:
441 return "9" + (count
- 9);
444 for (let i
= 0; i
< V
.size
.x
; i
++) {
446 for (let j
= 0; j
< V
.size
.y
; j
++) {
447 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
449 if (emptyCount
> 0) {
450 // Add empty squares in-between
451 position
+= format(emptyCount
);
454 position
+= V
.board2fen(this.board
[i
][j
]);
457 if (emptyCount
> 0) {
459 position
+= format(emptyCount
);
461 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
470 // Flags part of the FEN string
474 for (let c
of ["w", "b"])
475 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
479 // Enpassant part of the FEN string
481 const L
= this.epSquares
.length
;
482 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
483 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
486 // Turn position fen into double array ["wb","wp","bk",...]
487 static GetBoard(position
) {
488 const rows
= position
.split("/");
489 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
490 for (let i
= 0; i
< rows
.length
; i
++) {
492 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
493 const character
= rows
[i
][indexInRow
];
494 const num
= parseInt(character
, 10);
495 // If num is a number, just shift j:
496 if (!isNaN(num
)) j
+= num
;
497 // Else: something at position i,j
498 else board
[i
][j
++] = V
.fen2board(character
);
504 // Extract (relevant) flags from fen
506 // white a-castle, h-castle, black a-castle, h-castle
507 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
508 for (let i
= 0; i
< 4; i
++) {
509 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
510 V
.ColumnToCoord(fenflags
.charAt(i
));
517 // Fen string fully describes the game state
520 // In printDiagram() fen isn't supply because only getPpath() is used
521 // TODO: find a better solution!
523 const fenParsed
= V
.ParseFen(fen
);
524 this.board
= V
.GetBoard(fenParsed
.position
);
525 this.turn
= fenParsed
.turn
;
526 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
527 this.setOtherVariables(fen
);
530 // Scan board for kings positions
532 // Squares of white and black king:
533 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
534 const fenRows
= V
.ParseFen(fen
).position
.split("/");
535 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
536 for (let i
= 0; i
< fenRows
.length
; i
++) {
537 let k
= 0; //column index on board
538 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
539 switch (fenRows
[i
].charAt(j
)) {
541 this.kingPos
["b"] = [i
, k
];
544 this.kingPos
["w"] = [i
, k
];
547 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
548 if (!isNaN(num
)) k
+= num
- 1;
556 // Some additional variables from FEN (variant dependant)
557 setOtherVariables(fen
) {
558 // Set flags and enpassant:
559 const parsedFen
= V
.ParseFen(fen
);
560 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
561 if (V
.HasEnpassant
) {
563 parsedFen
.enpassant
!= "-"
564 ? this.getEpSquare(parsedFen
.enpassant
)
566 this.epSquares
= [epSq
];
568 // Search for kings positions:
572 /////////////////////
576 return { x: 8, y: 8 };
579 // Color of thing on square (i,j). 'undefined' if square is empty
581 return this.board
[i
][j
].charAt(0);
584 // Piece type on square (i,j). 'undefined' if square is empty
586 return this.board
[i
][j
].charAt(1);
589 // Get opponent color
590 static GetOppCol(color
) {
591 return color
== "w" ? "b" : "w";
594 // Pieces codes (for a clearer code)
601 static get KNIGHT() {
604 static get BISHOP() {
615 static get PIECES() {
616 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
624 // Some pieces movements
655 // All possible moves from selected square
656 getPotentialMovesFrom([x
, y
]) {
657 switch (this.getPiece(x
, y
)) {
659 return this.getPotentialPawnMoves([x
, y
]);
661 return this.getPotentialRookMoves([x
, y
]);
663 return this.getPotentialKnightMoves([x
, y
]);
665 return this.getPotentialBishopMoves([x
, y
]);
667 return this.getPotentialQueenMoves([x
, y
]);
669 return this.getPotentialKingMoves([x
, y
]);
671 return []; //never reached
674 // Build a regular move from its initial and destination squares.
675 // tr: transformation
676 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
677 const initColor
= this.getColor(sx
, sy
);
678 const initPiece
= this.board
[sx
][sy
].charAt(1);
684 c: tr
? tr
.c : initColor
,
685 p: tr
? tr
.p : initPiece
698 // The opponent piece disappears if we take it
699 if (this.board
[ex
][ey
] != V
.EMPTY
) {
704 c: this.getColor(ex
, ey
),
705 p: this.board
[ex
][ey
].charAt(1)
713 // Generic method to find possible moves of non-pawn pieces:
714 // "sliding or jumping"
715 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
717 outerLoop: for (let step
of steps
) {
720 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
721 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
722 if (oneStep
) continue outerLoop
;
726 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
727 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
732 // Special case of en-passant captures: treated separately
733 getEnpassantCaptures([x
, y
], shiftX
) {
734 const Lep
= this.epSquares
.length
;
735 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
736 let enpassantMove
= null;
739 epSquare
.x
== x
+ shiftX
&&
740 Math
.abs(epSquare
.y
- y
) == 1
742 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
743 enpassantMove
.vanish
.push({
746 p: this.board
[x
][epSquare
.y
].charAt(1),
747 c: this.getColor(x
, epSquare
.y
)
750 return !!enpassantMove
? [enpassantMove
] : [];
753 // Consider all potential promotions:
754 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
755 let finalPieces
= [V
.PAWN
];
756 const color
= this.turn
; //this.getColor(x1, y1);
757 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
758 if (x2
== lastRank
) {
759 // promotions arg: special override for Hiddenqueen variant
760 if (!!promotions
) finalPieces
= promotions
;
761 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
764 for (let piece
of finalPieces
) {
765 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
766 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
770 // What are the pawn moves from square x,y ?
771 getPotentialPawnMoves([x
, y
], promotions
) {
772 const color
= this.turn
; //this.getColor(x, y);
773 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
774 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
775 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
776 const forward
= (color
== 'w' ? -1 : 1);
778 // Pawn movements in shiftX direction:
779 const getPawnMoves
= (shiftX
) => {
781 // NOTE: next condition is generally true (no pawn on last rank)
782 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
783 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
784 // One square forward (or backward)
785 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
786 // Next condition because pawns on 1st rank can generally jump
788 V
.PawnSpecs
.twoSquares
&&
790 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
792 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
797 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
800 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
802 V
.PawnSpecs
.threeSquares
&&
803 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
805 // Three squares jump
806 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
812 if (V
.PawnSpecs
.canCapture
) {
813 for (let shiftY
of [-1, 1]) {
814 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
816 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
817 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
820 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
825 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
826 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
827 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
828 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
831 [x
, y
], [x
- shiftX
, y
+ shiftY
],
842 let pMoves
= getPawnMoves(pawnShiftX
);
843 if (V
.PawnSpecs
.bidirectional
)
844 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
846 if (V
.HasEnpassant
) {
847 // NOTE: backward en-passant captures are not considered
848 // because no rules define them (for now).
849 Array
.prototype.push
.apply(
851 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
858 // What are the rook moves from square x,y ?
859 getPotentialRookMoves(sq
) {
860 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
863 // What are the knight moves from square x,y ?
864 getPotentialKnightMoves(sq
) {
865 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
868 // What are the bishop moves from square x,y ?
869 getPotentialBishopMoves(sq
) {
870 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
873 // What are the queen moves from square x,y ?
874 getPotentialQueenMoves(sq
) {
875 return this.getSlideNJumpMoves(
877 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
881 // What are the king moves from square x,y ?
882 getPotentialKingMoves(sq
) {
883 // Initialize with normal moves
884 let moves
= this.getSlideNJumpMoves(
886 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
889 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
890 moves
= moves
.concat(this.getCastleMoves(sq
));
894 // "castleInCheck" arg to let some variants castle under check
895 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
896 const c
= this.getColor(x
, y
);
899 const oppCol
= V
.GetOppCol(c
);
903 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
904 const castlingKing
= this.board
[x
][y
].charAt(1);
908 castleSide
++ //large, then small
910 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
911 // If this code is reached, rook and king are on initial position
913 // NOTE: in some variants this is not a rook
914 const rookPos
= this.castleFlags
[c
][castleSide
];
915 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
917 this.board
[x
][rookPos
] == V
.EMPTY
||
918 this.getColor(x
, rookPos
) != c
||
919 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
921 // Rook is not here, or changed color (see Benedict)
925 // Nothing on the path of the king ? (and no checks)
926 const finDist
= finalSquares
[castleSide
][0] - y
;
927 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
931 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
933 this.board
[x
][i
] != V
.EMPTY
&&
934 // NOTE: next check is enough, because of chessboard constraints
935 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
938 continue castlingCheck
;
941 } while (i
!= finalSquares
[castleSide
][0]);
943 // Nothing on the path to the rook?
944 step
= castleSide
== 0 ? -1 : 1;
945 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
946 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
949 // Nothing on final squares, except maybe king and castling rook?
950 for (i
= 0; i
< 2; i
++) {
952 finalSquares
[castleSide
][i
] != rookPos
&&
953 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
955 finalSquares
[castleSide
][i
] != y
||
956 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
959 continue castlingCheck
;
963 // If this code is reached, castle is valid
969 y: finalSquares
[castleSide
][0],
975 y: finalSquares
[castleSide
][1],
981 // King might be initially disguised (Titan...)
982 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
983 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
986 Math
.abs(y
- rookPos
) <= 2
987 ? { x: x
, y: rookPos
}
988 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
999 // For the interface: possible moves for the current turn from square sq
1000 getPossibleMovesFrom(sq
) {
1001 return this.filterValid(this.getPotentialMovesFrom(sq
));
1004 // TODO: promotions (into R,B,N,Q) should be filtered only once
1005 filterValid(moves
) {
1006 if (moves
.length
== 0) return [];
1007 const color
= this.turn
;
1008 return moves
.filter(m
=> {
1010 const res
= !this.underCheck(color
);
1016 getAllPotentialMoves() {
1017 const color
= this.turn
;
1018 let potentialMoves
= [];
1019 for (let i
= 0; i
< V
.size
.x
; i
++) {
1020 for (let j
= 0; j
< V
.size
.y
; j
++) {
1021 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1022 Array
.prototype.push
.apply(
1024 this.getPotentialMovesFrom([i
, j
])
1029 return potentialMoves
;
1032 // Search for all valid moves considering current turn
1033 // (for engine and game end)
1034 getAllValidMoves() {
1035 return this.filterValid(this.getAllPotentialMoves());
1038 // Stop at the first move found
1039 // TODO: not really, it explores all moves from a square (one is enough).
1041 const color
= this.turn
;
1042 for (let i
= 0; i
< V
.size
.x
; i
++) {
1043 for (let j
= 0; j
< V
.size
.y
; j
++) {
1044 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1045 const moves
= this.getPotentialMovesFrom([i
, j
]);
1046 if (moves
.length
> 0) {
1047 for (let k
= 0; k
< moves
.length
; k
++)
1048 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1056 // Check if pieces of given color are attacking (king) on square x,y
1057 isAttacked(sq
, color
) {
1059 this.isAttackedByPawn(sq
, color
) ||
1060 this.isAttackedByRook(sq
, color
) ||
1061 this.isAttackedByKnight(sq
, color
) ||
1062 this.isAttackedByBishop(sq
, color
) ||
1063 this.isAttackedByQueen(sq
, color
) ||
1064 this.isAttackedByKing(sq
, color
)
1068 // Generic method for non-pawn pieces ("sliding or jumping"):
1069 // is x,y attacked by a piece of given color ?
1070 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1071 for (let step
of steps
) {
1072 let rx
= x
+ step
[0],
1074 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1079 V
.OnBoard(rx
, ry
) &&
1080 this.getPiece(rx
, ry
) == piece
&&
1081 this.getColor(rx
, ry
) == color
1089 // Is square x,y attacked by 'color' pawns ?
1090 isAttackedByPawn(sq
, color
) {
1091 const pawnShift
= (color
== "w" ? 1 : -1);
1092 return this.isAttackedBySlideNJump(
1096 [[pawnShift
, 1], [pawnShift
, -1]],
1101 // Is square x,y attacked by 'color' rooks ?
1102 isAttackedByRook(sq
, color
) {
1103 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1106 // Is square x,y attacked by 'color' knights ?
1107 isAttackedByKnight(sq
, color
) {
1108 return this.isAttackedBySlideNJump(
1117 // Is square x,y attacked by 'color' bishops ?
1118 isAttackedByBishop(sq
, color
) {
1119 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1122 // Is square x,y attacked by 'color' queens ?
1123 isAttackedByQueen(sq
, color
) {
1124 return this.isAttackedBySlideNJump(
1128 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1132 // Is square x,y attacked by 'color' king(s) ?
1133 isAttackedByKing(sq
, color
) {
1134 return this.isAttackedBySlideNJump(
1138 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1143 // Is color under check after his move ?
1145 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1151 // Apply a move on board
1152 static PlayOnBoard(board
, move) {
1153 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1154 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1156 // Un-apply the played move
1157 static UndoOnBoard(board
, move) {
1158 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1159 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1166 // if (!this.states) this.states = [];
1167 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1168 // this.states.push(stateFen);
1171 // Save flags (for undo)
1172 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1173 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1174 V
.PlayOnBoard(this.board
, move);
1175 this.turn
= V
.GetOppCol(this.turn
);
1177 this.postPlay(move);
1180 updateCastleFlags(move, piece
, color
) {
1181 const c
= color
|| V
.GetOppCol(this.turn
);
1182 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1183 // Update castling flags if rooks are moved
1184 const oppCol
= this.turn
;
1185 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1186 if (piece
== V
.KING
&& move.appear
.length
> 0)
1187 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1189 move.start
.x
== firstRank
&& //our rook moves?
1190 this.castleFlags
[c
].includes(move.start
.y
)
1192 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1193 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1195 // NOTE: not "else if" because a rook could take an opposing rook
1197 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1198 this.castleFlags
[oppCol
].includes(move.end
.y
)
1200 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1201 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1205 // After move is played, update variables + flags
1207 const c
= V
.GetOppCol(this.turn
);
1208 let piece
= undefined;
1209 if (move.vanish
.length
>= 1)
1210 // Usual case, something is moved
1211 piece
= move.vanish
[0].p
;
1213 // Crazyhouse-like variants
1214 piece
= move.appear
[0].p
;
1216 // Update king position + flags
1217 if (piece
== V
.KING
&& move.appear
.length
> 0)
1218 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1219 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1226 if (V
.HasEnpassant
) this.epSquares
.pop();
1227 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1228 V
.UndoOnBoard(this.board
, move);
1229 this.turn
= V
.GetOppCol(this.turn
);
1231 this.postUndo(move);
1234 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1235 // if (stateFen != this.states[this.states.length-1]) debugger;
1236 // this.states.pop();
1239 // After move is undo-ed *and flags resetted*, un-update other variables
1240 // TODO: more symmetry, by storing flags increment in move (?!)
1242 // (Potentially) Reset king position
1243 const c
= this.getColor(move.start
.x
, move.start
.y
);
1244 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1245 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1251 // What is the score ? (Interesting if game is over)
1253 if (this.atLeastOneMove()) return "*";
1255 const color
= this.turn
;
1256 // No valid move: stalemate or checkmate?
1257 if (!this.underCheck(color
)) return "1/2";
1259 return (color
== "w" ? "0-1" : "1-0");
1266 static get VALUES() {
1277 // "Checkmate" (unreachable eval)
1278 static get INFINITY() {
1282 // At this value or above, the game is over
1283 static get THRESHOLD_MATE() {
1287 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1288 static get SEARCH_DEPTH() {
1292 // 'movesList' arg for some variants to provide a custom list
1293 getComputerMove(movesList
) {
1294 const maxeval
= V
.INFINITY
;
1295 const color
= this.turn
;
1296 let moves1
= movesList
|| this.getAllValidMoves();
1298 if (moves1
.length
== 0)
1299 // TODO: this situation should not happen
1302 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1303 for (let i
= 0; i
< moves1
.length
; i
++) {
1304 this.play(moves1
[i
]);
1305 const score1
= this.getCurrentScore();
1306 if (score1
!= "*") {
1310 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1312 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1313 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1314 this.undo(moves1
[i
]);
1317 // Initial self evaluation is very low: "I'm checkmated"
1318 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1319 // Initial enemy evaluation is very low too, for him
1320 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1321 // Second half-move:
1322 let moves2
= this.getAllValidMoves();
1323 for (let j
= 0; j
< moves2
.length
; j
++) {
1324 this.play(moves2
[j
]);
1325 const score2
= this.getCurrentScore();
1326 let evalPos
= 0; //1/2 value
1329 evalPos
= this.evalPosition();
1339 (color
== "w" && evalPos
< eval2
) ||
1340 (color
== "b" && evalPos
> eval2
)
1344 this.undo(moves2
[j
]);
1347 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1348 (color
== "b" && eval2
< moves1
[i
].eval
)
1350 moves1
[i
].eval
= eval2
;
1352 this.undo(moves1
[i
]);
1354 moves1
.sort((a
, b
) => {
1355 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1357 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1359 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1360 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1361 for (let i
= 0; i
< moves1
.length
; i
++) {
1362 this.play(moves1
[i
]);
1363 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1365 0.1 * moves1
[i
].eval
+
1366 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1367 this.undo(moves1
[i
]);
1369 moves1
.sort((a
, b
) => {
1370 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1374 let candidates
= [0];
1375 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1377 return moves1
[candidates
[randInt(candidates
.length
)]];
1380 alphabeta(depth
, alpha
, beta
) {
1381 const maxeval
= V
.INFINITY
;
1382 const color
= this.turn
;
1383 const score
= this.getCurrentScore();
1385 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1386 if (depth
== 0) return this.evalPosition();
1387 const moves
= this.getAllValidMoves();
1388 let v
= color
== "w" ? -maxeval : maxeval
;
1390 for (let i
= 0; i
< moves
.length
; i
++) {
1391 this.play(moves
[i
]);
1392 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1393 this.undo(moves
[i
]);
1394 alpha
= Math
.max(alpha
, v
);
1395 if (alpha
>= beta
) break; //beta cutoff
1400 for (let i
= 0; i
< moves
.length
; i
++) {
1401 this.play(moves
[i
]);
1402 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1403 this.undo(moves
[i
]);
1404 beta
= Math
.min(beta
, v
);
1405 if (alpha
>= beta
) break; //alpha cutoff
1413 // Just count material for now
1414 for (let i
= 0; i
< V
.size
.x
; i
++) {
1415 for (let j
= 0; j
< V
.size
.y
; j
++) {
1416 if (this.board
[i
][j
] != V
.EMPTY
) {
1417 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1418 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1425 /////////////////////////
1426 // MOVES + GAME NOTATION
1427 /////////////////////////
1429 // Context: just before move is played, turn hasn't changed
1430 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1432 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1434 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1436 // Translate final square
1437 const finalSquare
= V
.CoordsToSquare(move.end
);
1439 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1440 if (piece
== V
.PAWN
) {
1443 if (move.vanish
.length
> move.appear
.length
) {
1445 const startColumn
= V
.CoordToColumn(move.start
.y
);
1446 notation
= startColumn
+ "x" + finalSquare
;
1448 else notation
= finalSquare
;
1449 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1451 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1456 piece
.toUpperCase() +
1457 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1462 static GetUnambiguousNotation(move) {
1463 // Machine-readable format with all the informations about the move
1465 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1466 ? V
.CoordsToSquare(move.start
)
1469 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1470 ? V
.CoordsToSquare(move.end
)
1473 (!!move.appear
&& move.appear
.length
> 0
1474 ? move.appear
.map(a
=>
1475 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1478 (!!move.vanish
&& move.vanish
.length
> 0
1479 ? move.vanish
.map(a
=>
1480 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")