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;
99 for (let row
of rows
) {
101 for (let i
= 0; i
< row
.length
; i
++) {
102 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
104 const num
= parseInt(row
[i
]);
105 if (isNaN(num
)) return false;
109 if (sumElts
!= V
.size
.y
) return false;
115 static IsGoodTurn(turn
) {
116 return ["w", "b"].includes(turn
);
120 static IsGoodFlags(flags
) {
121 return !!flags
.match(/^[01]{4,4}$/);
124 static IsGoodEnpassant(enpassant
) {
125 if (enpassant
!= "-") {
126 const ep
= V
.SquareToCoords(enpassant
);
127 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
132 // 3 --> d (column number to letter)
133 static CoordToColumn(colnum
) {
134 return String
.fromCharCode(97 + colnum
);
137 // d --> 3 (column letter to number)
138 static ColumnToCoord(column
) {
139 return column
.charCodeAt(0) - 97;
143 static SquareToCoords(sq
) {
145 // NOTE: column is always one char => max 26 columns
146 // row is counted from black side => subtraction
147 x: V
.size
.x
- parseInt(sq
.substr(1)),
148 y: sq
[0].charCodeAt() - 97
153 static CoordsToSquare(coords
) {
154 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
157 // Aggregates flags into one object
159 return this.castleFlags
;
163 disaggregateFlags(flags
) {
164 this.castleFlags
= flags
;
167 // En-passant square, if any
168 getEpSquare(moveOrSquare
) {
169 if (!moveOrSquare
) return undefined;
170 if (typeof moveOrSquare
=== "string") {
171 const square
= moveOrSquare
;
172 if (square
== "-") return undefined;
173 return V
.SquareToCoords(square
);
175 // Argument is a move:
176 const move = moveOrSquare
;
177 const [sx
, sy
, ex
] = [move.start
.x
, move.start
.y
, move.end
.x
];
178 // NOTE: next conditions are first for Atomic, and last for Checkered
180 move.appear
.length
> 0 &&
181 Math
.abs(sx
- ex
) == 2 &&
182 move.appear
[0].p
== V
.PAWN
&&
183 ["w", "b"].includes(move.appear
[0].c
)
190 return undefined; //default
193 // Can thing on square1 take thing on square2
194 canTake([x1
, y1
], [x2
, y2
]) {
195 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
198 // Is (x,y) on the chessboard?
199 static OnBoard(x
, y
) {
200 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
203 // Used in interface: 'side' arg == player color
204 canIplay(side
, [x
, y
]) {
205 return this.turn
== side
&& this.getColor(x
, y
) == side
;
208 // On which squares is color under check ? (for interface)
209 getCheckSquares(color
) {
210 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
211 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
218 // Setup the initial random (assymetric) position
219 static GenRandInitFen() {
220 let pieces
= { w: new Array(8), b: new Array(8) };
221 // Shuffle pieces on first and last rank
222 for (let c
of ["w", "b"]) {
223 let positions
= ArrayFun
.range(8);
225 // Get random squares for bishops
226 let randIndex
= 2 * randInt(4);
227 const bishop1Pos
= positions
[randIndex
];
228 // The second bishop must be on a square of different color
229 let randIndex_tmp
= 2 * randInt(4) + 1;
230 const bishop2Pos
= positions
[randIndex_tmp
];
231 // Remove chosen squares
232 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
233 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
235 // Get random squares for knights
236 randIndex
= randInt(6);
237 const knight1Pos
= positions
[randIndex
];
238 positions
.splice(randIndex
, 1);
239 randIndex
= randInt(5);
240 const knight2Pos
= positions
[randIndex
];
241 positions
.splice(randIndex
, 1);
243 // Get random square for queen
244 randIndex
= randInt(4);
245 const queenPos
= positions
[randIndex
];
246 positions
.splice(randIndex
, 1);
248 // Rooks and king positions are now fixed,
249 // because of the ordering rook-king-rook
250 const rook1Pos
= positions
[0];
251 const kingPos
= positions
[1];
252 const rook2Pos
= positions
[2];
254 // Finally put the shuffled pieces in the board array
255 pieces
[c
][rook1Pos
] = "r";
256 pieces
[c
][knight1Pos
] = "n";
257 pieces
[c
][bishop1Pos
] = "b";
258 pieces
[c
][queenPos
] = "q";
259 pieces
[c
][kingPos
] = "k";
260 pieces
[c
][bishop2Pos
] = "b";
261 pieces
[c
][knight2Pos
] = "n";
262 pieces
[c
][rook2Pos
] = "r";
265 pieces
["b"].join("") +
266 "/pppppppp/8/8/8/8/PPPPPPPP/" +
267 pieces
["w"].join("").toUpperCase() +
269 ); //add turn + flags + enpassant
272 // "Parse" FEN: just return untransformed string data
273 static ParseFen(fen
) {
274 const fenParts
= fen
.split(" ");
276 position: fenParts
[0],
278 movesCount: fenParts
[2]
281 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
282 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
286 // Return current fen (game state)
294 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
295 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
299 // Position part of the FEN string
302 for (let i
= 0; i
< V
.size
.x
; i
++) {
304 for (let j
= 0; j
< V
.size
.y
; j
++) {
305 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
307 if (emptyCount
> 0) {
308 // Add empty squares in-between
309 position
+= emptyCount
;
312 position
+= V
.board2fen(this.board
[i
][j
]);
315 if (emptyCount
> 0) {
317 position
+= emptyCount
;
319 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
328 // Flags part of the FEN string
331 // Add castling flags
332 for (let i
of ["w", "b"]) {
333 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
338 // Enpassant part of the FEN string
340 const L
= this.epSquares
.length
;
341 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
342 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
345 // Turn position fen into double array ["wb","wp","bk",...]
346 static GetBoard(position
) {
347 const rows
= position
.split("/");
348 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
349 for (let i
= 0; i
< rows
.length
; i
++) {
351 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
352 const character
= rows
[i
][indexInRow
];
353 const num
= parseInt(character
);
354 if (!isNaN(num
)) j
+= num
;
356 //something at position i,j
357 else board
[i
][j
++] = V
.fen2board(character
);
363 // Extract (relevant) flags from fen
365 // white a-castle, h-castle, black a-castle, h-castle
366 this.castleFlags
= { w: [true, true], b: [true, true] };
367 if (!fenflags
) return;
368 for (let i
= 0; i
< 4; i
++)
369 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
379 // Fen string fully describes the game state
381 const fenParsed
= V
.ParseFen(fen
);
382 this.board
= V
.GetBoard(fenParsed
.position
);
383 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
384 this.movesCount
= parseInt(fenParsed
.movesCount
);
385 this.setOtherVariables(fen
);
388 // Scan board for kings and rooks positions
389 scanKingsRooks(fen
) {
390 this.INIT_COL_KING
= { w: -1, b: -1 };
391 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
392 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
393 const fenRows
= V
.ParseFen(fen
).position
.split("/");
394 for (let i
= 0; i
< fenRows
.length
; i
++) {
395 let k
= 0; //column index on board
396 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
397 switch (fenRows
[i
].charAt(j
)) {
399 this.kingPos
["b"] = [i
, k
];
400 this.INIT_COL_KING
["b"] = k
;
403 this.kingPos
["w"] = [i
, k
];
404 this.INIT_COL_KING
["w"] = k
;
407 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
408 else this.INIT_COL_ROOK
["b"][1] = k
;
411 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
412 else this.INIT_COL_ROOK
["w"][1] = k
;
415 const num
= parseInt(fenRows
[i
].charAt(j
));
416 if (!isNaN(num
)) k
+= num
- 1;
424 // Some additional variables from FEN (variant dependant)
425 setOtherVariables(fen
) {
426 // Set flags and enpassant:
427 const parsedFen
= V
.ParseFen(fen
);
428 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
429 if (V
.HasEnpassant
) {
431 parsedFen
.enpassant
!= "-"
432 ? V
.SquareToCoords(parsedFen
.enpassant
)
434 this.epSquares
= [epSq
];
436 // Search for king and rooks positions:
437 this.scanKingsRooks(fen
);
440 /////////////////////
444 return { x: 8, y: 8 };
447 // Color of thing on suqare (i,j). 'undefined' if square is empty
449 return this.board
[i
][j
].charAt(0);
452 // Piece type on square (i,j). 'undefined' if square is empty
454 return this.board
[i
][j
].charAt(1);
457 // Get opponent color
458 static GetOppCol(color
) {
459 return color
== "w" ? "b" : "w";
462 // Pieces codes (for a clearer code)
469 static get KNIGHT() {
472 static get BISHOP() {
483 static get PIECES() {
484 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
492 // Some pieces movements
523 // All possible moves from selected square (assumption: color is OK)
524 getPotentialMovesFrom([x
, y
]) {
525 switch (this.getPiece(x
, y
)) {
527 return this.getPotentialPawnMoves([x
, y
]);
529 return this.getPotentialRookMoves([x
, y
]);
531 return this.getPotentialKnightMoves([x
, y
]);
533 return this.getPotentialBishopMoves([x
, y
]);
535 return this.getPotentialQueenMoves([x
, y
]);
537 return this.getPotentialKingMoves([x
, y
]);
539 return []; //never reached
542 // Build a regular move from its initial and destination squares.
543 // tr: transformation
544 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
550 c: tr
? tr
.c : this.getColor(sx
, sy
),
551 p: tr
? tr
.p : this.getPiece(sx
, sy
)
558 c: this.getColor(sx
, sy
),
559 p: this.getPiece(sx
, sy
)
564 // The opponent piece disappears if we take it
565 if (this.board
[ex
][ey
] != V
.EMPTY
) {
570 c: this.getColor(ex
, ey
),
571 p: this.getPiece(ex
, ey
)
578 // Generic method to find possible moves of non-pawn pieces:
579 // "sliding or jumping"
580 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
582 outerLoop: for (let step
of steps
) {
585 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
586 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
587 if (oneStep
!== undefined) continue outerLoop
;
591 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
592 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
597 // What are the pawn moves from square x,y ?
598 getPotentialPawnMoves([x
, y
]) {
599 const color
= this.turn
;
601 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
602 const shiftX
= color
== "w" ? -1 : 1;
603 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
604 const startRank
= color
== "w" ? sizeX
- 2 : 1;
605 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
606 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
608 // NOTE: next condition is generally true (no pawn on last rank)
609 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
611 x
+ shiftX
== lastRank
612 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
614 // One square forward
615 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
616 for (let piece
of finalPieces
) {
618 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
624 // Next condition because pawns on 1st rank can generally jump
626 [startRank
, firstRank
].includes(x
) &&
627 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
630 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
634 for (let shiftY
of [-1, 1]) {
637 y
+ shiftY
< sizeY
&&
638 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
639 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
641 for (let piece
of finalPieces
) {
643 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
653 if (V
.HasEnpassant
) {
655 const Lep
= this.epSquares
.length
;
656 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
659 epSquare
.x
== x
+ shiftX
&&
660 Math
.abs(epSquare
.y
- y
) == 1
662 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
663 enpassantMove
.vanish
.push({
667 c: this.getColor(x
, epSquare
.y
)
669 moves
.push(enpassantMove
);
676 // What are the rook moves from square x,y ?
677 getPotentialRookMoves(sq
) {
678 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
681 // What are the knight moves from square x,y ?
682 getPotentialKnightMoves(sq
) {
683 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
686 // What are the bishop moves from square x,y ?
687 getPotentialBishopMoves(sq
) {
688 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
691 // What are the queen moves from square x,y ?
692 getPotentialQueenMoves(sq
) {
693 return this.getSlideNJumpMoves(
695 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
699 // What are the king moves from square x,y ?
700 getPotentialKingMoves(sq
) {
701 // Initialize with normal moves
702 let moves
= this.getSlideNJumpMoves(
704 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
707 return moves
.concat(this.getCastleMoves(sq
));
710 getCastleMoves([x
, y
]) {
711 const c
= this.getColor(x
, y
);
712 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
713 return []; //x isn't first rank, or king has moved (shortcut)
716 const oppCol
= V
.GetOppCol(c
);
719 const finalSquares
= [
721 [V
.size
.y
- 2, V
.size
.y
- 3]
726 castleSide
++ //large, then small
728 if (!this.castleFlags
[c
][castleSide
]) continue;
729 // If this code is reached, rooks and king are on initial position
731 // Nothing on the path of the king ? (and no checks)
732 const finDist
= finalSquares
[castleSide
][0] - y
;
733 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
737 this.isAttacked([x
, i
], [oppCol
]) ||
738 (this.board
[x
][i
] != V
.EMPTY
&&
739 // NOTE: next check is enough, because of chessboard constraints
740 (this.getColor(x
, i
) != c
||
741 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
743 continue castlingCheck
;
746 } while (i
!= finalSquares
[castleSide
][0]);
748 // Nothing on the path to the rook?
749 step
= castleSide
== 0 ? -1 : 1;
750 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
751 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
753 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
755 // Nothing on final squares, except maybe king and castling rook?
756 for (i
= 0; i
< 2; i
++) {
758 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
759 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
760 finalSquares
[castleSide
][i
] != rookPos
762 continue castlingCheck
;
766 // If this code is reached, castle is valid
770 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
771 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
774 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
775 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
778 Math
.abs(y
- rookPos
) <= 2
779 ? { x: x
, y: rookPos
}
780 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
791 // For the interface: possible moves for the current turn from square sq
792 getPossibleMovesFrom(sq
) {
793 return this.filterValid(this.getPotentialMovesFrom(sq
));
796 // TODO: promotions (into R,B,N,Q) should be filtered only once
798 if (moves
.length
== 0) return [];
799 const color
= this.turn
;
800 return moves
.filter(m
=> {
802 const res
= !this.underCheck(color
);
808 // Search for all valid moves considering current turn
809 // (for engine and game end)
811 const color
= this.turn
;
812 const oppCol
= V
.GetOppCol(color
);
813 let potentialMoves
= [];
814 for (let i
= 0; i
< V
.size
.x
; i
++) {
815 for (let j
= 0; j
< V
.size
.y
; j
++) {
816 // Next condition "!= oppCol" to work with checkered variant
817 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
818 Array
.prototype.push
.apply(
820 this.getPotentialMovesFrom([i
, j
])
825 return this.filterValid(potentialMoves
);
828 // Stop at the first move found
830 const color
= this.turn
;
831 const oppCol
= V
.GetOppCol(color
);
832 for (let i
= 0; i
< V
.size
.x
; i
++) {
833 for (let j
= 0; j
< V
.size
.y
; j
++) {
834 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
835 const moves
= this.getPotentialMovesFrom([i
, j
]);
836 if (moves
.length
> 0) {
837 for (let k
= 0; k
< moves
.length
; k
++) {
838 if (this.filterValid([moves
[k
]]).length
> 0) return true;
847 // Check if pieces of color in 'colors' are attacking (king) on square x,y
848 isAttacked(sq
, colors
) {
850 this.isAttackedByPawn(sq
, colors
) ||
851 this.isAttackedByRook(sq
, colors
) ||
852 this.isAttackedByKnight(sq
, colors
) ||
853 this.isAttackedByBishop(sq
, colors
) ||
854 this.isAttackedByQueen(sq
, colors
) ||
855 this.isAttackedByKing(sq
, colors
)
859 // Is square x,y attacked by 'colors' pawns ?
860 isAttackedByPawn([x
, y
], colors
) {
861 for (let c
of colors
) {
862 let pawnShift
= c
== "w" ? 1 : -1;
863 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
864 for (let i
of [-1, 1]) {
868 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
869 this.getColor(x
+ pawnShift
, y
+ i
) == c
879 // Is square x,y attacked by 'colors' rooks ?
880 isAttackedByRook(sq
, colors
) {
881 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
884 // Is square x,y attacked by 'colors' knights ?
885 isAttackedByKnight(sq
, colors
) {
886 return this.isAttackedBySlideNJump(
895 // Is square x,y attacked by 'colors' bishops ?
896 isAttackedByBishop(sq
, colors
) {
897 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
900 // Is square x,y attacked by 'colors' queens ?
901 isAttackedByQueen(sq
, colors
) {
902 return this.isAttackedBySlideNJump(
906 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
910 // Is square x,y attacked by 'colors' king(s) ?
911 isAttackedByKing(sq
, colors
) {
912 return this.isAttackedBySlideNJump(
916 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
921 // Generic method for non-pawn pieces ("sliding or jumping"):
922 // is x,y attacked by a piece of color in array 'colors' ?
923 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
924 for (let step
of steps
) {
925 let rx
= x
+ step
[0],
927 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
933 this.getPiece(rx
, ry
) === piece
&&
934 colors
.includes(this.getColor(rx
, ry
))
942 // Is color under check after his move ?
944 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
950 // Apply a move on board
951 static PlayOnBoard(board
, move) {
952 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
953 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
955 // Un-apply the played move
956 static UndoOnBoard(board
, move) {
957 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
958 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
961 // After move is played, update variables + flags
962 updateVariables(move) {
963 let piece
= undefined;
965 if (move.vanish
.length
>= 1) {
966 // Usual case, something is moved
967 piece
= move.vanish
[0].p
;
968 c
= move.vanish
[0].c
;
970 // Crazyhouse-like variants
971 piece
= move.appear
[0].p
;
972 c
= move.appear
[0].c
;
975 //if (!["w","b"].includes(c))
976 // 'c = move.vanish[0].c' doesn't work for Checkered
977 c
= V
.GetOppCol(this.turn
);
979 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
981 // Update king position + flags
982 if (piece
== V
.KING
&& move.appear
.length
> 0) {
983 this.kingPos
[c
][0] = move.appear
[0].x
;
984 this.kingPos
[c
][1] = move.appear
[0].y
;
985 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
989 // Update castling flags if rooks are moved
990 const oppCol
= V
.GetOppCol(c
);
991 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
993 move.start
.x
== firstRank
&& //our rook moves?
994 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
996 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
997 this.castleFlags
[c
][flagIdx
] = false;
999 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1000 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1002 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1003 this.castleFlags
[oppCol
][flagIdx
] = false;
1008 // After move is undo-ed *and flags resetted*, un-update other variables
1009 // TODO: more symmetry, by storing flags increment in move (?!)
1010 unupdateVariables(move) {
1011 // (Potentially) Reset king position
1012 const c
= this.getColor(move.start
.x
, move.start
.y
);
1013 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1014 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1019 // if (!this.states) this.states = [];
1020 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1021 // this.states.push(stateFen);
1023 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1024 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1025 V
.PlayOnBoard(this.board
, move);
1026 this.turn
= V
.GetOppCol(this.turn
);
1028 this.updateVariables(move);
1032 if (V
.HasEnpassant
) this.epSquares
.pop();
1033 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1034 V
.UndoOnBoard(this.board
, move);
1035 this.turn
= V
.GetOppCol(this.turn
);
1037 this.unupdateVariables(move);
1040 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1041 // if (stateFen != this.states[this.states.length-1]) debugger;
1042 // this.states.pop();
1048 // What is the score ? (Interesting if game is over)
1050 if (this.atLeastOneMove())
1055 const color
= this.turn
;
1056 // No valid move: stalemate or checkmate?
1057 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1060 return color
== "w" ? "0-1" : "1-0";
1067 static get VALUES() {
1078 // "Checkmate" (unreachable eval)
1079 static get INFINITY() {
1083 // At this value or above, the game is over
1084 static get THRESHOLD_MATE() {
1088 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1089 static get SEARCH_DEPTH() {
1093 // NOTE: works also for extinction chess because depth is 3...
1095 const maxeval
= V
.INFINITY
;
1096 const color
= this.turn
;
1097 // Some variants may show a bigger moves list to the human (Switching),
1098 // thus the argument "computer" below (which is generally ignored)
1099 let moves1
= this.getAllValidMoves("computer");
1100 if (moves1
.length
== 0)
1101 //TODO: this situation should not happen
1104 // Can I mate in 1 ? (for Magnetic & Extinction)
1105 for (let i
of shuffle(ArrayFun
.range(moves1
.length
))) {
1106 this.play(moves1
[i
]);
1107 let finish
= Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
;
1109 const score
= this.getCurrentScore();
1110 if (["1-0", "0-1"].includes(score
)) finish
= true;
1112 this.undo(moves1
[i
]);
1113 if (finish
) return moves1
[i
];
1116 // Rank moves using a min-max at depth 2
1117 for (let i
= 0; i
< moves1
.length
; i
++) {
1118 // Initial self evaluation is very low: "I'm checkmated"
1119 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1120 this.play(moves1
[i
]);
1121 const score1
= this.getCurrentScore();
1122 let eval2
= undefined;
1123 if (score1
== "*") {
1124 // Initial enemy evaluation is very low too, for him
1125 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1126 // Second half-move:
1127 let moves2
= this.getAllValidMoves("computer");
1128 for (let j
= 0; j
< moves2
.length
; j
++) {
1129 this.play(moves2
[j
]);
1130 const score2
= this.getCurrentScore();
1131 let evalPos
= 0; //1/2 value
1134 evalPos
= this.evalPosition();
1144 (color
== "w" && evalPos
< eval2
) ||
1145 (color
== "b" && evalPos
> eval2
)
1149 this.undo(moves2
[j
]);
1151 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1153 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1154 (color
== "b" && eval2
< moves1
[i
].eval
)
1156 moves1
[i
].eval
= eval2
;
1158 this.undo(moves1
[i
]);
1160 moves1
.sort((a
, b
) => {
1161 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1164 let candidates
= [0]; //indices of candidates moves
1165 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1167 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1169 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1170 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1171 // From here, depth >= 3: may take a while, so we control time
1172 const timeStart
= Date
.now();
1173 for (let i
= 0; i
< moves1
.length
; i
++) {
1174 if (Date
.now() - timeStart
>= 5000)
1175 //more than 5 seconds
1176 return currentBest
; //depth 2 at least
1177 this.play(moves1
[i
]);
1178 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1180 0.1 * moves1
[i
].eval
+
1181 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1182 this.undo(moves1
[i
]);
1184 moves1
.sort((a
, b
) => {
1185 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1187 } else return currentBest
;
1188 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1191 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1193 return moves1
[candidates
[randInt(candidates
.length
)]];
1196 alphabeta(depth
, alpha
, beta
) {
1197 const maxeval
= V
.INFINITY
;
1198 const color
= this.turn
;
1199 const score
= this.getCurrentScore();
1201 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1202 if (depth
== 0) return this.evalPosition();
1203 const moves
= this.getAllValidMoves("computer");
1204 let v
= color
== "w" ? -maxeval : maxeval
;
1206 for (let i
= 0; i
< moves
.length
; i
++) {
1207 this.play(moves
[i
]);
1208 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1209 this.undo(moves
[i
]);
1210 alpha
= Math
.max(alpha
, v
);
1211 if (alpha
>= beta
) break; //beta cutoff
1215 for (let i
= 0; i
< moves
.length
; i
++) {
1216 this.play(moves
[i
]);
1217 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1218 this.undo(moves
[i
]);
1219 beta
= Math
.min(beta
, v
);
1220 if (alpha
>= beta
) break; //alpha cutoff
1228 // Just count material for now
1229 for (let i
= 0; i
< V
.size
.x
; i
++) {
1230 for (let j
= 0; j
< V
.size
.y
; j
++) {
1231 if (this.board
[i
][j
] != V
.EMPTY
) {
1232 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1233 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1240 /////////////////////////
1241 // MOVES + GAME NOTATION
1242 /////////////////////////
1244 // Context: just before move is played, turn hasn't changed
1245 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1247 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1249 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1251 // Translate final square
1252 const finalSquare
= V
.CoordsToSquare(move.end
);
1254 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1255 if (piece
== V
.PAWN
) {
1258 if (move.vanish
.length
> move.appear
.length
) {
1260 const startColumn
= V
.CoordToColumn(move.start
.y
);
1261 notation
= startColumn
+ "x" + finalSquare
;
1263 else notation
= finalSquare
;
1264 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1266 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1271 piece
.toUpperCase() +
1272 (move.vanish
.length
> move.appear
.length
? "x" : "") +