ee13d5ebe87d8c900ecfab55df01e07ee30bec0c
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
{
36 // Some variants don't have flags:
37 static get HasFlags() {
42 static get HasCastle() {
46 // Pawns specifications
47 static get PawnSpecs() {
49 directions: { 'w': -1, 'b': 1 },
50 initShift: { w: 1, b: 1 },
53 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
55 captureBackward: false,
60 // En-passant captures need a stack of squares:
61 static get HasEnpassant() {
65 // Some variants cannot have analyse mode
66 static get CanAnalyze() {
69 // Patch: issues with javascript OOP, objects can't access static fields.
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
83 // Sometimes moves must remain hidden until game ends
84 static get SomeHiddenMoves() {
87 get someHiddenMoves() {
88 return V
.SomeHiddenMoves
;
91 // Generally true, unless the variant includes random effects
92 static get CorrConfirm() {
96 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
101 // Some variants always show the same orientation
102 static get CanFlip() {
109 // For (generally old) variants without checkered board
110 static get Monochrome() {
114 // Some variants require lines drawing
118 // Draw all inter-squares lines
119 for (let i
= 0; i
<= V
.size
.x
; i
++)
120 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
121 for (let j
= 0; j
<= V
.size
.y
; j
++)
122 lines
.push([[0, j
], [V
.size
.x
, j
]]);
128 // Some variants use click infos:
133 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
138 static get IMAGE_EXTENSION() {
139 // All pieces should be in the SVG format
143 // Turn "wb" into "B" (for FEN)
144 static board2fen(b
) {
145 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
148 // Turn "p" into "bp" (for board)
149 static fen2board(f
) {
150 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
153 // Check if FEN describes a board situation correctly
154 static IsGoodFen(fen
) {
155 const fenParsed
= V
.ParseFen(fen
);
157 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
159 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
160 // 3) Check moves count
161 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
164 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
166 // 5) Check enpassant
169 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
176 // Is position part of the FEN a priori correct?
177 static IsGoodPosition(position
) {
178 if (position
.length
== 0) return false;
179 const rows
= position
.split("/");
180 if (rows
.length
!= V
.size
.x
) return false;
181 let kings
= { "k": 0, "K": 0 };
182 for (let row
of rows
) {
184 for (let i
= 0; i
< row
.length
; i
++) {
185 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
186 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
188 const num
= parseInt(row
[i
]);
189 if (isNaN(num
)) return false;
193 if (sumElts
!= V
.size
.y
) return false;
195 // Both kings should be on board. Exactly one per color.
196 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
201 static IsGoodTurn(turn
) {
202 return ["w", "b"].includes(turn
);
206 static IsGoodFlags(flags
) {
207 // NOTE: a little too permissive to work with more variants
208 return !!flags
.match(/^[a-z]{4,4}$/);
211 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
212 static IsGoodEnpassant(enpassant
) {
213 if (enpassant
!= "-") {
214 const ep
= V
.SquareToCoords(enpassant
);
215 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
220 // 3 --> d (column number to letter)
221 static CoordToColumn(colnum
) {
222 return String
.fromCharCode(97 + colnum
);
225 // d --> 3 (column letter to number)
226 static ColumnToCoord(column
) {
227 return column
.charCodeAt(0) - 97;
231 static SquareToCoords(sq
) {
233 // NOTE: column is always one char => max 26 columns
234 // row is counted from black side => subtraction
235 x: V
.size
.x
- parseInt(sq
.substr(1)),
236 y: sq
[0].charCodeAt() - 97
241 static CoordsToSquare(coords
) {
242 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
245 // Path to pieces (standard ones in pieces/ folder)
250 // Path to promotion pieces (usually the same)
252 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
255 // Aggregates flags into one object
257 return this.castleFlags
;
261 disaggregateFlags(flags
) {
262 this.castleFlags
= flags
;
265 // En-passant square, if any
266 getEpSquare(moveOrSquare
) {
267 if (!moveOrSquare
) return undefined;
268 if (typeof moveOrSquare
=== "string") {
269 const square
= moveOrSquare
;
270 if (square
== "-") return undefined;
271 return V
.SquareToCoords(square
);
273 // Argument is a move:
274 const move = moveOrSquare
;
275 const s
= move.start
,
279 Math
.abs(s
.x
- e
.x
) == 2 &&
280 // Next conditions for variants like Atomic or Rifle, Recycle...
281 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
282 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
289 return undefined; //default
292 // Can thing on square1 take thing on square2
293 canTake([x1
, y1
], [x2
, y2
]) {
294 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
297 // Is (x,y) on the chessboard?
298 static OnBoard(x
, y
) {
299 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
302 // Used in interface: 'side' arg == player color
303 canIplay(side
, [x
, y
]) {
304 return this.turn
== side
&& this.getColor(x
, y
) == side
;
307 // On which squares is color under check ? (for interface)
309 const color
= this.turn
;
311 this.underCheck(color
)
312 // kingPos must be duplicated, because it may change:
313 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
321 // Setup the initial random (asymmetric) position
322 static GenRandInitFen(randomness
) {
325 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
327 let pieces
= { w: new Array(8), b: new Array(8) };
329 // Shuffle pieces on first (and last rank if randomness == 2)
330 for (let c
of ["w", "b"]) {
331 if (c
== 'b' && randomness
== 1) {
332 pieces
['b'] = pieces
['w'];
337 let positions
= ArrayFun
.range(8);
339 // Get random squares for bishops
340 let randIndex
= 2 * randInt(4);
341 const bishop1Pos
= positions
[randIndex
];
342 // The second bishop must be on a square of different color
343 let randIndex_tmp
= 2 * randInt(4) + 1;
344 const bishop2Pos
= positions
[randIndex_tmp
];
345 // Remove chosen squares
346 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
347 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
349 // Get random squares for knights
350 randIndex
= randInt(6);
351 const knight1Pos
= positions
[randIndex
];
352 positions
.splice(randIndex
, 1);
353 randIndex
= randInt(5);
354 const knight2Pos
= positions
[randIndex
];
355 positions
.splice(randIndex
, 1);
357 // Get random square for queen
358 randIndex
= randInt(4);
359 const queenPos
= positions
[randIndex
];
360 positions
.splice(randIndex
, 1);
362 // Rooks and king positions are now fixed,
363 // because of the ordering rook-king-rook
364 const rook1Pos
= positions
[0];
365 const kingPos
= positions
[1];
366 const rook2Pos
= positions
[2];
368 // Finally put the shuffled pieces in the board array
369 pieces
[c
][rook1Pos
] = "r";
370 pieces
[c
][knight1Pos
] = "n";
371 pieces
[c
][bishop1Pos
] = "b";
372 pieces
[c
][queenPos
] = "q";
373 pieces
[c
][kingPos
] = "k";
374 pieces
[c
][bishop2Pos
] = "b";
375 pieces
[c
][knight2Pos
] = "n";
376 pieces
[c
][rook2Pos
] = "r";
377 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
379 // Add turn + flags + enpassant
381 pieces
["b"].join("") +
382 "/pppppppp/8/8/8/8/PPPPPPPP/" +
383 pieces
["w"].join("").toUpperCase() +
384 " w 0 " + flags
+ " -"
388 // "Parse" FEN: just return untransformed string data
389 static ParseFen(fen
) {
390 const fenParts
= fen
.split(" ");
392 position: fenParts
[0],
394 movesCount: fenParts
[2]
397 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
398 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
402 // Return current fen (game state)
405 this.getBaseFen() + " " +
406 this.getTurnFen() + " " +
408 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
409 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
414 // Omit movesCount, only variable allowed to differ
416 this.getBaseFen() + "_" +
418 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
419 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
423 // Position part of the FEN string
425 const format
= (count
) => {
426 // if more than 9 consecutive free spaces, break the integer,
427 // otherwise FEN parsing will fail.
428 if (count
<= 9) return count
;
429 // Currently only boards of size up to 11 or 12:
430 return "9" + (count
- 9);
433 for (let i
= 0; i
< V
.size
.x
; i
++) {
435 for (let j
= 0; j
< V
.size
.y
; j
++) {
436 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
438 if (emptyCount
> 0) {
439 // Add empty squares in-between
440 position
+= format(emptyCount
);
443 position
+= V
.board2fen(this.board
[i
][j
]);
446 if (emptyCount
> 0) {
448 position
+= format(emptyCount
);
450 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
459 // Flags part of the FEN string
463 for (let c
of ["w", "b"])
464 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
468 // Enpassant part of the FEN string
470 const L
= this.epSquares
.length
;
471 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
472 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
475 // Turn position fen into double array ["wb","wp","bk",...]
476 static GetBoard(position
) {
477 const rows
= position
.split("/");
478 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
479 for (let i
= 0; i
< rows
.length
; i
++) {
481 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
482 const character
= rows
[i
][indexInRow
];
483 const num
= parseInt(character
);
484 // If num is a number, just shift j:
485 if (!isNaN(num
)) j
+= num
;
486 // Else: something at position i,j
487 else board
[i
][j
++] = V
.fen2board(character
);
493 // Extract (relevant) flags from fen
495 // white a-castle, h-castle, black a-castle, h-castle
496 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
497 for (let i
= 0; i
< 4; i
++) {
498 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
499 V
.ColumnToCoord(fenflags
.charAt(i
));
506 // Fen string fully describes the game state
509 // In printDiagram() fen isn't supply because only getPpath() is used
510 // TODO: find a better solution!
512 const fenParsed
= V
.ParseFen(fen
);
513 this.board
= V
.GetBoard(fenParsed
.position
);
514 this.turn
= fenParsed
.turn
;
515 this.movesCount
= parseInt(fenParsed
.movesCount
);
516 this.setOtherVariables(fen
);
519 // Scan board for kings positions
521 this.INIT_COL_KING
= { w: -1, b: -1 };
522 // Squares of white and black king:
523 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
524 const fenRows
= V
.ParseFen(fen
).position
.split("/");
525 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
526 for (let i
= 0; i
< fenRows
.length
; i
++) {
527 let k
= 0; //column index on board
528 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
529 switch (fenRows
[i
].charAt(j
)) {
531 this.kingPos
["b"] = [i
, k
];
532 this.INIT_COL_KING
["b"] = k
;
535 this.kingPos
["w"] = [i
, k
];
536 this.INIT_COL_KING
["w"] = k
;
539 const num
= parseInt(fenRows
[i
].charAt(j
));
540 if (!isNaN(num
)) k
+= num
- 1;
548 // Some additional variables from FEN (variant dependant)
549 setOtherVariables(fen
) {
550 // Set flags and enpassant:
551 const parsedFen
= V
.ParseFen(fen
);
552 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
553 if (V
.HasEnpassant
) {
555 parsedFen
.enpassant
!= "-"
556 ? this.getEpSquare(parsedFen
.enpassant
)
558 this.epSquares
= [epSq
];
560 // Search for kings positions:
564 /////////////////////
568 return { x: 8, y: 8 };
571 // Color of thing on square (i,j). 'undefined' if square is empty
573 return this.board
[i
][j
].charAt(0);
576 // Piece type on square (i,j). 'undefined' if square is empty
578 return this.board
[i
][j
].charAt(1);
581 // Get opponent color
582 static GetOppCol(color
) {
583 return color
== "w" ? "b" : "w";
586 // Pieces codes (for a clearer code)
593 static get KNIGHT() {
596 static get BISHOP() {
607 static get PIECES() {
608 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
616 // Some pieces movements
647 // All possible moves from selected square
648 getPotentialMovesFrom([x
, y
]) {
649 switch (this.getPiece(x
, y
)) {
651 return this.getPotentialPawnMoves([x
, y
]);
653 return this.getPotentialRookMoves([x
, y
]);
655 return this.getPotentialKnightMoves([x
, y
]);
657 return this.getPotentialBishopMoves([x
, y
]);
659 return this.getPotentialQueenMoves([x
, y
]);
661 return this.getPotentialKingMoves([x
, y
]);
663 return []; //never reached
666 // Build a regular move from its initial and destination squares.
667 // tr: transformation
668 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
669 const initColor
= this.getColor(sx
, sy
);
670 const initPiece
= this.getPiece(sx
, sy
);
676 c: tr
? tr
.c : initColor
,
677 p: tr
? tr
.p : initPiece
690 // The opponent piece disappears if we take it
691 if (this.board
[ex
][ey
] != V
.EMPTY
) {
696 c: this.getColor(ex
, ey
),
697 p: this.getPiece(ex
, ey
)
705 // Generic method to find possible moves of non-pawn pieces:
706 // "sliding or jumping"
707 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
709 outerLoop: for (let step
of steps
) {
712 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
713 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
714 if (oneStep
) continue outerLoop
;
718 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
719 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
724 // Special case of en-passant captures: treated separately
725 getEnpassantCaptures([x
, y
], shiftX
) {
726 const Lep
= this.epSquares
.length
;
727 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
728 let enpassantMove
= null;
731 epSquare
.x
== x
+ shiftX
&&
732 Math
.abs(epSquare
.y
- y
) == 1
734 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
735 enpassantMove
.vanish
.push({
738 // Captured piece is usually a pawn, but next line seems harmless
739 p: this.getPiece(x
, epSquare
.y
),
740 c: this.getColor(x
, epSquare
.y
)
743 return !!enpassantMove
? [enpassantMove
] : [];
746 // Consider all potential promotions:
747 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
748 let finalPieces
= [V
.PAWN
];
749 const color
= this.turn
; //this.getColor(x1, y1);
750 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
751 if (x2
== lastRank
) {
752 // promotions arg: special override for Hiddenqueen variant
753 if (!!promotions
) finalPieces
= promotions
;
754 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
757 for (let piece
of finalPieces
) {
758 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
759 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
763 // What are the pawn moves from square x,y ?
764 getPotentialPawnMoves([x
, y
], promotions
) {
765 const color
= this.turn
; //this.getColor(x, y);
766 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
767 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
768 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
769 const forward
= (color
== 'w' ? -1 : 1);
771 // Pawn movements in shiftX direction:
772 const getPawnMoves
= (shiftX
) => {
774 // NOTE: next condition is generally true (no pawn on last rank)
775 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
776 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
777 // One square forward (or backward)
778 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
779 // Next condition because pawns on 1st rank can generally jump
781 V
.PawnSpecs
.twoSquares
&&
783 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
785 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
790 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
793 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
795 V
.PawnSpecs
.threeSquares
&&
796 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
798 // Three squares jump
799 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
805 if (V
.PawnSpecs
.canCapture
) {
806 for (let shiftY
of [-1, 1]) {
807 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
809 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
810 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
813 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
818 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
819 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
820 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
821 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
824 [x
, y
], [x
- shiftX
, y
+ shiftY
],
835 let pMoves
= getPawnMoves(pawnShiftX
);
836 if (V
.PawnSpecs
.bidirectional
)
837 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
839 if (V
.HasEnpassant
) {
840 // NOTE: backward en-passant captures are not considered
841 // because no rules define them (for now).
842 Array
.prototype.push
.apply(
844 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
851 // What are the rook moves from square x,y ?
852 getPotentialRookMoves(sq
) {
853 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
856 // What are the knight moves from square x,y ?
857 getPotentialKnightMoves(sq
) {
858 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
861 // What are the bishop moves from square x,y ?
862 getPotentialBishopMoves(sq
) {
863 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
866 // What are the queen moves from square x,y ?
867 getPotentialQueenMoves(sq
) {
868 return this.getSlideNJumpMoves(
870 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
874 // What are the king moves from square x,y ?
875 getPotentialKingMoves(sq
) {
876 // Initialize with normal moves
877 let moves
= this.getSlideNJumpMoves(
879 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
882 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
886 // "castleInCheck" arg to let some variants castle under check
887 getCastleMoves([x
, y
], castleInCheck
) {
888 const c
= this.getColor(x
, y
);
889 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
890 return []; //x isn't first rank, or king has moved (shortcut)
893 const oppCol
= V
.GetOppCol(c
);
897 const finalSquares
= [
899 [V
.size
.y
- 2, V
.size
.y
- 3]
904 castleSide
++ //large, then small
906 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
907 // If this code is reached, rook and king are on initial position
909 // NOTE: in some variants this is not a rook
910 const rookPos
= this.castleFlags
[c
][castleSide
];
911 if (this.board
[x
][rookPos
] == V
.EMPTY
|| this.getColor(x
, rookPos
) != c
)
912 // Rook is not here, or changed color (see Benedict)
915 // Nothing on the path of the king ? (and no checks)
916 const castlingPiece
= this.getPiece(x
, rookPos
);
917 const finDist
= finalSquares
[castleSide
][0] - y
;
918 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
922 // NOTE: "castling" arg is used by some variants (Monster),
923 // where "isAttacked" is overloaded in an infinite-recursive way.
924 // TODO: not used anymore (Monster + Doublemove2 are simplified).
925 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
, "castling")) ||
926 (this.board
[x
][i
] != V
.EMPTY
&&
927 // NOTE: next check is enough, because of chessboard constraints
928 (this.getColor(x
, i
) != c
||
929 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
931 continue castlingCheck
;
934 } while (i
!= finalSquares
[castleSide
][0]);
936 // Nothing on the path to the rook?
937 step
= castleSide
== 0 ? -1 : 1;
938 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
939 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
942 // Nothing on final squares, except maybe king and castling rook?
943 for (i
= 0; i
< 2; i
++) {
945 finalSquares
[castleSide
][i
] != rookPos
&&
946 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
948 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
||
949 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
952 continue castlingCheck
;
956 // If this code is reached, castle is valid
962 y: finalSquares
[castleSide
][0],
968 y: finalSquares
[castleSide
][1],
974 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
975 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
978 Math
.abs(y
- rookPos
) <= 2
979 ? { x: x
, y: rookPos
}
980 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
991 // For the interface: possible moves for the current turn from square sq
992 getPossibleMovesFrom(sq
) {
993 return this.filterValid(this.getPotentialMovesFrom(sq
));
996 // TODO: promotions (into R,B,N,Q) should be filtered only once
998 if (moves
.length
== 0) return [];
999 const color
= this.turn
;
1000 return moves
.filter(m
=> {
1002 const res
= !this.underCheck(color
);
1008 getAllPotentialMoves() {
1009 const color
= this.turn
;
1010 let potentialMoves
= [];
1011 for (let i
= 0; i
< V
.size
.x
; i
++) {
1012 for (let j
= 0; j
< V
.size
.y
; j
++) {
1013 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1014 Array
.prototype.push
.apply(
1016 this.getPotentialMovesFrom([i
, j
])
1021 return potentialMoves
;
1024 // Search for all valid moves considering current turn
1025 // (for engine and game end)
1026 getAllValidMoves() {
1027 return this.filterValid(this.getAllPotentialMoves());
1030 // Stop at the first move found
1031 // TODO: not really, it explores all moves from a square (one is enough).
1033 const color
= this.turn
;
1034 for (let i
= 0; i
< V
.size
.x
; i
++) {
1035 for (let j
= 0; j
< V
.size
.y
; j
++) {
1036 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1037 const moves
= this.getPotentialMovesFrom([i
, j
]);
1038 if (moves
.length
> 0) {
1039 for (let k
= 0; k
< moves
.length
; k
++)
1040 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1048 // Check if pieces of given color are attacking (king) on square x,y
1049 isAttacked(sq
, color
) {
1051 this.isAttackedByPawn(sq
, color
) ||
1052 this.isAttackedByRook(sq
, color
) ||
1053 this.isAttackedByKnight(sq
, color
) ||
1054 this.isAttackedByBishop(sq
, color
) ||
1055 this.isAttackedByQueen(sq
, color
) ||
1056 this.isAttackedByKing(sq
, color
)
1060 // Generic method for non-pawn pieces ("sliding or jumping"):
1061 // is x,y attacked by a piece of given color ?
1062 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1063 for (let step
of steps
) {
1064 let rx
= x
+ step
[0],
1066 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1071 V
.OnBoard(rx
, ry
) &&
1072 this.getPiece(rx
, ry
) == piece
&&
1073 this.getColor(rx
, ry
) == color
1081 // Is square x,y attacked by 'color' pawns ?
1082 isAttackedByPawn(sq
, color
) {
1083 const pawnShift
= (color
== "w" ? 1 : -1);
1084 return this.isAttackedBySlideNJump(
1088 [[pawnShift
, 1], [pawnShift
, -1]],
1093 // Is square x,y attacked by 'color' rooks ?
1094 isAttackedByRook(sq
, color
) {
1095 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1098 // Is square x,y attacked by 'color' knights ?
1099 isAttackedByKnight(sq
, color
) {
1100 return this.isAttackedBySlideNJump(
1109 // Is square x,y attacked by 'color' bishops ?
1110 isAttackedByBishop(sq
, color
) {
1111 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1114 // Is square x,y attacked by 'color' queens ?
1115 isAttackedByQueen(sq
, color
) {
1116 return this.isAttackedBySlideNJump(
1120 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1124 // Is square x,y attacked by 'color' king(s) ?
1125 isAttackedByKing(sq
, color
) {
1126 return this.isAttackedBySlideNJump(
1130 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1135 // Is color under check after his move ?
1137 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1143 // Apply a move on board
1144 static PlayOnBoard(board
, move) {
1145 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1146 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1148 // Un-apply the played move
1149 static UndoOnBoard(board
, move) {
1150 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1151 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1158 // if (!this.states) this.states = [];
1159 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1160 // this.states.push(stateFen);
1163 // Save flags (for undo)
1164 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1165 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1166 V
.PlayOnBoard(this.board
, move);
1167 this.turn
= V
.GetOppCol(this.turn
);
1169 this.postPlay(move);
1172 updateCastleFlags(move, piece
) {
1173 const c
= V
.GetOppCol(this.turn
);
1174 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1175 // Update castling flags if rooks are moved
1176 const oppCol
= this.turn
;
1177 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1178 if (piece
== V
.KING
&& move.appear
.length
> 0)
1179 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1181 move.start
.x
== firstRank
&& //our rook moves?
1182 this.castleFlags
[c
].includes(move.start
.y
)
1184 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1185 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1187 // NOTE: not "else if" because a rook could take an opposing rook
1189 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1190 this.castleFlags
[oppCol
].includes(move.end
.y
)
1192 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1193 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1197 // After move is played, update variables + flags
1199 const c
= V
.GetOppCol(this.turn
);
1200 let piece
= undefined;
1201 if (move.vanish
.length
>= 1)
1202 // Usual case, something is moved
1203 piece
= move.vanish
[0].p
;
1205 // Crazyhouse-like variants
1206 piece
= move.appear
[0].p
;
1208 // Update king position + flags
1209 if (piece
== V
.KING
&& move.appear
.length
> 0)
1210 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1211 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1218 if (V
.HasEnpassant
) this.epSquares
.pop();
1219 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1220 V
.UndoOnBoard(this.board
, move);
1221 this.turn
= V
.GetOppCol(this.turn
);
1223 this.postUndo(move);
1226 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1227 // if (stateFen != this.states[this.states.length-1]) debugger;
1228 // this.states.pop();
1231 // After move is undo-ed *and flags resetted*, un-update other variables
1232 // TODO: more symmetry, by storing flags increment in move (?!)
1234 // (Potentially) Reset king position
1235 const c
= this.getColor(move.start
.x
, move.start
.y
);
1236 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1237 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1243 // What is the score ? (Interesting if game is over)
1245 if (this.atLeastOneMove()) return "*";
1247 const color
= this.turn
;
1248 // No valid move: stalemate or checkmate?
1249 if (!this.underCheck(color
)) return "1/2";
1251 return (color
== "w" ? "0-1" : "1-0");
1258 static get VALUES() {
1269 // "Checkmate" (unreachable eval)
1270 static get INFINITY() {
1274 // At this value or above, the game is over
1275 static get THRESHOLD_MATE() {
1279 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1280 static get SEARCH_DEPTH() {
1284 // 'movesList' arg for some variants to provide a custom list
1285 getComputerMove(movesList
) {
1286 const maxeval
= V
.INFINITY
;
1287 const color
= this.turn
;
1288 let moves1
= movesList
|| this.getAllValidMoves();
1290 if (moves1
.length
== 0)
1291 // TODO: this situation should not happen
1294 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1295 for (let i
= 0; i
< moves1
.length
; i
++) {
1296 this.play(moves1
[i
]);
1297 const score1
= this.getCurrentScore();
1298 if (score1
!= "*") {
1302 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1304 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1305 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1306 this.undo(moves1
[i
]);
1309 // Initial self evaluation is very low: "I'm checkmated"
1310 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1311 // Initial enemy evaluation is very low too, for him
1312 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1313 // Second half-move:
1314 let moves2
= this.getAllValidMoves();
1315 for (let j
= 0; j
< moves2
.length
; j
++) {
1316 this.play(moves2
[j
]);
1317 const score2
= this.getCurrentScore();
1318 let evalPos
= 0; //1/2 value
1321 evalPos
= this.evalPosition();
1331 (color
== "w" && evalPos
< eval2
) ||
1332 (color
== "b" && evalPos
> eval2
)
1336 this.undo(moves2
[j
]);
1339 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1340 (color
== "b" && eval2
< moves1
[i
].eval
)
1342 moves1
[i
].eval
= eval2
;
1344 this.undo(moves1
[i
]);
1346 moves1
.sort((a
, b
) => {
1347 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1349 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1351 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1352 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1353 for (let i
= 0; i
< moves1
.length
; i
++) {
1354 this.play(moves1
[i
]);
1355 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1357 0.1 * moves1
[i
].eval
+
1358 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1359 this.undo(moves1
[i
]);
1361 moves1
.sort((a
, b
) => {
1362 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1366 let candidates
= [0];
1367 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1369 return moves1
[candidates
[randInt(candidates
.length
)]];
1372 alphabeta(depth
, alpha
, beta
) {
1373 const maxeval
= V
.INFINITY
;
1374 const color
= this.turn
;
1375 const score
= this.getCurrentScore();
1377 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1378 if (depth
== 0) return this.evalPosition();
1379 const moves
= this.getAllValidMoves();
1380 let v
= color
== "w" ? -maxeval : maxeval
;
1382 for (let i
= 0; i
< moves
.length
; i
++) {
1383 this.play(moves
[i
]);
1384 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1385 this.undo(moves
[i
]);
1386 alpha
= Math
.max(alpha
, v
);
1387 if (alpha
>= beta
) break; //beta cutoff
1392 for (let i
= 0; i
< moves
.length
; i
++) {
1393 this.play(moves
[i
]);
1394 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1395 this.undo(moves
[i
]);
1396 beta
= Math
.min(beta
, v
);
1397 if (alpha
>= beta
) break; //alpha cutoff
1405 // Just count material for now
1406 for (let i
= 0; i
< V
.size
.x
; i
++) {
1407 for (let j
= 0; j
< V
.size
.y
; j
++) {
1408 if (this.board
[i
][j
] != V
.EMPTY
) {
1409 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1410 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1417 /////////////////////////
1418 // MOVES + GAME NOTATION
1419 /////////////////////////
1421 // Context: just before move is played, turn hasn't changed
1422 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1424 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1426 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1428 // Translate final square
1429 const finalSquare
= V
.CoordsToSquare(move.end
);
1431 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1432 if (piece
== V
.PAWN
) {
1435 if (move.vanish
.length
> move.appear
.length
) {
1437 const startColumn
= V
.CoordToColumn(move.start
.y
);
1438 notation
= startColumn
+ "x" + finalSquare
;
1440 else notation
= finalSquare
;
1441 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1443 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1448 piece
.toUpperCase() +
1449 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1454 static GetUnambiguousNotation(move) {
1455 // Machine-readable format with all the informations about the move
1457 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1458 ? V
.CoordsToSquare(move.start
)
1461 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1462 ? V
.CoordsToSquare(move.end
)
1465 (!!move.appear
&& move.appear
.length
> 0
1466 ? move.appear
.map(a
=>
1467 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1470 (!!move.vanish
&& move.vanish
.length
> 0
1471 ? move.vanish
.map(a
=>
1472 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")