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 },
51 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
53 captureBackward: false,
58 // En-passant captures need a stack of squares:
59 static get HasEnpassant() {
63 // Some variants cannot have analyse mode
64 static get CanAnalyze() {
67 // Patch: issues with javascript OOP, objects can't access static fields.
72 // Some variants show incomplete information,
73 // and thus show only a partial moves list or no list at all.
74 static get ShowMoves() {
81 // Some variants always show the same orientation
82 static get CanFlip() {
89 // Some variants use click infos:
94 static get IMAGE_EXTENSION() {
95 // All pieces should be in the SVG format
99 // Turn "wb" into "B" (for FEN)
100 static board2fen(b
) {
101 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
104 // Turn "p" into "bp" (for board)
105 static fen2board(f
) {
106 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
109 // Check if FEN describes a board situation correctly
110 static IsGoodFen(fen
) {
111 const fenParsed
= V
.ParseFen(fen
);
113 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
115 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
116 // 3) Check moves count
117 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
120 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
122 // 5) Check enpassant
125 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
132 // Is position part of the FEN a priori correct?
133 static IsGoodPosition(position
) {
134 if (position
.length
== 0) return false;
135 const rows
= position
.split("/");
136 if (rows
.length
!= V
.size
.x
) return false;
137 let kings
= { "k": 0, "K": 0 };
138 for (let row
of rows
) {
140 for (let i
= 0; i
< row
.length
; i
++) {
141 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
142 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
144 const num
= parseInt(row
[i
]);
145 if (isNaN(num
)) return false;
149 if (sumElts
!= V
.size
.y
) return false;
151 // Both kings should be on board. Exactly one per color.
152 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
157 static IsGoodTurn(turn
) {
158 return ["w", "b"].includes(turn
);
162 static IsGoodFlags(flags
) {
163 // NOTE: a little too permissive to work with more variants
164 return !!flags
.match(/^[a-z]{4,4}$/);
167 static IsGoodEnpassant(enpassant
) {
168 if (enpassant
!= "-") {
169 const ep
= V
.SquareToCoords(enpassant
);
170 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
175 // 3 --> d (column number to letter)
176 static CoordToColumn(colnum
) {
177 return String
.fromCharCode(97 + colnum
);
180 // d --> 3 (column letter to number)
181 static ColumnToCoord(column
) {
182 return column
.charCodeAt(0) - 97;
186 static SquareToCoords(sq
) {
188 // NOTE: column is always one char => max 26 columns
189 // row is counted from black side => subtraction
190 x: V
.size
.x
- parseInt(sq
.substr(1)),
191 y: sq
[0].charCodeAt() - 97
196 static CoordsToSquare(coords
) {
197 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
200 // Path to pieces (standard ones in pieces/ folder)
205 // Path to promotion pieces (usually the same)
207 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
210 // Aggregates flags into one object
212 return this.castleFlags
;
216 disaggregateFlags(flags
) {
217 this.castleFlags
= flags
;
220 // En-passant square, if any
221 getEpSquare(moveOrSquare
) {
222 if (!moveOrSquare
) return undefined;
223 if (typeof moveOrSquare
=== "string") {
224 const square
= moveOrSquare
;
225 if (square
== "-") return undefined;
226 return V
.SquareToCoords(square
);
228 // Argument is a move:
229 const move = moveOrSquare
;
230 const s
= move.start
,
234 Math
.abs(s
.x
- e
.x
) == 2 &&
235 // Next conditions for variants like Atomic or Rifle, Recycle...
236 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
237 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
244 return undefined; //default
247 // Can thing on square1 take thing on square2
248 canTake([x1
, y1
], [x2
, y2
]) {
249 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
252 // Is (x,y) on the chessboard?
253 static OnBoard(x
, y
) {
254 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
257 // Used in interface: 'side' arg == player color
258 canIplay(side
, [x
, y
]) {
259 return this.turn
== side
&& this.getColor(x
, y
) == side
;
262 // On which squares is color under check ? (for interface)
263 getCheckSquares(color
) {
265 this.underCheck(color
)
266 // kingPos must be duplicated, because it may change:
267 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
275 // Setup the initial random (asymmetric) position
276 static GenRandInitFen(randomness
) {
279 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
281 let pieces
= { w: new Array(8), b: new Array(8) };
283 // Shuffle pieces on first (and last rank if randomness == 2)
284 for (let c
of ["w", "b"]) {
285 if (c
== 'b' && randomness
== 1) {
286 pieces
['b'] = pieces
['w'];
291 let positions
= ArrayFun
.range(8);
293 // Get random squares for bishops
294 let randIndex
= 2 * randInt(4);
295 const bishop1Pos
= positions
[randIndex
];
296 // The second bishop must be on a square of different color
297 let randIndex_tmp
= 2 * randInt(4) + 1;
298 const bishop2Pos
= positions
[randIndex_tmp
];
299 // Remove chosen squares
300 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
301 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
303 // Get random squares for knights
304 randIndex
= randInt(6);
305 const knight1Pos
= positions
[randIndex
];
306 positions
.splice(randIndex
, 1);
307 randIndex
= randInt(5);
308 const knight2Pos
= positions
[randIndex
];
309 positions
.splice(randIndex
, 1);
311 // Get random square for queen
312 randIndex
= randInt(4);
313 const queenPos
= positions
[randIndex
];
314 positions
.splice(randIndex
, 1);
316 // Rooks and king positions are now fixed,
317 // because of the ordering rook-king-rook
318 const rook1Pos
= positions
[0];
319 const kingPos
= positions
[1];
320 const rook2Pos
= positions
[2];
322 // Finally put the shuffled pieces in the board array
323 pieces
[c
][rook1Pos
] = "r";
324 pieces
[c
][knight1Pos
] = "n";
325 pieces
[c
][bishop1Pos
] = "b";
326 pieces
[c
][queenPos
] = "q";
327 pieces
[c
][kingPos
] = "k";
328 pieces
[c
][bishop2Pos
] = "b";
329 pieces
[c
][knight2Pos
] = "n";
330 pieces
[c
][rook2Pos
] = "r";
331 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
333 // Add turn + flags + enpassant
335 pieces
["b"].join("") +
336 "/pppppppp/8/8/8/8/PPPPPPPP/" +
337 pieces
["w"].join("").toUpperCase() +
338 " w 0 " + flags
+ " -"
342 // "Parse" FEN: just return untransformed string data
343 static ParseFen(fen
) {
344 const fenParts
= fen
.split(" ");
346 position: fenParts
[0],
348 movesCount: fenParts
[2]
351 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
352 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
356 // Return current fen (game state)
359 this.getBaseFen() + " " +
360 this.getTurnFen() + " " +
362 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
363 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
368 // Omit movesCount, only variable allowed to differ
370 this.getBaseFen() + "_" +
372 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
373 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
377 // Position part of the FEN string
379 const format
= (count
) => {
380 // if more than 9 consecutive free spaces, break the integer,
381 // otherwise FEN parsing will fail.
382 if (count
<= 9) return count
;
383 // Currently only boards of size up to 11 or 12:
384 return "9" + (count
- 9);
387 for (let i
= 0; i
< V
.size
.x
; i
++) {
389 for (let j
= 0; j
< V
.size
.y
; j
++) {
390 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
392 if (emptyCount
> 0) {
393 // Add empty squares in-between
394 position
+= format(emptyCount
);
397 position
+= V
.board2fen(this.board
[i
][j
]);
400 if (emptyCount
> 0) {
402 position
+= format(emptyCount
);
404 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
413 // Flags part of the FEN string
417 for (let c
of ["w", "b"])
418 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
422 // Enpassant part of the FEN string
424 const L
= this.epSquares
.length
;
425 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
426 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
429 // Turn position fen into double array ["wb","wp","bk",...]
430 static GetBoard(position
) {
431 const rows
= position
.split("/");
432 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
433 for (let i
= 0; i
< rows
.length
; i
++) {
435 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
436 const character
= rows
[i
][indexInRow
];
437 const num
= parseInt(character
);
438 // If num is a number, just shift j:
439 if (!isNaN(num
)) j
+= num
;
440 // Else: something at position i,j
441 else board
[i
][j
++] = V
.fen2board(character
);
447 // Extract (relevant) flags from fen
449 // white a-castle, h-castle, black a-castle, h-castle
450 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
451 for (let i
= 0; i
< 4; i
++) {
452 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
453 V
.ColumnToCoord(fenflags
.charAt(i
));
460 // Fen string fully describes the game state
463 // In printDiagram() fen isn't supply because only getPpath() is used
464 // TODO: find a better solution!
466 const fenParsed
= V
.ParseFen(fen
);
467 this.board
= V
.GetBoard(fenParsed
.position
);
468 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
469 this.movesCount
= parseInt(fenParsed
.movesCount
);
470 this.setOtherVariables(fen
);
473 // Scan board for kings positions
475 this.INIT_COL_KING
= { w: -1, b: -1 };
476 // Squares of white and black king:
477 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
478 const fenRows
= V
.ParseFen(fen
).position
.split("/");
479 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
480 for (let i
= 0; i
< fenRows
.length
; i
++) {
481 let k
= 0; //column index on board
482 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
483 switch (fenRows
[i
].charAt(j
)) {
485 this.kingPos
["b"] = [i
, k
];
486 this.INIT_COL_KING
["b"] = k
;
489 this.kingPos
["w"] = [i
, k
];
490 this.INIT_COL_KING
["w"] = k
;
493 const num
= parseInt(fenRows
[i
].charAt(j
));
494 if (!isNaN(num
)) k
+= num
- 1;
502 // Some additional variables from FEN (variant dependant)
503 setOtherVariables(fen
) {
504 // Set flags and enpassant:
505 const parsedFen
= V
.ParseFen(fen
);
506 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
507 if (V
.HasEnpassant
) {
509 parsedFen
.enpassant
!= "-"
510 ? this.getEpSquare(parsedFen
.enpassant
)
512 this.epSquares
= [epSq
];
514 // Search for kings positions:
518 /////////////////////
522 return { x: 8, y: 8 };
525 // Color of thing on square (i,j). 'undefined' if square is empty
527 return this.board
[i
][j
].charAt(0);
530 // Piece type on square (i,j). 'undefined' if square is empty
532 return this.board
[i
][j
].charAt(1);
535 // Get opponent color
536 static GetOppCol(color
) {
537 return color
== "w" ? "b" : "w";
540 // Pieces codes (for a clearer code)
547 static get KNIGHT() {
550 static get BISHOP() {
561 static get PIECES() {
562 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
570 // Some pieces movements
601 // All possible moves from selected square
602 getPotentialMovesFrom([x
, y
]) {
603 switch (this.getPiece(x
, y
)) {
605 return this.getPotentialPawnMoves([x
, y
]);
607 return this.getPotentialRookMoves([x
, y
]);
609 return this.getPotentialKnightMoves([x
, y
]);
611 return this.getPotentialBishopMoves([x
, y
]);
613 return this.getPotentialQueenMoves([x
, y
]);
615 return this.getPotentialKingMoves([x
, y
]);
617 return []; //never reached
620 // Build a regular move from its initial and destination squares.
621 // tr: transformation
622 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
623 const initColor
= this.getColor(sx
, sy
);
624 const initPiece
= this.getPiece(sx
, sy
);
630 c: tr
? tr
.c : initColor
,
631 p: tr
? tr
.p : initPiece
644 // The opponent piece disappears if we take it
645 if (this.board
[ex
][ey
] != V
.EMPTY
) {
650 c: this.getColor(ex
, ey
),
651 p: this.getPiece(ex
, ey
)
659 // Generic method to find possible moves of non-pawn pieces:
660 // "sliding or jumping"
661 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
663 outerLoop: for (let step
of steps
) {
666 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
667 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
668 if (oneStep
) continue outerLoop
;
672 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
673 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
678 // Special case of en-passant captures: treated separately
679 getEnpassantCaptures([x
, y
], shiftX
) {
680 const Lep
= this.epSquares
.length
;
681 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
682 let enpassantMove
= null;
685 epSquare
.x
== x
+ shiftX
&&
686 Math
.abs(epSquare
.y
- y
) == 1
688 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
689 enpassantMove
.vanish
.push({
692 // Captured piece is usually a pawn, but next line seems harmless
693 p: this.getPiece(x
, epSquare
.y
),
694 c: this.getColor(x
, epSquare
.y
)
697 return !!enpassantMove
? [enpassantMove
] : [];
700 // Consider all potential promotions:
701 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
702 let finalPieces
= [V
.PAWN
];
703 const color
= this.turn
;
704 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
705 if (x2
== lastRank
) {
706 // promotions arg: special override for Hiddenqueen variant
707 if (!!promotions
) finalPieces
= promotions
;
708 else if (!!V
.PawnSpecs
.promotions
)
709 finalPieces
= V
.PawnSpecs
.promotions
;
712 for (let piece
of finalPieces
) {
713 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
714 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
718 // What are the pawn moves from square x,y ?
719 getPotentialPawnMoves([x
, y
], promotions
) {
720 const color
= this.turn
;
721 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
722 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
723 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
724 const startRank
= (color
== "w" ? sizeX
- 2 : 1);
726 // Pawn movements in shiftX direction:
727 const getPawnMoves
= (shiftX
) => {
729 // NOTE: next condition is generally true (no pawn on last rank)
730 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
731 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
732 // One square forward
733 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
734 // Next condition because pawns on 1st rank can generally jump
736 V
.PawnSpecs
.twoSquares
&&
737 [startRank
, firstRank
].includes(x
) &&
738 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
741 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
745 if (V
.PawnSpecs
.canCapture
) {
746 for (let shiftY
of [-1, 1]) {
752 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
753 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
756 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
761 V
.PawnSpecs
.captureBackward
&&
762 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
763 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
764 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
767 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
778 let pMoves
= getPawnMoves(pawnShiftX
);
779 if (V
.PawnSpecs
.bidirectional
)
780 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
782 if (V
.HasEnpassant
) {
783 // NOTE: backward en-passant captures are not considered
784 // because no rules define them (for now).
785 Array
.prototype.push
.apply(
787 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
794 // What are the rook moves from square x,y ?
795 getPotentialRookMoves(sq
) {
796 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
799 // What are the knight moves from square x,y ?
800 getPotentialKnightMoves(sq
) {
801 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
804 // What are the bishop moves from square x,y ?
805 getPotentialBishopMoves(sq
) {
806 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
809 // What are the queen moves from square x,y ?
810 getPotentialQueenMoves(sq
) {
811 return this.getSlideNJumpMoves(
813 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
817 // What are the king moves from square x,y ?
818 getPotentialKingMoves(sq
) {
819 // Initialize with normal moves
820 let moves
= this.getSlideNJumpMoves(
822 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
825 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
829 // "castleInCheck" arg to let some variants castle under check
830 getCastleMoves([x
, y
], castleInCheck
) {
831 const c
= this.getColor(x
, y
);
832 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
833 return []; //x isn't first rank, or king has moved (shortcut)
836 const oppCol
= V
.GetOppCol(c
);
840 const finalSquares
= [
842 [V
.size
.y
- 2, V
.size
.y
- 3]
847 castleSide
++ //large, then small
849 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
850 // If this code is reached, rook and king are on initial position
852 // NOTE: in some variants this is not a rook
853 const rookPos
= this.castleFlags
[c
][castleSide
];
854 if (this.board
[x
][rookPos
] == V
.EMPTY
|| this.getColor(x
, rookPos
) != c
)
855 // Rook is not here, or changed color (see Benedict)
858 // Nothing on the path of the king ? (and no checks)
859 const castlingPiece
= this.getPiece(x
, rookPos
);
860 const finDist
= finalSquares
[castleSide
][0] - y
;
861 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
865 // NOTE: "castling" arg is used by some variants (Monster),
866 // where "isAttacked" is overloaded in an infinite-recursive way.
867 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
, "castling")) ||
868 (this.board
[x
][i
] != V
.EMPTY
&&
869 // NOTE: next check is enough, because of chessboard constraints
870 (this.getColor(x
, i
) != c
||
871 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
873 continue castlingCheck
;
876 } while (i
!= finalSquares
[castleSide
][0]);
878 // Nothing on the path to the rook?
879 step
= castleSide
== 0 ? -1 : 1;
880 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
881 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
884 // Nothing on final squares, except maybe king and castling rook?
885 for (i
= 0; i
< 2; i
++) {
887 finalSquares
[castleSide
][i
] != rookPos
&&
888 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
890 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
||
891 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
894 continue castlingCheck
;
898 // If this code is reached, castle is valid
904 y: finalSquares
[castleSide
][0],
910 y: finalSquares
[castleSide
][1],
916 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
917 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
920 Math
.abs(y
- rookPos
) <= 2
921 ? { x: x
, y: rookPos
}
922 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
933 // For the interface: possible moves for the current turn from square sq
934 getPossibleMovesFrom(sq
) {
935 return this.filterValid(this.getPotentialMovesFrom(sq
));
938 // TODO: promotions (into R,B,N,Q) should be filtered only once
940 if (moves
.length
== 0) return [];
941 const color
= this.turn
;
942 return moves
.filter(m
=> {
944 const res
= !this.underCheck(color
);
950 getAllPotentialMoves() {
951 const color
= this.turn
;
952 let potentialMoves
= [];
953 for (let i
= 0; i
< V
.size
.x
; i
++) {
954 for (let j
= 0; j
< V
.size
.y
; j
++) {
955 if (this.getColor(i
, j
) == color
) {
956 Array
.prototype.push
.apply(
958 this.getPotentialMovesFrom([i
, j
])
963 return potentialMoves
;
966 // Search for all valid moves considering current turn
967 // (for engine and game end)
969 return this.filterValid(this.getAllPotentialMoves());
972 // Stop at the first move found
973 // TODO: not really, it explores all moves from a square (one is enough).
975 const color
= this.turn
;
976 for (let i
= 0; i
< V
.size
.x
; i
++) {
977 for (let j
= 0; j
< V
.size
.y
; j
++) {
978 if (this.getColor(i
, j
) == color
) {
979 const moves
= this.getPotentialMovesFrom([i
, j
]);
980 if (moves
.length
> 0) {
981 for (let k
= 0; k
< moves
.length
; k
++) {
982 if (this.filterValid([moves
[k
]]).length
> 0) return true;
991 // Check if pieces of given color are attacking (king) on square x,y
992 isAttacked(sq
, color
) {
994 this.isAttackedByPawn(sq
, color
) ||
995 this.isAttackedByRook(sq
, color
) ||
996 this.isAttackedByKnight(sq
, color
) ||
997 this.isAttackedByBishop(sq
, color
) ||
998 this.isAttackedByQueen(sq
, color
) ||
999 this.isAttackedByKing(sq
, color
)
1003 // Generic method for non-pawn pieces ("sliding or jumping"):
1004 // is x,y attacked by a piece of given color ?
1005 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1006 for (let step
of steps
) {
1007 let rx
= x
+ step
[0],
1009 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1014 V
.OnBoard(rx
, ry
) &&
1015 this.getPiece(rx
, ry
) == piece
&&
1016 this.getColor(rx
, ry
) == color
1024 // Is square x,y attacked by 'color' pawns ?
1025 isAttackedByPawn([x
, y
], color
) {
1026 const pawnShift
= (color
== "w" ? 1 : -1);
1027 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
1028 for (let i
of [-1, 1]) {
1032 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
1033 this.getColor(x
+ pawnShift
, y
+ i
) == color
1042 // Is square x,y attacked by 'color' rooks ?
1043 isAttackedByRook(sq
, color
) {
1044 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1047 // Is square x,y attacked by 'color' knights ?
1048 isAttackedByKnight(sq
, color
) {
1049 return this.isAttackedBySlideNJump(
1058 // Is square x,y attacked by 'color' bishops ?
1059 isAttackedByBishop(sq
, color
) {
1060 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1063 // Is square x,y attacked by 'color' queens ?
1064 isAttackedByQueen(sq
, color
) {
1065 return this.isAttackedBySlideNJump(
1069 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1073 // Is square x,y attacked by 'color' king(s) ?
1074 isAttackedByKing(sq
, color
) {
1075 return this.isAttackedBySlideNJump(
1079 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1084 // Is color under check after his move ?
1086 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1092 // Apply a move on board
1093 static PlayOnBoard(board
, move) {
1094 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1095 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1097 // Un-apply the played move
1098 static UndoOnBoard(board
, move) {
1099 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1100 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1107 // if (!this.states) this.states = [];
1108 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1109 // this.states.push(stateFen);
1112 // Save flags (for undo)
1113 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1114 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1115 V
.PlayOnBoard(this.board
, move);
1116 this.turn
= V
.GetOppCol(this.turn
);
1118 this.postPlay(move);
1121 updateCastleFlags(move, piece
) {
1122 const c
= V
.GetOppCol(this.turn
);
1123 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1124 // Update castling flags if rooks are moved
1125 const oppCol
= this.turn
;
1126 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1127 if (piece
== V
.KING
&& move.appear
.length
> 0)
1128 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1130 move.start
.x
== firstRank
&& //our rook moves?
1131 this.castleFlags
[c
].includes(move.start
.y
)
1133 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1134 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1136 // NOTE: not "else if" because a rook could take an opposing rook
1138 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1139 this.castleFlags
[oppCol
].includes(move.end
.y
)
1141 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1142 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1146 // After move is played, update variables + flags
1148 const c
= V
.GetOppCol(this.turn
);
1149 let piece
= undefined;
1150 if (move.vanish
.length
>= 1)
1151 // Usual case, something is moved
1152 piece
= move.vanish
[0].p
;
1154 // Crazyhouse-like variants
1155 piece
= move.appear
[0].p
;
1157 // Update king position + flags
1158 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1159 this.kingPos
[c
][0] = move.appear
[0].x
;
1160 this.kingPos
[c
][1] = move.appear
[0].y
;
1163 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1170 if (V
.HasEnpassant
) this.epSquares
.pop();
1171 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1172 V
.UndoOnBoard(this.board
, move);
1173 this.turn
= V
.GetOppCol(this.turn
);
1175 this.postUndo(move);
1178 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1179 // if (stateFen != this.states[this.states.length-1]) debugger;
1180 // this.states.pop();
1183 // After move is undo-ed *and flags resetted*, un-update other variables
1184 // TODO: more symmetry, by storing flags increment in move (?!)
1186 // (Potentially) Reset king position
1187 const c
= this.getColor(move.start
.x
, move.start
.y
);
1188 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1189 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1195 // What is the score ? (Interesting if game is over)
1197 if (this.atLeastOneMove()) return "*";
1199 const color
= this.turn
;
1200 // No valid move: stalemate or checkmate?
1201 if (!this.underCheck(color
)) return "1/2";
1203 return (color
== "w" ? "0-1" : "1-0");
1210 static get VALUES() {
1221 // "Checkmate" (unreachable eval)
1222 static get INFINITY() {
1226 // At this value or above, the game is over
1227 static get THRESHOLD_MATE() {
1231 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1232 static get SEARCH_DEPTH() {
1237 const maxeval
= V
.INFINITY
;
1238 const color
= this.turn
;
1239 let moves1
= this.getAllValidMoves();
1241 if (moves1
.length
== 0)
1242 // TODO: this situation should not happen
1245 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1246 for (let i
= 0; i
< moves1
.length
; i
++) {
1247 this.play(moves1
[i
]);
1248 const score1
= this.getCurrentScore();
1249 if (score1
!= "*") {
1253 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1255 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1256 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1257 this.undo(moves1
[i
]);
1260 // Initial self evaluation is very low: "I'm checkmated"
1261 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1262 // Initial enemy evaluation is very low too, for him
1263 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1264 // Second half-move:
1265 let moves2
= this.getAllValidMoves();
1266 for (let j
= 0; j
< moves2
.length
; j
++) {
1267 this.play(moves2
[j
]);
1268 const score2
= this.getCurrentScore();
1269 let evalPos
= 0; //1/2 value
1272 evalPos
= this.evalPosition();
1282 (color
== "w" && evalPos
< eval2
) ||
1283 (color
== "b" && evalPos
> eval2
)
1287 this.undo(moves2
[j
]);
1290 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1291 (color
== "b" && eval2
< moves1
[i
].eval
)
1293 moves1
[i
].eval
= eval2
;
1295 this.undo(moves1
[i
]);
1297 moves1
.sort((a
, b
) => {
1298 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1300 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1302 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1303 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1304 for (let i
= 0; i
< moves1
.length
; i
++) {
1305 this.play(moves1
[i
]);
1306 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1308 0.1 * moves1
[i
].eval
+
1309 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1310 this.undo(moves1
[i
]);
1312 moves1
.sort((a
, b
) => {
1313 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1317 let candidates
= [0];
1318 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1320 return moves1
[candidates
[randInt(candidates
.length
)]];
1323 alphabeta(depth
, alpha
, beta
) {
1324 const maxeval
= V
.INFINITY
;
1325 const color
= this.turn
;
1326 const score
= this.getCurrentScore();
1328 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1329 if (depth
== 0) return this.evalPosition();
1330 const moves
= this.getAllValidMoves();
1331 let v
= color
== "w" ? -maxeval : maxeval
;
1333 for (let i
= 0; i
< moves
.length
; i
++) {
1334 this.play(moves
[i
]);
1335 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1336 this.undo(moves
[i
]);
1337 alpha
= Math
.max(alpha
, v
);
1338 if (alpha
>= beta
) break; //beta cutoff
1343 for (let i
= 0; i
< moves
.length
; i
++) {
1344 this.play(moves
[i
]);
1345 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1346 this.undo(moves
[i
]);
1347 beta
= Math
.min(beta
, v
);
1348 if (alpha
>= beta
) break; //alpha cutoff
1356 // Just count material for now
1357 for (let i
= 0; i
< V
.size
.x
; i
++) {
1358 for (let j
= 0; j
< V
.size
.y
; j
++) {
1359 if (this.board
[i
][j
] != V
.EMPTY
) {
1360 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1361 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1368 /////////////////////////
1369 // MOVES + GAME NOTATION
1370 /////////////////////////
1372 // Context: just before move is played, turn hasn't changed
1373 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1375 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1377 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1379 // Translate final square
1380 const finalSquare
= V
.CoordsToSquare(move.end
);
1382 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1383 if (piece
== V
.PAWN
) {
1386 if (move.vanish
.length
> move.appear
.length
) {
1388 const startColumn
= V
.CoordToColumn(move.start
.y
);
1389 notation
= startColumn
+ "x" + finalSquare
;
1391 else notation
= finalSquare
;
1392 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1394 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1399 piece
.toUpperCase() +
1400 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1405 static GetUnambiguousNotation(move) {
1406 // Machine-readable format with all the informations about the move
1408 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1409 ? V
.CoordsToSquare(move.start
)
1412 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1413 ? V
.CoordsToSquare(move.end
)
1416 (!!move.appear
&& move.appear
.length
> 0
1417 ? move.appear
.map(a
=>
1418 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1421 (!!move.vanish
&& move.vanish
.length
> 0
1422 ? move.vanish
.map(a
=>
1423 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")