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 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
88 // Some variants always show the same orientation
89 static get CanFlip() {
96 // Some variants use click infos:
101 static get IMAGE_EXTENSION() {
102 // All pieces should be in the SVG format
106 // Turn "wb" into "B" (for FEN)
107 static board2fen(b
) {
108 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
111 // Turn "p" into "bp" (for board)
112 static fen2board(f
) {
113 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
116 // Check if FEN describes a board situation correctly
117 static IsGoodFen(fen
) {
118 const fenParsed
= V
.ParseFen(fen
);
120 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
122 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
123 // 3) Check moves count
124 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
127 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
129 // 5) Check enpassant
132 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
139 // Is position part of the FEN a priori correct?
140 static IsGoodPosition(position
) {
141 if (position
.length
== 0) return false;
142 const rows
= position
.split("/");
143 if (rows
.length
!= V
.size
.x
) return false;
144 let kings
= { "k": 0, "K": 0 };
145 for (let row
of rows
) {
147 for (let i
= 0; i
< row
.length
; i
++) {
148 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
149 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
151 const num
= parseInt(row
[i
]);
152 if (isNaN(num
)) return false;
156 if (sumElts
!= V
.size
.y
) return false;
158 // Both kings should be on board. Exactly one per color.
159 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
164 static IsGoodTurn(turn
) {
165 return ["w", "b"].includes(turn
);
169 static IsGoodFlags(flags
) {
170 // NOTE: a little too permissive to work with more variants
171 return !!flags
.match(/^[a-z]{4,4}$/);
174 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
175 static IsGoodEnpassant(enpassant
) {
176 if (enpassant
!= "-") {
177 const ep
= V
.SquareToCoords(enpassant
);
178 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
183 // 3 --> d (column number to letter)
184 static CoordToColumn(colnum
) {
185 return String
.fromCharCode(97 + colnum
);
188 // d --> 3 (column letter to number)
189 static ColumnToCoord(column
) {
190 return column
.charCodeAt(0) - 97;
194 static SquareToCoords(sq
) {
196 // NOTE: column is always one char => max 26 columns
197 // row is counted from black side => subtraction
198 x: V
.size
.x
- parseInt(sq
.substr(1)),
199 y: sq
[0].charCodeAt() - 97
204 static CoordsToSquare(coords
) {
205 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
208 // Path to pieces (standard ones in pieces/ folder)
213 // Path to promotion pieces (usually the same)
215 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
218 // Aggregates flags into one object
220 return this.castleFlags
;
224 disaggregateFlags(flags
) {
225 this.castleFlags
= flags
;
228 // En-passant square, if any
229 getEpSquare(moveOrSquare
) {
230 if (!moveOrSquare
) return undefined;
231 if (typeof moveOrSquare
=== "string") {
232 const square
= moveOrSquare
;
233 if (square
== "-") return undefined;
234 return V
.SquareToCoords(square
);
236 // Argument is a move:
237 const move = moveOrSquare
;
238 const s
= move.start
,
242 Math
.abs(s
.x
- e
.x
) == 2 &&
243 // Next conditions for variants like Atomic or Rifle, Recycle...
244 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
245 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
252 return undefined; //default
255 // Can thing on square1 take thing on square2
256 canTake([x1
, y1
], [x2
, y2
]) {
257 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
260 // Is (x,y) on the chessboard?
261 static OnBoard(x
, y
) {
262 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
265 // Used in interface: 'side' arg == player color
266 canIplay(side
, [x
, y
]) {
267 return this.turn
== side
&& this.getColor(x
, y
) == side
;
270 // On which squares is color under check ? (for interface)
272 const color
= this.turn
;
274 this.underCheck(color
)
275 // kingPos must be duplicated, because it may change:
276 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
284 // Setup the initial random (asymmetric) position
285 static GenRandInitFen(randomness
) {
288 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
290 let pieces
= { w: new Array(8), b: new Array(8) };
292 // Shuffle pieces on first (and last rank if randomness == 2)
293 for (let c
of ["w", "b"]) {
294 if (c
== 'b' && randomness
== 1) {
295 pieces
['b'] = pieces
['w'];
300 let positions
= ArrayFun
.range(8);
302 // Get random squares for bishops
303 let randIndex
= 2 * randInt(4);
304 const bishop1Pos
= positions
[randIndex
];
305 // The second bishop must be on a square of different color
306 let randIndex_tmp
= 2 * randInt(4) + 1;
307 const bishop2Pos
= positions
[randIndex_tmp
];
308 // Remove chosen squares
309 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
310 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
312 // Get random squares for knights
313 randIndex
= randInt(6);
314 const knight1Pos
= positions
[randIndex
];
315 positions
.splice(randIndex
, 1);
316 randIndex
= randInt(5);
317 const knight2Pos
= positions
[randIndex
];
318 positions
.splice(randIndex
, 1);
320 // Get random square for queen
321 randIndex
= randInt(4);
322 const queenPos
= positions
[randIndex
];
323 positions
.splice(randIndex
, 1);
325 // Rooks and king positions are now fixed,
326 // because of the ordering rook-king-rook
327 const rook1Pos
= positions
[0];
328 const kingPos
= positions
[1];
329 const rook2Pos
= positions
[2];
331 // Finally put the shuffled pieces in the board array
332 pieces
[c
][rook1Pos
] = "r";
333 pieces
[c
][knight1Pos
] = "n";
334 pieces
[c
][bishop1Pos
] = "b";
335 pieces
[c
][queenPos
] = "q";
336 pieces
[c
][kingPos
] = "k";
337 pieces
[c
][bishop2Pos
] = "b";
338 pieces
[c
][knight2Pos
] = "n";
339 pieces
[c
][rook2Pos
] = "r";
340 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
342 // Add turn + flags + enpassant
344 pieces
["b"].join("") +
345 "/pppppppp/8/8/8/8/PPPPPPPP/" +
346 pieces
["w"].join("").toUpperCase() +
347 " w 0 " + flags
+ " -"
351 // "Parse" FEN: just return untransformed string data
352 static ParseFen(fen
) {
353 const fenParts
= fen
.split(" ");
355 position: fenParts
[0],
357 movesCount: fenParts
[2]
360 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
361 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
365 // Return current fen (game state)
368 this.getBaseFen() + " " +
369 this.getTurnFen() + " " +
371 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
372 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
377 // Omit movesCount, only variable allowed to differ
379 this.getBaseFen() + "_" +
381 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
382 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
386 // Position part of the FEN string
388 const format
= (count
) => {
389 // if more than 9 consecutive free spaces, break the integer,
390 // otherwise FEN parsing will fail.
391 if (count
<= 9) return count
;
392 // Currently only boards of size up to 11 or 12:
393 return "9" + (count
- 9);
396 for (let i
= 0; i
< V
.size
.x
; i
++) {
398 for (let j
= 0; j
< V
.size
.y
; j
++) {
399 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
401 if (emptyCount
> 0) {
402 // Add empty squares in-between
403 position
+= format(emptyCount
);
406 position
+= V
.board2fen(this.board
[i
][j
]);
409 if (emptyCount
> 0) {
411 position
+= format(emptyCount
);
413 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
422 // Flags part of the FEN string
426 for (let c
of ["w", "b"])
427 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
431 // Enpassant part of the FEN string
433 const L
= this.epSquares
.length
;
434 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
435 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
438 // Turn position fen into double array ["wb","wp","bk",...]
439 static GetBoard(position
) {
440 const rows
= position
.split("/");
441 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
442 for (let i
= 0; i
< rows
.length
; i
++) {
444 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
445 const character
= rows
[i
][indexInRow
];
446 const num
= parseInt(character
);
447 // If num is a number, just shift j:
448 if (!isNaN(num
)) j
+= num
;
449 // Else: something at position i,j
450 else board
[i
][j
++] = V
.fen2board(character
);
456 // Extract (relevant) flags from fen
458 // white a-castle, h-castle, black a-castle, h-castle
459 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
460 for (let i
= 0; i
< 4; i
++) {
461 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
462 V
.ColumnToCoord(fenflags
.charAt(i
));
469 // Fen string fully describes the game state
472 // In printDiagram() fen isn't supply because only getPpath() is used
473 // TODO: find a better solution!
475 const fenParsed
= V
.ParseFen(fen
);
476 this.board
= V
.GetBoard(fenParsed
.position
);
477 this.turn
= fenParsed
.turn
;
478 this.movesCount
= parseInt(fenParsed
.movesCount
);
479 this.setOtherVariables(fen
);
482 // Scan board for kings positions
484 this.INIT_COL_KING
= { w: -1, b: -1 };
485 // Squares of white and black king:
486 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
487 const fenRows
= V
.ParseFen(fen
).position
.split("/");
488 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
489 for (let i
= 0; i
< fenRows
.length
; i
++) {
490 let k
= 0; //column index on board
491 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
492 switch (fenRows
[i
].charAt(j
)) {
494 this.kingPos
["b"] = [i
, k
];
495 this.INIT_COL_KING
["b"] = k
;
498 this.kingPos
["w"] = [i
, k
];
499 this.INIT_COL_KING
["w"] = k
;
502 const num
= parseInt(fenRows
[i
].charAt(j
));
503 if (!isNaN(num
)) k
+= num
- 1;
511 // Some additional variables from FEN (variant dependant)
512 setOtherVariables(fen
) {
513 // Set flags and enpassant:
514 const parsedFen
= V
.ParseFen(fen
);
515 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
516 if (V
.HasEnpassant
) {
518 parsedFen
.enpassant
!= "-"
519 ? this.getEpSquare(parsedFen
.enpassant
)
521 this.epSquares
= [epSq
];
523 // Search for kings positions:
527 /////////////////////
531 return { x: 8, y: 8 };
534 // Color of thing on square (i,j). 'undefined' if square is empty
536 return this.board
[i
][j
].charAt(0);
539 // Piece type on square (i,j). 'undefined' if square is empty
541 return this.board
[i
][j
].charAt(1);
544 // Get opponent color
545 static GetOppCol(color
) {
546 return color
== "w" ? "b" : "w";
549 // Pieces codes (for a clearer code)
556 static get KNIGHT() {
559 static get BISHOP() {
570 static get PIECES() {
571 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
579 // Some pieces movements
610 // All possible moves from selected square
611 getPotentialMovesFrom([x
, y
]) {
612 switch (this.getPiece(x
, y
)) {
614 return this.getPotentialPawnMoves([x
, y
]);
616 return this.getPotentialRookMoves([x
, y
]);
618 return this.getPotentialKnightMoves([x
, y
]);
620 return this.getPotentialBishopMoves([x
, y
]);
622 return this.getPotentialQueenMoves([x
, y
]);
624 return this.getPotentialKingMoves([x
, y
]);
626 return []; //never reached
629 // Build a regular move from its initial and destination squares.
630 // tr: transformation
631 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
632 const initColor
= this.getColor(sx
, sy
);
633 const initPiece
= this.getPiece(sx
, sy
);
639 c: tr
? tr
.c : initColor
,
640 p: tr
? tr
.p : initPiece
653 // The opponent piece disappears if we take it
654 if (this.board
[ex
][ey
] != V
.EMPTY
) {
659 c: this.getColor(ex
, ey
),
660 p: this.getPiece(ex
, ey
)
668 // Generic method to find possible moves of non-pawn pieces:
669 // "sliding or jumping"
670 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
672 outerLoop: for (let step
of steps
) {
675 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
676 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
677 if (oneStep
) continue outerLoop
;
681 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
682 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
687 // Special case of en-passant captures: treated separately
688 getEnpassantCaptures([x
, y
], shiftX
) {
689 const Lep
= this.epSquares
.length
;
690 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
691 let enpassantMove
= null;
694 epSquare
.x
== x
+ shiftX
&&
695 Math
.abs(epSquare
.y
- y
) == 1
697 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
698 enpassantMove
.vanish
.push({
701 // Captured piece is usually a pawn, but next line seems harmless
702 p: this.getPiece(x
, epSquare
.y
),
703 c: this.getColor(x
, epSquare
.y
)
706 return !!enpassantMove
? [enpassantMove
] : [];
709 // Consider all potential promotions:
710 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
711 let finalPieces
= [V
.PAWN
];
712 const color
= this.turn
; //this.getColor(x1, y1);
713 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
714 if (x2
== lastRank
) {
715 // promotions arg: special override for Hiddenqueen variant
716 if (!!promotions
) finalPieces
= promotions
;
717 else if (!!V
.PawnSpecs
.promotions
)
718 finalPieces
= V
.PawnSpecs
.promotions
;
721 for (let piece
of finalPieces
) {
722 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
723 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
727 // What are the pawn moves from square x,y ?
728 getPotentialPawnMoves([x
, y
], promotions
) {
729 const color
= this.turn
; //this.getColor(x, y);
730 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
731 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
732 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
734 // Pawn movements in shiftX direction:
735 const getPawnMoves
= (shiftX
) => {
737 // NOTE: next condition is generally true (no pawn on last rank)
738 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
739 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
740 // One square forward
741 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
742 // Next condition because pawns on 1st rank can generally jump
744 V
.PawnSpecs
.twoSquares
&&
746 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
748 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
751 if (this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
) {
753 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
755 V
.PawnSpecs
.threeSquares
&&
756 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
758 // Three squares jump
759 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
765 if (V
.PawnSpecs
.canCapture
) {
766 for (let shiftY
of [-1, 1]) {
772 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
773 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
776 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
781 V
.PawnSpecs
.captureBackward
&&
782 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
783 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
784 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
787 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
798 let pMoves
= getPawnMoves(pawnShiftX
);
799 if (V
.PawnSpecs
.bidirectional
)
800 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
802 if (V
.HasEnpassant
) {
803 // NOTE: backward en-passant captures are not considered
804 // because no rules define them (for now).
805 Array
.prototype.push
.apply(
807 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
814 // What are the rook moves from square x,y ?
815 getPotentialRookMoves(sq
) {
816 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
819 // What are the knight moves from square x,y ?
820 getPotentialKnightMoves(sq
) {
821 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
824 // What are the bishop moves from square x,y ?
825 getPotentialBishopMoves(sq
) {
826 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
829 // What are the queen moves from square x,y ?
830 getPotentialQueenMoves(sq
) {
831 return this.getSlideNJumpMoves(
833 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
837 // What are the king moves from square x,y ?
838 getPotentialKingMoves(sq
) {
839 // Initialize with normal moves
840 let moves
= this.getSlideNJumpMoves(
842 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
845 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
849 // "castleInCheck" arg to let some variants castle under check
850 getCastleMoves([x
, y
], castleInCheck
) {
851 const c
= this.getColor(x
, y
);
852 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
853 return []; //x isn't first rank, or king has moved (shortcut)
856 const oppCol
= V
.GetOppCol(c
);
860 const finalSquares
= [
862 [V
.size
.y
- 2, V
.size
.y
- 3]
867 castleSide
++ //large, then small
869 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
870 // If this code is reached, rook and king are on initial position
872 // NOTE: in some variants this is not a rook
873 const rookPos
= this.castleFlags
[c
][castleSide
];
874 if (this.board
[x
][rookPos
] == V
.EMPTY
|| this.getColor(x
, rookPos
) != c
)
875 // Rook is not here, or changed color (see Benedict)
878 // Nothing on the path of the king ? (and no checks)
879 const castlingPiece
= this.getPiece(x
, rookPos
);
880 const finDist
= finalSquares
[castleSide
][0] - y
;
881 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
885 // NOTE: "castling" arg is used by some variants (Monster),
886 // where "isAttacked" is overloaded in an infinite-recursive way.
887 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
, "castling")) ||
888 (this.board
[x
][i
] != V
.EMPTY
&&
889 // NOTE: next check is enough, because of chessboard constraints
890 (this.getColor(x
, i
) != c
||
891 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
893 continue castlingCheck
;
896 } while (i
!= finalSquares
[castleSide
][0]);
898 // Nothing on the path to the rook?
899 step
= castleSide
== 0 ? -1 : 1;
900 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
901 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
904 // Nothing on final squares, except maybe king and castling rook?
905 for (i
= 0; i
< 2; i
++) {
907 finalSquares
[castleSide
][i
] != rookPos
&&
908 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
910 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
||
911 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
914 continue castlingCheck
;
918 // If this code is reached, castle is valid
924 y: finalSquares
[castleSide
][0],
930 y: finalSquares
[castleSide
][1],
936 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
937 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
940 Math
.abs(y
- rookPos
) <= 2
941 ? { x: x
, y: rookPos
}
942 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
953 // For the interface: possible moves for the current turn from square sq
954 getPossibleMovesFrom(sq
) {
955 return this.filterValid(this.getPotentialMovesFrom(sq
));
958 // TODO: promotions (into R,B,N,Q) should be filtered only once
960 if (moves
.length
== 0) return [];
961 const color
= this.turn
;
962 return moves
.filter(m
=> {
964 const res
= !this.underCheck(color
);
970 getAllPotentialMoves() {
971 const color
= this.turn
;
972 let potentialMoves
= [];
973 for (let i
= 0; i
< V
.size
.x
; i
++) {
974 for (let j
= 0; j
< V
.size
.y
; j
++) {
975 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
976 Array
.prototype.push
.apply(
978 this.getPotentialMovesFrom([i
, j
])
983 return potentialMoves
;
986 // Search for all valid moves considering current turn
987 // (for engine and game end)
989 return this.filterValid(this.getAllPotentialMoves());
992 // Stop at the first move found
993 // TODO: not really, it explores all moves from a square (one is enough).
995 const color
= this.turn
;
996 for (let i
= 0; i
< V
.size
.x
; i
++) {
997 for (let j
= 0; j
< V
.size
.y
; j
++) {
998 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
999 const moves
= this.getPotentialMovesFrom([i
, j
]);
1000 if (moves
.length
> 0) {
1001 for (let k
= 0; k
< moves
.length
; k
++) {
1002 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1011 // Check if pieces of given color are attacking (king) on square x,y
1012 isAttacked(sq
, color
) {
1014 this.isAttackedByPawn(sq
, color
) ||
1015 this.isAttackedByRook(sq
, color
) ||
1016 this.isAttackedByKnight(sq
, color
) ||
1017 this.isAttackedByBishop(sq
, color
) ||
1018 this.isAttackedByQueen(sq
, color
) ||
1019 this.isAttackedByKing(sq
, color
)
1023 // Generic method for non-pawn pieces ("sliding or jumping"):
1024 // is x,y attacked by a piece of given color ?
1025 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1026 for (let step
of steps
) {
1027 let rx
= x
+ step
[0],
1029 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1034 V
.OnBoard(rx
, ry
) &&
1035 this.getPiece(rx
, ry
) == piece
&&
1036 this.getColor(rx
, ry
) == color
1044 // Is square x,y attacked by 'color' pawns ?
1045 isAttackedByPawn([x
, y
], color
) {
1046 const pawnShift
= (color
== "w" ? 1 : -1);
1047 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
1048 for (let i
of [-1, 1]) {
1052 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
1053 this.getColor(x
+ pawnShift
, y
+ i
) == color
1062 // Is square x,y attacked by 'color' rooks ?
1063 isAttackedByRook(sq
, color
) {
1064 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1067 // Is square x,y attacked by 'color' knights ?
1068 isAttackedByKnight(sq
, color
) {
1069 return this.isAttackedBySlideNJump(
1078 // Is square x,y attacked by 'color' bishops ?
1079 isAttackedByBishop(sq
, color
) {
1080 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1083 // Is square x,y attacked by 'color' queens ?
1084 isAttackedByQueen(sq
, color
) {
1085 return this.isAttackedBySlideNJump(
1089 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1093 // Is square x,y attacked by 'color' king(s) ?
1094 isAttackedByKing(sq
, color
) {
1095 return this.isAttackedBySlideNJump(
1099 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1104 // Is color under check after his move ?
1106 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1112 // Apply a move on board
1113 static PlayOnBoard(board
, move) {
1114 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1115 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1117 // Un-apply the played move
1118 static UndoOnBoard(board
, move) {
1119 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1120 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1127 // if (!this.states) this.states = [];
1128 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1129 // this.states.push(stateFen);
1132 // Save flags (for undo)
1133 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1134 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1135 V
.PlayOnBoard(this.board
, move);
1136 this.turn
= V
.GetOppCol(this.turn
);
1138 this.postPlay(move);
1141 updateCastleFlags(move, piece
) {
1142 const c
= V
.GetOppCol(this.turn
);
1143 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1144 // Update castling flags if rooks are moved
1145 const oppCol
= this.turn
;
1146 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1147 if (piece
== V
.KING
&& move.appear
.length
> 0)
1148 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1150 move.start
.x
== firstRank
&& //our rook moves?
1151 this.castleFlags
[c
].includes(move.start
.y
)
1153 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1154 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1156 // NOTE: not "else if" because a rook could take an opposing rook
1158 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1159 this.castleFlags
[oppCol
].includes(move.end
.y
)
1161 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1162 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1166 // After move is played, update variables + flags
1168 const c
= V
.GetOppCol(this.turn
);
1169 let piece
= undefined;
1170 if (move.vanish
.length
>= 1)
1171 // Usual case, something is moved
1172 piece
= move.vanish
[0].p
;
1174 // Crazyhouse-like variants
1175 piece
= move.appear
[0].p
;
1177 // Update king position + flags
1178 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1179 this.kingPos
[c
][0] = move.appear
[0].x
;
1180 this.kingPos
[c
][1] = move.appear
[0].y
;
1182 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1189 if (V
.HasEnpassant
) this.epSquares
.pop();
1190 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1191 V
.UndoOnBoard(this.board
, move);
1192 this.turn
= V
.GetOppCol(this.turn
);
1194 this.postUndo(move);
1197 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1198 // if (stateFen != this.states[this.states.length-1]) debugger;
1199 // this.states.pop();
1202 // After move is undo-ed *and flags resetted*, un-update other variables
1203 // TODO: more symmetry, by storing flags increment in move (?!)
1205 // (Potentially) Reset king position
1206 const c
= this.getColor(move.start
.x
, move.start
.y
);
1207 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1208 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1214 // What is the score ? (Interesting if game is over)
1216 if (this.atLeastOneMove()) return "*";
1218 const color
= this.turn
;
1219 // No valid move: stalemate or checkmate?
1220 if (!this.underCheck(color
)) return "1/2";
1222 return (color
== "w" ? "0-1" : "1-0");
1229 static get VALUES() {
1240 // "Checkmate" (unreachable eval)
1241 static get INFINITY() {
1245 // At this value or above, the game is over
1246 static get THRESHOLD_MATE() {
1250 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1251 static get SEARCH_DEPTH() {
1255 // 'movesList' arg for some variants to provide a custom list
1256 getComputerMove(movesList
) {
1257 const maxeval
= V
.INFINITY
;
1258 const color
= this.turn
;
1259 let moves1
= movesList
|| this.getAllValidMoves();
1261 if (moves1
.length
== 0)
1262 // TODO: this situation should not happen
1265 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1266 for (let i
= 0; i
< moves1
.length
; i
++) {
1267 this.play(moves1
[i
]);
1268 const score1
= this.getCurrentScore();
1269 if (score1
!= "*") {
1273 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1275 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1276 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1277 this.undo(moves1
[i
]);
1280 // Initial self evaluation is very low: "I'm checkmated"
1281 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1282 // Initial enemy evaluation is very low too, for him
1283 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1284 // Second half-move:
1285 let moves2
= this.getAllValidMoves();
1286 for (let j
= 0; j
< moves2
.length
; j
++) {
1287 this.play(moves2
[j
]);
1288 const score2
= this.getCurrentScore();
1289 let evalPos
= 0; //1/2 value
1292 evalPos
= this.evalPosition();
1302 (color
== "w" && evalPos
< eval2
) ||
1303 (color
== "b" && evalPos
> eval2
)
1307 this.undo(moves2
[j
]);
1310 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1311 (color
== "b" && eval2
< moves1
[i
].eval
)
1313 moves1
[i
].eval
= eval2
;
1315 this.undo(moves1
[i
]);
1317 moves1
.sort((a
, b
) => {
1318 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1320 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1322 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1323 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1324 for (let i
= 0; i
< moves1
.length
; i
++) {
1325 this.play(moves1
[i
]);
1326 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1328 0.1 * moves1
[i
].eval
+
1329 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1330 this.undo(moves1
[i
]);
1332 moves1
.sort((a
, b
) => {
1333 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1337 let candidates
= [0];
1338 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1340 return moves1
[candidates
[randInt(candidates
.length
)]];
1343 alphabeta(depth
, alpha
, beta
) {
1344 const maxeval
= V
.INFINITY
;
1345 const color
= this.turn
;
1346 const score
= this.getCurrentScore();
1348 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1349 if (depth
== 0) return this.evalPosition();
1350 const moves
= this.getAllValidMoves();
1351 let v
= color
== "w" ? -maxeval : maxeval
;
1353 for (let i
= 0; i
< moves
.length
; i
++) {
1354 this.play(moves
[i
]);
1355 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1356 this.undo(moves
[i
]);
1357 alpha
= Math
.max(alpha
, v
);
1358 if (alpha
>= beta
) break; //beta cutoff
1363 for (let i
= 0; i
< moves
.length
; i
++) {
1364 this.play(moves
[i
]);
1365 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1366 this.undo(moves
[i
]);
1367 beta
= Math
.min(beta
, v
);
1368 if (alpha
>= beta
) break; //alpha cutoff
1376 // Just count material for now
1377 for (let i
= 0; i
< V
.size
.x
; i
++) {
1378 for (let j
= 0; j
< V
.size
.y
; j
++) {
1379 if (this.board
[i
][j
] != V
.EMPTY
) {
1380 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1381 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1388 /////////////////////////
1389 // MOVES + GAME NOTATION
1390 /////////////////////////
1392 // Context: just before move is played, turn hasn't changed
1393 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1395 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1397 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1399 // Translate final square
1400 const finalSquare
= V
.CoordsToSquare(move.end
);
1402 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1403 if (piece
== V
.PAWN
) {
1406 if (move.vanish
.length
> move.appear
.length
) {
1408 const startColumn
= V
.CoordToColumn(move.start
.y
);
1409 notation
= startColumn
+ "x" + finalSquare
;
1411 else notation
= finalSquare
;
1412 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1414 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1419 piece
.toUpperCase() +
1420 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1425 static GetUnambiguousNotation(move) {
1426 // Machine-readable format with all the informations about the move
1428 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1429 ? V
.CoordsToSquare(move.start
)
1432 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1433 ? V
.CoordsToSquare(move.end
)
1436 (!!move.appear
&& move.appear
.length
> 0
1437 ? move.appear
.map(a
=>
1438 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1441 (!!move.vanish
&& move.vanish
.length
> 0
1442 ? move.vanish
.map(a
=>
1443 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")