5bf47f76430401f0f748bc3b1ff49f4f0d8374f8
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 (from white player perspective)
31 export const ChessRules
= class ChessRules
{
35 // Some variants don't have flags:
36 static get HasFlags() {
40 // Some variants don't have en-passant
41 static get HasEnpassant() {
45 // Some variants cannot have analyse mode
46 static get CanAnalyze() {
50 // Some variants show incomplete information,
51 // and thus show only a partial moves list or no list at all.
52 static get ShowMoves() {
58 return b
; //usual pieces in pieces/ folder
61 // Turn "wb" into "B" (for FEN)
63 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
66 // Turn "p" into "bp" (for board)
68 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
71 // Check if FEN describe a board situation correctly
72 static IsGoodFen(fen
) {
73 const fenParsed
= V
.ParseFen(fen
);
75 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
77 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
78 // 3) Check moves count
79 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
82 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
87 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
94 // Is position part of the FEN a priori correct?
95 static IsGoodPosition(position
) {
96 if (position
.length
== 0) return false;
97 const rows
= position
.split("/");
98 if (rows
.length
!= V
.size
.x
) return false;
100 for (let row
of rows
) {
102 for (let i
= 0; i
< row
.length
; i
++) {
103 if (['K','k'].includes(row
[i
]))
104 kings
[row
[i
]] = true;
105 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
107 const num
= parseInt(row
[i
]);
108 if (isNaN(num
)) return false;
112 if (sumElts
!= V
.size
.y
) return false;
114 // Both kings should be on board:
115 if (Object
.keys(kings
).length
!= 2)
121 static IsGoodTurn(turn
) {
122 return ["w", "b"].includes(turn
);
126 static IsGoodFlags(flags
) {
127 return !!flags
.match(/^[01]{4,4}$/);
130 static IsGoodEnpassant(enpassant
) {
131 if (enpassant
!= "-") {
132 const ep
= V
.SquareToCoords(enpassant
);
133 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
138 // 3 --> d (column number to letter)
139 static CoordToColumn(colnum
) {
140 return String
.fromCharCode(97 + colnum
);
143 // d --> 3 (column letter to number)
144 static ColumnToCoord(column
) {
145 return column
.charCodeAt(0) - 97;
149 static SquareToCoords(sq
) {
151 // NOTE: column is always one char => max 26 columns
152 // row is counted from black side => subtraction
153 x: V
.size
.x
- parseInt(sq
.substr(1)),
154 y: sq
[0].charCodeAt() - 97
159 static CoordsToSquare(coords
) {
160 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
163 // Aggregates flags into one object
165 return this.castleFlags
;
169 disaggregateFlags(flags
) {
170 this.castleFlags
= flags
;
173 // En-passant square, if any
174 getEpSquare(moveOrSquare
) {
175 if (!moveOrSquare
) return undefined;
176 if (typeof moveOrSquare
=== "string") {
177 const square
= moveOrSquare
;
178 if (square
== "-") return undefined;
179 return V
.SquareToCoords(square
);
181 // Argument is a move:
182 const move = moveOrSquare
;
183 const [sx
, sy
, ex
] = [move.start
.x
, move.start
.y
, move.end
.x
];
184 // NOTE: next conditions are first for Atomic, and last for Checkered
186 move.appear
.length
> 0 &&
187 Math
.abs(sx
- ex
) == 2 &&
188 move.appear
[0].p
== V
.PAWN
&&
189 ["w", "b"].includes(move.appear
[0].c
)
196 return undefined; //default
199 // Can thing on square1 take thing on square2
200 canTake([x1
, y1
], [x2
, y2
]) {
201 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
204 // Is (x,y) on the chessboard?
205 static OnBoard(x
, y
) {
206 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
209 // Used in interface: 'side' arg == player color
210 canIplay(side
, [x
, y
]) {
211 return this.turn
== side
&& this.getColor(x
, y
) == side
;
214 // On which squares is color under check ? (for interface)
215 getCheckSquares(color
) {
216 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
217 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
224 // Setup the initial random (assymetric) position
225 static GenRandInitFen() {
226 let pieces
= { w: new Array(8), b: new Array(8) };
227 // Shuffle pieces on first and last rank
228 for (let c
of ["w", "b"]) {
229 let positions
= ArrayFun
.range(8);
231 // Get random squares for bishops
232 let randIndex
= 2 * randInt(4);
233 const bishop1Pos
= positions
[randIndex
];
234 // The second bishop must be on a square of different color
235 let randIndex_tmp
= 2 * randInt(4) + 1;
236 const bishop2Pos
= positions
[randIndex_tmp
];
237 // Remove chosen squares
238 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
239 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
241 // Get random squares for knights
242 randIndex
= randInt(6);
243 const knight1Pos
= positions
[randIndex
];
244 positions
.splice(randIndex
, 1);
245 randIndex
= randInt(5);
246 const knight2Pos
= positions
[randIndex
];
247 positions
.splice(randIndex
, 1);
249 // Get random square for queen
250 randIndex
= randInt(4);
251 const queenPos
= positions
[randIndex
];
252 positions
.splice(randIndex
, 1);
254 // Rooks and king positions are now fixed,
255 // because of the ordering rook-king-rook
256 const rook1Pos
= positions
[0];
257 const kingPos
= positions
[1];
258 const rook2Pos
= positions
[2];
260 // Finally put the shuffled pieces in the board array
261 pieces
[c
][rook1Pos
] = "r";
262 pieces
[c
][knight1Pos
] = "n";
263 pieces
[c
][bishop1Pos
] = "b";
264 pieces
[c
][queenPos
] = "q";
265 pieces
[c
][kingPos
] = "k";
266 pieces
[c
][bishop2Pos
] = "b";
267 pieces
[c
][knight2Pos
] = "n";
268 pieces
[c
][rook2Pos
] = "r";
271 pieces
["b"].join("") +
272 "/pppppppp/8/8/8/8/PPPPPPPP/" +
273 pieces
["w"].join("").toUpperCase() +
275 ); //add turn + flags + enpassant
278 // "Parse" FEN: just return untransformed string data
279 static ParseFen(fen
) {
280 const fenParts
= fen
.split(" ");
282 position: fenParts
[0],
284 movesCount: fenParts
[2]
287 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
288 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
292 // Return current fen (game state)
300 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
301 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
305 // Position part of the FEN string
308 for (let i
= 0; i
< V
.size
.x
; i
++) {
310 for (let j
= 0; j
< V
.size
.y
; j
++) {
311 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
313 if (emptyCount
> 0) {
314 // Add empty squares in-between
315 position
+= emptyCount
;
318 position
+= V
.board2fen(this.board
[i
][j
]);
321 if (emptyCount
> 0) {
323 position
+= emptyCount
;
325 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
334 // Flags part of the FEN string
337 // Add castling flags
338 for (let i
of ["w", "b"]) {
339 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
344 // Enpassant part of the FEN string
346 const L
= this.epSquares
.length
;
347 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
348 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
351 // Turn position fen into double array ["wb","wp","bk",...]
352 static GetBoard(position
) {
353 const rows
= position
.split("/");
354 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
355 for (let i
= 0; i
< rows
.length
; i
++) {
357 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
358 const character
= rows
[i
][indexInRow
];
359 const num
= parseInt(character
);
360 if (!isNaN(num
)) j
+= num
;
362 //something at position i,j
363 else board
[i
][j
++] = V
.fen2board(character
);
369 // Extract (relevant) flags from fen
371 // white a-castle, h-castle, black a-castle, h-castle
372 this.castleFlags
= { w: [true, true], b: [true, true] };
373 if (!fenflags
) return;
374 for (let i
= 0; i
< 4; i
++)
375 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
385 // Fen string fully describes the game state
387 const fenParsed
= V
.ParseFen(fen
);
388 this.board
= V
.GetBoard(fenParsed
.position
);
389 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
390 this.movesCount
= parseInt(fenParsed
.movesCount
);
391 this.setOtherVariables(fen
);
394 // Scan board for kings and rooks positions
395 scanKingsRooks(fen
) {
396 this.INIT_COL_KING
= { w: -1, b: -1 };
397 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
398 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
399 const fenRows
= V
.ParseFen(fen
).position
.split("/");
400 for (let i
= 0; i
< fenRows
.length
; i
++) {
401 let k
= 0; //column index on board
402 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
403 switch (fenRows
[i
].charAt(j
)) {
405 this.kingPos
["b"] = [i
, k
];
406 this.INIT_COL_KING
["b"] = k
;
409 this.kingPos
["w"] = [i
, k
];
410 this.INIT_COL_KING
["w"] = k
;
413 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
414 else this.INIT_COL_ROOK
["b"][1] = k
;
417 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
418 else this.INIT_COL_ROOK
["w"][1] = k
;
421 const num
= parseInt(fenRows
[i
].charAt(j
));
422 if (!isNaN(num
)) k
+= num
- 1;
430 // Some additional variables from FEN (variant dependant)
431 setOtherVariables(fen
) {
432 // Set flags and enpassant:
433 const parsedFen
= V
.ParseFen(fen
);
434 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
435 if (V
.HasEnpassant
) {
437 parsedFen
.enpassant
!= "-"
438 ? this.getEpSquare(parsedFen
.enpassant
)
440 this.epSquares
= [epSq
];
442 // Search for king and rooks positions:
443 this.scanKingsRooks(fen
);
446 /////////////////////
450 return { x: 8, y: 8 };
453 // Color of thing on suqare (i,j). 'undefined' if square is empty
455 return this.board
[i
][j
].charAt(0);
458 // Piece type on square (i,j). 'undefined' if square is empty
460 return this.board
[i
][j
].charAt(1);
463 // Get opponent color
464 static GetOppCol(color
) {
465 return color
== "w" ? "b" : "w";
468 // Pieces codes (for a clearer code)
475 static get KNIGHT() {
478 static get BISHOP() {
489 static get PIECES() {
490 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
498 // Some pieces movements
529 // All possible moves from selected square (assumption: color is OK)
530 getPotentialMovesFrom([x
, y
]) {
531 switch (this.getPiece(x
, y
)) {
533 return this.getPotentialPawnMoves([x
, y
]);
535 return this.getPotentialRookMoves([x
, y
]);
537 return this.getPotentialKnightMoves([x
, y
]);
539 return this.getPotentialBishopMoves([x
, y
]);
541 return this.getPotentialQueenMoves([x
, y
]);
543 return this.getPotentialKingMoves([x
, y
]);
545 return []; //never reached
548 // Build a regular move from its initial and destination squares.
549 // tr: transformation
550 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
556 c: tr
? tr
.c : this.getColor(sx
, sy
),
557 p: tr
? tr
.p : this.getPiece(sx
, sy
)
564 c: this.getColor(sx
, sy
),
565 p: this.getPiece(sx
, sy
)
570 // The opponent piece disappears if we take it
571 if (this.board
[ex
][ey
] != V
.EMPTY
) {
576 c: this.getColor(ex
, ey
),
577 p: this.getPiece(ex
, ey
)
584 // Generic method to find possible moves of non-pawn pieces:
585 // "sliding or jumping"
586 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
588 outerLoop: for (let step
of steps
) {
591 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
592 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
593 if (oneStep
!== undefined) continue outerLoop
;
597 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
598 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
603 // What are the pawn moves from square x,y ?
604 getPotentialPawnMoves([x
, y
]) {
605 const color
= this.turn
;
607 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
608 const shiftX
= color
== "w" ? -1 : 1;
609 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
610 const startRank
= color
== "w" ? sizeX
- 2 : 1;
611 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
612 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
614 // NOTE: next condition is generally true (no pawn on last rank)
615 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
617 x
+ shiftX
== lastRank
618 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
620 // One square forward
621 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
622 for (let piece
of finalPieces
) {
624 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
630 // Next condition because pawns on 1st rank can generally jump
632 [startRank
, firstRank
].includes(x
) &&
633 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
636 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
640 for (let shiftY
of [-1, 1]) {
643 y
+ shiftY
< sizeY
&&
644 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
645 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
647 for (let piece
of finalPieces
) {
649 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
659 if (V
.HasEnpassant
) {
661 const Lep
= this.epSquares
.length
;
662 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
665 epSquare
.x
== x
+ shiftX
&&
666 Math
.abs(epSquare
.y
- y
) == 1
668 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
669 enpassantMove
.vanish
.push({
673 c: this.getColor(x
, epSquare
.y
)
675 moves
.push(enpassantMove
);
682 // What are the rook moves from square x,y ?
683 getPotentialRookMoves(sq
) {
684 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
687 // What are the knight moves from square x,y ?
688 getPotentialKnightMoves(sq
) {
689 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
692 // What are the bishop moves from square x,y ?
693 getPotentialBishopMoves(sq
) {
694 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
697 // What are the queen moves from square x,y ?
698 getPotentialQueenMoves(sq
) {
699 return this.getSlideNJumpMoves(
701 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
705 // What are the king moves from square x,y ?
706 getPotentialKingMoves(sq
) {
707 // Initialize with normal moves
708 let moves
= this.getSlideNJumpMoves(
710 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
713 return moves
.concat(this.getCastleMoves(sq
));
716 getCastleMoves([x
, y
]) {
717 const c
= this.getColor(x
, y
);
718 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
719 return []; //x isn't first rank, or king has moved (shortcut)
722 const oppCol
= V
.GetOppCol(c
);
726 const finalSquares
= [
728 [V
.size
.y
- 2, V
.size
.y
- 3]
733 castleSide
++ //large, then small
735 if (!this.castleFlags
[c
][castleSide
]) continue;
736 // If this code is reached, rooks and king are on initial position
738 // Nothing on the path of the king ? (and no checks)
739 const finDist
= finalSquares
[castleSide
][0] - y
;
740 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
744 this.isAttacked([x
, i
], [oppCol
]) ||
745 (this.board
[x
][i
] != V
.EMPTY
&&
746 // NOTE: next check is enough, because of chessboard constraints
747 (this.getColor(x
, i
) != c
||
748 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
750 continue castlingCheck
;
753 } while (i
!= finalSquares
[castleSide
][0]);
755 // Nothing on the path to the rook?
756 step
= castleSide
== 0 ? -1 : 1;
757 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
758 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
760 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
762 // Nothing on final squares, except maybe king and castling rook?
763 for (i
= 0; i
< 2; i
++) {
765 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
766 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
767 finalSquares
[castleSide
][i
] != rookPos
769 continue castlingCheck
;
773 // If this code is reached, castle is valid
777 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
778 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
781 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
782 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
785 Math
.abs(y
- rookPos
) <= 2
786 ? { x: x
, y: rookPos
}
787 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
798 // For the interface: possible moves for the current turn from square sq
799 getPossibleMovesFrom(sq
) {
800 return this.filterValid(this.getPotentialMovesFrom(sq
));
803 // TODO: promotions (into R,B,N,Q) should be filtered only once
805 if (moves
.length
== 0) return [];
806 const color
= this.turn
;
807 return moves
.filter(m
=> {
809 const res
= !this.underCheck(color
);
815 // Search for all valid moves considering current turn
816 // (for engine and game end)
818 const color
= this.turn
;
819 const oppCol
= V
.GetOppCol(color
);
820 let potentialMoves
= [];
821 for (let i
= 0; i
< V
.size
.x
; i
++) {
822 for (let j
= 0; j
< V
.size
.y
; j
++) {
823 // Next condition "!= oppCol" to work with checkered variant
824 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
825 Array
.prototype.push
.apply(
827 this.getPotentialMovesFrom([i
, j
])
832 return this.filterValid(potentialMoves
);
835 // Stop at the first move found
837 const color
= this.turn
;
838 const oppCol
= V
.GetOppCol(color
);
839 for (let i
= 0; i
< V
.size
.x
; i
++) {
840 for (let j
= 0; j
< V
.size
.y
; j
++) {
841 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
842 const moves
= this.getPotentialMovesFrom([i
, j
]);
843 if (moves
.length
> 0) {
844 for (let k
= 0; k
< moves
.length
; k
++) {
845 if (this.filterValid([moves
[k
]]).length
> 0) return true;
854 // Check if pieces of color in 'colors' are attacking (king) on square x,y
855 isAttacked(sq
, colors
) {
857 this.isAttackedByPawn(sq
, colors
) ||
858 this.isAttackedByRook(sq
, colors
) ||
859 this.isAttackedByKnight(sq
, colors
) ||
860 this.isAttackedByBishop(sq
, colors
) ||
861 this.isAttackedByQueen(sq
, colors
) ||
862 this.isAttackedByKing(sq
, colors
)
866 // Is square x,y attacked by 'colors' pawns ?
867 isAttackedByPawn([x
, y
], colors
) {
868 for (let c
of colors
) {
869 let pawnShift
= c
== "w" ? 1 : -1;
870 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
871 for (let i
of [-1, 1]) {
875 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
876 this.getColor(x
+ pawnShift
, y
+ i
) == c
886 // Is square x,y attacked by 'colors' rooks ?
887 isAttackedByRook(sq
, colors
) {
888 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
891 // Is square x,y attacked by 'colors' knights ?
892 isAttackedByKnight(sq
, colors
) {
893 return this.isAttackedBySlideNJump(
902 // Is square x,y attacked by 'colors' bishops ?
903 isAttackedByBishop(sq
, colors
) {
904 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
907 // Is square x,y attacked by 'colors' queens ?
908 isAttackedByQueen(sq
, colors
) {
909 return this.isAttackedBySlideNJump(
913 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
917 // Is square x,y attacked by 'colors' king(s) ?
918 isAttackedByKing(sq
, colors
) {
919 return this.isAttackedBySlideNJump(
923 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
928 // Generic method for non-pawn pieces ("sliding or jumping"):
929 // is x,y attacked by a piece of color in array 'colors' ?
930 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
931 for (let step
of steps
) {
932 let rx
= x
+ step
[0],
934 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
940 this.getPiece(rx
, ry
) === piece
&&
941 colors
.includes(this.getColor(rx
, ry
))
949 // Is color under check after his move ?
951 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
957 // Apply a move on board
958 static PlayOnBoard(board
, move) {
959 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
960 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
962 // Un-apply the played move
963 static UndoOnBoard(board
, move) {
964 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
965 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
968 // After move is played, update variables + flags
969 updateVariables(move) {
970 let piece
= undefined;
972 if (move.vanish
.length
>= 1) {
973 // Usual case, something is moved
974 piece
= move.vanish
[0].p
;
975 c
= move.vanish
[0].c
;
977 // Crazyhouse-like variants
978 piece
= move.appear
[0].p
;
979 c
= move.appear
[0].c
;
982 //if (!["w","b"].includes(c))
983 // 'c = move.vanish[0].c' doesn't work for Checkered
984 c
= V
.GetOppCol(this.turn
);
986 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
988 // Update king position + flags
989 if (piece
== V
.KING
&& move.appear
.length
> 0) {
990 this.kingPos
[c
][0] = move.appear
[0].x
;
991 this.kingPos
[c
][1] = move.appear
[0].y
;
992 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
996 // Update castling flags if rooks are moved
997 const oppCol
= V
.GetOppCol(c
);
998 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1000 move.start
.x
== firstRank
&& //our rook moves?
1001 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
1003 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
1004 this.castleFlags
[c
][flagIdx
] = false;
1006 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1007 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1009 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1010 this.castleFlags
[oppCol
][flagIdx
] = false;
1015 // After move is undo-ed *and flags resetted*, un-update other variables
1016 // TODO: more symmetry, by storing flags increment in move (?!)
1017 unupdateVariables(move) {
1018 // (Potentially) Reset king position
1019 const c
= this.getColor(move.start
.x
, move.start
.y
);
1020 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1021 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1026 // if (!this.states) this.states = [];
1027 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1028 // this.states.push(stateFen);
1030 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1031 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1032 V
.PlayOnBoard(this.board
, move);
1033 this.turn
= V
.GetOppCol(this.turn
);
1035 this.updateVariables(move);
1039 if (V
.HasEnpassant
) this.epSquares
.pop();
1040 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1041 V
.UndoOnBoard(this.board
, move);
1042 this.turn
= V
.GetOppCol(this.turn
);
1044 this.unupdateVariables(move);
1047 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1048 // if (stateFen != this.states[this.states.length-1]) debugger;
1049 // this.states.pop();
1055 // What is the score ? (Interesting if game is over)
1057 if (this.atLeastOneMove())
1061 const color
= this.turn
;
1062 // No valid move: stalemate or checkmate?
1063 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1066 return color
== "w" ? "0-1" : "1-0";
1073 static get VALUES() {
1084 // "Checkmate" (unreachable eval)
1085 static get INFINITY() {
1089 // At this value or above, the game is over
1090 static get THRESHOLD_MATE() {
1094 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1095 static get SEARCH_DEPTH() {
1099 // NOTE: works also for extinction chess because depth is 3...
1101 const maxeval
= V
.INFINITY
;
1102 const color
= this.turn
;
1103 // Some variants may show a bigger moves list to the human (Switching),
1104 // thus the argument "computer" below (which is generally ignored)
1105 let moves1
= this.getAllValidMoves("computer");
1106 if (moves1
.length
== 0)
1107 //TODO: this situation should not happen
1110 // Can I mate in 1 ? (for Magnetic & Extinction)
1111 for (let i
of shuffle(ArrayFun
.range(moves1
.length
))) {
1112 this.play(moves1
[i
]);
1113 let finish
= Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
;
1115 const score
= this.getCurrentScore();
1116 if (["1-0", "0-1"].includes(score
)) finish
= true;
1118 this.undo(moves1
[i
]);
1119 if (finish
) return moves1
[i
];
1122 // Rank moves using a min-max at depth 2
1123 for (let i
= 0; i
< moves1
.length
; i
++) {
1124 // Initial self evaluation is very low: "I'm checkmated"
1125 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1126 this.play(moves1
[i
]);
1127 const score1
= this.getCurrentScore();
1128 let eval2
= undefined;
1129 if (score1
== "*") {
1130 // Initial enemy evaluation is very low too, for him
1131 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1132 // Second half-move:
1133 let moves2
= this.getAllValidMoves("computer");
1134 for (let j
= 0; j
< moves2
.length
; j
++) {
1135 this.play(moves2
[j
]);
1136 const score2
= this.getCurrentScore();
1137 let evalPos
= 0; //1/2 value
1140 evalPos
= this.evalPosition();
1150 (color
== "w" && evalPos
< eval2
) ||
1151 (color
== "b" && evalPos
> eval2
)
1155 this.undo(moves2
[j
]);
1157 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1159 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1160 (color
== "b" && eval2
< moves1
[i
].eval
)
1162 moves1
[i
].eval
= eval2
;
1164 this.undo(moves1
[i
]);
1166 moves1
.sort((a
, b
) => {
1167 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1170 let candidates
= [0]; //indices of candidates moves
1171 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1173 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1175 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1176 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1177 // From here, depth >= 3: may take a while, so we control time
1178 const timeStart
= Date
.now();
1179 for (let i
= 0; i
< moves1
.length
; i
++) {
1180 if (Date
.now() - timeStart
>= 5000)
1181 //more than 5 seconds
1182 return currentBest
; //depth 2 at least
1183 this.play(moves1
[i
]);
1184 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1186 0.1 * moves1
[i
].eval
+
1187 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1188 this.undo(moves1
[i
]);
1190 moves1
.sort((a
, b
) => {
1191 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1193 } else return currentBest
;
1194 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1197 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1199 return moves1
[candidates
[randInt(candidates
.length
)]];
1202 alphabeta(depth
, alpha
, beta
) {
1203 const maxeval
= V
.INFINITY
;
1204 const color
= this.turn
;
1205 const score
= this.getCurrentScore();
1207 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1208 if (depth
== 0) return this.evalPosition();
1209 const moves
= this.getAllValidMoves("computer");
1210 let v
= color
== "w" ? -maxeval : maxeval
;
1212 for (let i
= 0; i
< moves
.length
; i
++) {
1213 this.play(moves
[i
]);
1214 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1215 this.undo(moves
[i
]);
1216 alpha
= Math
.max(alpha
, v
);
1217 if (alpha
>= beta
) break; //beta cutoff
1221 for (let i
= 0; i
< moves
.length
; i
++) {
1222 this.play(moves
[i
]);
1223 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1224 this.undo(moves
[i
]);
1225 beta
= Math
.min(beta
, v
);
1226 if (alpha
>= beta
) break; //alpha cutoff
1234 // Just count material for now
1235 for (let i
= 0; i
< V
.size
.x
; i
++) {
1236 for (let j
= 0; j
< V
.size
.y
; j
++) {
1237 if (this.board
[i
][j
] != V
.EMPTY
) {
1238 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1239 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1246 /////////////////////////
1247 // MOVES + GAME NOTATION
1248 /////////////////////////
1250 // Context: just before move is played, turn hasn't changed
1251 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1253 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1255 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1257 // Translate final square
1258 const finalSquare
= V
.CoordsToSquare(move.end
);
1260 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1261 if (piece
== V
.PAWN
) {
1264 if (move.vanish
.length
> move.appear
.length
) {
1266 const startColumn
= V
.CoordToColumn(move.start
.y
);
1267 notation
= startColumn
+ "x" + finalSquare
;
1269 else notation
= finalSquare
;
1270 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1272 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1277 piece
.toUpperCase() +
1278 (move.vanish
.length
> move.appear
.length
? "x" : "") +