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 static get HasFlags() {
37 } //some variants don't have flags
39 static get HasEnpassant() {
41 } //some variants don't have ep.
45 return b
; //usual pieces in pieces/ folder
48 // Turn "wb" into "B" (for FEN)
50 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
53 // Turn "p" into "bp" (for board)
55 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
58 // Check if FEN describe a board situation correctly
59 static IsGoodFen(fen
) {
60 const fenParsed
= V
.ParseFen(fen
);
62 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
64 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
65 // 3) Check moves count
66 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
69 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
74 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
81 // Is position part of the FEN a priori correct?
82 static IsGoodPosition(position
) {
83 if (position
.length
== 0) return false;
84 const rows
= position
.split("/");
85 if (rows
.length
!= V
.size
.x
) return false;
86 for (let row
of rows
) {
88 for (let i
= 0; i
< row
.length
; i
++) {
89 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
91 const num
= parseInt(row
[i
]);
92 if (isNaN(num
)) return false;
96 if (sumElts
!= V
.size
.y
) return false;
102 static IsGoodTurn(turn
) {
103 return ["w", "b"].includes(turn
);
107 static IsGoodFlags(flags
) {
108 return !!flags
.match(/^[01]{4,4}$/);
111 static IsGoodEnpassant(enpassant
) {
112 if (enpassant
!= "-") {
113 const ep
= V
.SquareToCoords(enpassant
);
114 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
119 // 3 --> d (column number to letter)
120 static CoordToColumn(colnum
) {
121 return String
.fromCharCode(97 + colnum
);
124 // d --> 3 (column letter to number)
125 static ColumnToCoord(column
) {
126 return column
.charCodeAt(0) - 97;
130 static SquareToCoords(sq
) {
132 // NOTE: column is always one char => max 26 columns
133 // row is counted from black side => subtraction
134 x: V
.size
.x
- parseInt(sq
.substr(1)),
135 y: sq
[0].charCodeAt() - 97
140 static CoordsToSquare(coords
) {
141 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
144 // Aggregates flags into one object
146 return this.castleFlags
;
150 disaggregateFlags(flags
) {
151 this.castleFlags
= flags
;
154 // En-passant square, if any
155 getEpSquare(moveOrSquare
) {
156 if (!moveOrSquare
) return undefined;
157 if (typeof moveOrSquare
=== "string") {
158 const square
= moveOrSquare
;
159 if (square
== "-") return undefined;
160 return V
.SquareToCoords(square
);
162 // Argument is a move:
163 const move = moveOrSquare
;
164 const [sx
, sy
, ex
] = [move.start
.x
, move.start
.y
, move.end
.x
];
165 // NOTE: next conditions are first for Atomic, and last for Checkered
167 move.appear
.length
> 0 &&
168 Math
.abs(sx
- ex
) == 2 &&
169 move.appear
[0].p
== V
.PAWN
&&
170 ["w", "b"].includes(move.appear
[0].c
)
177 return undefined; //default
180 // Can thing on square1 take thing on square2
181 canTake([x1
, y1
], [x2
, y2
]) {
182 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
185 // Is (x,y) on the chessboard?
186 static OnBoard(x
, y
) {
187 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
190 // Used in interface: 'side' arg == player color
191 canIplay(side
, [x
, y
]) {
192 return this.turn
== side
&& this.getColor(x
, y
) == side
;
195 // On which squares is color under check ? (for interface)
196 getCheckSquares(color
) {
197 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
198 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
205 // Setup the initial random (assymetric) position
206 static GenRandInitFen() {
207 let pieces
= { w: new Array(8), b: new Array(8) };
208 // Shuffle pieces on first and last rank
209 for (let c
of ["w", "b"]) {
210 let positions
= ArrayFun
.range(8);
212 // Get random squares for bishops
213 let randIndex
= 2 * randInt(4);
214 const bishop1Pos
= positions
[randIndex
];
215 // The second bishop must be on a square of different color
216 let randIndex_tmp
= 2 * randInt(4) + 1;
217 const bishop2Pos
= positions
[randIndex_tmp
];
218 // Remove chosen squares
219 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
220 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
222 // Get random squares for knights
223 randIndex
= randInt(6);
224 const knight1Pos
= positions
[randIndex
];
225 positions
.splice(randIndex
, 1);
226 randIndex
= randInt(5);
227 const knight2Pos
= positions
[randIndex
];
228 positions
.splice(randIndex
, 1);
230 // Get random square for queen
231 randIndex
= randInt(4);
232 const queenPos
= positions
[randIndex
];
233 positions
.splice(randIndex
, 1);
235 // Rooks and king positions are now fixed,
236 // because of the ordering rook-king-rook
237 const rook1Pos
= positions
[0];
238 const kingPos
= positions
[1];
239 const rook2Pos
= positions
[2];
241 // Finally put the shuffled pieces in the board array
242 pieces
[c
][rook1Pos
] = "r";
243 pieces
[c
][knight1Pos
] = "n";
244 pieces
[c
][bishop1Pos
] = "b";
245 pieces
[c
][queenPos
] = "q";
246 pieces
[c
][kingPos
] = "k";
247 pieces
[c
][bishop2Pos
] = "b";
248 pieces
[c
][knight2Pos
] = "n";
249 pieces
[c
][rook2Pos
] = "r";
252 pieces
["b"].join("") +
253 "/pppppppp/8/8/8/8/PPPPPPPP/" +
254 pieces
["w"].join("").toUpperCase() +
256 ); //add turn + flags + enpassant
259 // "Parse" FEN: just return untransformed string data
260 static ParseFen(fen
) {
261 const fenParts
= fen
.split(" ");
263 position: fenParts
[0],
265 movesCount: fenParts
[2]
268 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
269 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
273 // Return current fen (game state)
281 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
282 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
286 // Position part of the FEN string
289 for (let i
= 0; i
< V
.size
.x
; i
++) {
291 for (let j
= 0; j
< V
.size
.y
; j
++) {
292 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
294 if (emptyCount
> 0) {
295 // Add empty squares in-between
296 position
+= emptyCount
;
299 position
+= V
.board2fen(this.board
[i
][j
]);
302 if (emptyCount
> 0) {
304 position
+= emptyCount
;
306 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
315 // Flags part of the FEN string
318 // Add castling flags
319 for (let i
of ["w", "b"]) {
320 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
325 // Enpassant part of the FEN string
327 const L
= this.epSquares
.length
;
328 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
329 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
332 // Turn position fen into double array ["wb","wp","bk",...]
333 static GetBoard(position
) {
334 const rows
= position
.split("/");
335 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
336 for (let i
= 0; i
< rows
.length
; i
++) {
338 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
339 const character
= rows
[i
][indexInRow
];
340 const num
= parseInt(character
);
341 if (!isNaN(num
)) j
+= num
;
343 //something at position i,j
344 else board
[i
][j
++] = V
.fen2board(character
);
350 // Extract (relevant) flags from fen
352 // white a-castle, h-castle, black a-castle, h-castle
353 this.castleFlags
= { w: [true, true], b: [true, true] };
354 if (!fenflags
) return;
355 for (let i
= 0; i
< 4; i
++)
356 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
366 // Fen string fully describes the game state
368 const fenParsed
= V
.ParseFen(fen
);
369 this.board
= V
.GetBoard(fenParsed
.position
);
370 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
371 this.movesCount
= parseInt(fenParsed
.movesCount
);
372 this.setOtherVariables(fen
);
375 // Scan board for kings and rooks positions
376 scanKingsRooks(fen
) {
377 this.INIT_COL_KING
= { w: -1, b: -1 };
378 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
379 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
380 const fenRows
= V
.ParseFen(fen
).position
.split("/");
381 for (let i
= 0; i
< fenRows
.length
; i
++) {
382 let k
= 0; //column index on board
383 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
384 switch (fenRows
[i
].charAt(j
)) {
386 this.kingPos
["b"] = [i
, k
];
387 this.INIT_COL_KING
["b"] = k
;
390 this.kingPos
["w"] = [i
, k
];
391 this.INIT_COL_KING
["w"] = k
;
394 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
395 else this.INIT_COL_ROOK
["b"][1] = k
;
398 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
399 else this.INIT_COL_ROOK
["w"][1] = k
;
402 const num
= parseInt(fenRows
[i
].charAt(j
));
403 if (!isNaN(num
)) k
+= num
- 1;
411 // Some additional variables from FEN (variant dependant)
412 setOtherVariables(fen
) {
413 // Set flags and enpassant:
414 const parsedFen
= V
.ParseFen(fen
);
415 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
416 if (V
.HasEnpassant
) {
418 parsedFen
.enpassant
!= "-"
419 ? V
.SquareToCoords(parsedFen
.enpassant
)
421 this.epSquares
= [epSq
];
423 // Search for king and rooks positions:
424 this.scanKingsRooks(fen
);
427 /////////////////////
431 return { x: 8, y: 8 };
434 // Color of thing on suqare (i,j). 'undefined' if square is empty
436 return this.board
[i
][j
].charAt(0);
439 // Piece type on square (i,j). 'undefined' if square is empty
441 return this.board
[i
][j
].charAt(1);
444 // Get opponent color
445 static GetOppCol(color
) {
446 return color
== "w" ? "b" : "w";
449 // Pieces codes (for a clearer code)
456 static get KNIGHT() {
459 static get BISHOP() {
470 static get PIECES() {
471 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
479 // Some pieces movements
510 // All possible moves from selected square (assumption: color is OK)
511 getPotentialMovesFrom([x
, y
]) {
512 switch (this.getPiece(x
, y
)) {
514 return this.getPotentialPawnMoves([x
, y
]);
516 return this.getPotentialRookMoves([x
, y
]);
518 return this.getPotentialKnightMoves([x
, y
]);
520 return this.getPotentialBishopMoves([x
, y
]);
522 return this.getPotentialQueenMoves([x
, y
]);
524 return this.getPotentialKingMoves([x
, y
]);
526 return []; //never reached
529 // Build a regular move from its initial and destination squares.
530 // tr: transformation
531 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
537 c: tr
? tr
.c : this.getColor(sx
, sy
),
538 p: tr
? tr
.p : this.getPiece(sx
, sy
)
545 c: this.getColor(sx
, sy
),
546 p: this.getPiece(sx
, sy
)
551 // The opponent piece disappears if we take it
552 if (this.board
[ex
][ey
] != V
.EMPTY
) {
557 c: this.getColor(ex
, ey
),
558 p: this.getPiece(ex
, ey
)
565 // Generic method to find possible moves of non-pawn pieces:
566 // "sliding or jumping"
567 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
569 outerLoop: for (let step
of steps
) {
572 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
573 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
574 if (oneStep
!== undefined) continue outerLoop
;
578 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
579 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
584 // What are the pawn moves from square x,y ?
585 getPotentialPawnMoves([x
, y
]) {
586 const color
= this.turn
;
588 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
589 const shiftX
= color
== "w" ? -1 : 1;
590 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
591 const startRank
= color
== "w" ? sizeX
- 2 : 1;
592 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
593 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
595 // NOTE: next condition is generally true (no pawn on last rank)
596 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
598 x
+ shiftX
== lastRank
599 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
601 // One square forward
602 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
603 for (let piece
of finalPieces
) {
605 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
611 // Next condition because pawns on 1st rank can generally jump
613 [startRank
, firstRank
].includes(x
) &&
614 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
617 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
621 for (let shiftY
of [-1, 1]) {
624 y
+ shiftY
< sizeY
&&
625 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
626 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
628 for (let piece
of finalPieces
) {
630 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
640 if (V
.HasEnpassant
) {
642 const Lep
= this.epSquares
.length
;
643 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
646 epSquare
.x
== x
+ shiftX
&&
647 Math
.abs(epSquare
.y
- y
) == 1
649 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
650 enpassantMove
.vanish
.push({
654 c: this.getColor(x
, epSquare
.y
)
656 moves
.push(enpassantMove
);
663 // What are the rook moves from square x,y ?
664 getPotentialRookMoves(sq
) {
665 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
668 // What are the knight moves from square x,y ?
669 getPotentialKnightMoves(sq
) {
670 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
673 // What are the bishop moves from square x,y ?
674 getPotentialBishopMoves(sq
) {
675 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
678 // What are the queen moves from square x,y ?
679 getPotentialQueenMoves(sq
) {
680 return this.getSlideNJumpMoves(
682 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
686 // What are the king moves from square x,y ?
687 getPotentialKingMoves(sq
) {
688 // Initialize with normal moves
689 let moves
= this.getSlideNJumpMoves(
691 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
694 return moves
.concat(this.getCastleMoves(sq
));
697 getCastleMoves([x
, y
]) {
698 const c
= this.getColor(x
, y
);
699 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
700 return []; //x isn't first rank, or king has moved (shortcut)
703 const oppCol
= V
.GetOppCol(c
);
706 const finalSquares
= [
708 [V
.size
.y
- 2, V
.size
.y
- 3]
713 castleSide
++ //large, then small
715 if (!this.castleFlags
[c
][castleSide
]) continue;
716 // If this code is reached, rooks and king are on initial position
718 // Nothing on the path of the king ? (and no checks)
719 const finDist
= finalSquares
[castleSide
][0] - y
;
720 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
724 this.isAttacked([x
, i
], [oppCol
]) ||
725 (this.board
[x
][i
] != V
.EMPTY
&&
726 // NOTE: next check is enough, because of chessboard constraints
727 (this.getColor(x
, i
) != c
||
728 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
730 continue castlingCheck
;
733 } while (i
!= finalSquares
[castleSide
][0]);
735 // Nothing on the path to the rook?
736 step
= castleSide
== 0 ? -1 : 1;
737 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
738 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
740 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
742 // Nothing on final squares, except maybe king and castling rook?
743 for (i
= 0; i
< 2; i
++) {
745 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
746 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
747 finalSquares
[castleSide
][i
] != rookPos
749 continue castlingCheck
;
753 // If this code is reached, castle is valid
757 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
758 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
761 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
762 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
765 Math
.abs(y
- rookPos
) <= 2
766 ? { x: x
, y: rookPos
}
767 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
778 // For the interface: possible moves for the current turn from square sq
779 getPossibleMovesFrom(sq
) {
780 return this.filterValid(this.getPotentialMovesFrom(sq
));
783 // TODO: promotions (into R,B,N,Q) should be filtered only once
785 if (moves
.length
== 0) return [];
786 const color
= this.turn
;
787 return moves
.filter(m
=> {
789 const res
= !this.underCheck(color
);
795 // Search for all valid moves considering current turn
796 // (for engine and game end)
798 const color
= this.turn
;
799 const oppCol
= V
.GetOppCol(color
);
800 let potentialMoves
= [];
801 for (let i
= 0; i
< V
.size
.x
; i
++) {
802 for (let j
= 0; j
< V
.size
.y
; j
++) {
803 // Next condition "!= oppCol" to work with checkered variant
804 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
805 Array
.prototype.push
.apply(
807 this.getPotentialMovesFrom([i
, j
])
812 return this.filterValid(potentialMoves
);
815 // Stop at the first move found
817 const color
= this.turn
;
818 const oppCol
= V
.GetOppCol(color
);
819 for (let i
= 0; i
< V
.size
.x
; i
++) {
820 for (let j
= 0; j
< V
.size
.y
; j
++) {
821 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
822 const moves
= this.getPotentialMovesFrom([i
, j
]);
823 if (moves
.length
> 0) {
824 for (let k
= 0; k
< moves
.length
; k
++) {
825 if (this.filterValid([moves
[k
]]).length
> 0) return true;
834 // Check if pieces of color in 'colors' are attacking (king) on square x,y
835 isAttacked(sq
, colors
) {
837 this.isAttackedByPawn(sq
, colors
) ||
838 this.isAttackedByRook(sq
, colors
) ||
839 this.isAttackedByKnight(sq
, colors
) ||
840 this.isAttackedByBishop(sq
, colors
) ||
841 this.isAttackedByQueen(sq
, colors
) ||
842 this.isAttackedByKing(sq
, colors
)
846 // Is square x,y attacked by 'colors' pawns ?
847 isAttackedByPawn([x
, y
], colors
) {
848 for (let c
of colors
) {
849 let pawnShift
= c
== "w" ? 1 : -1;
850 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
851 for (let i
of [-1, 1]) {
855 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
856 this.getColor(x
+ pawnShift
, y
+ i
) == c
866 // Is square x,y attacked by 'colors' rooks ?
867 isAttackedByRook(sq
, colors
) {
868 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
871 // Is square x,y attacked by 'colors' knights ?
872 isAttackedByKnight(sq
, colors
) {
873 return this.isAttackedBySlideNJump(
882 // Is square x,y attacked by 'colors' bishops ?
883 isAttackedByBishop(sq
, colors
) {
884 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
887 // Is square x,y attacked by 'colors' queens ?
888 isAttackedByQueen(sq
, colors
) {
889 return this.isAttackedBySlideNJump(
893 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
897 // Is square x,y attacked by 'colors' king(s) ?
898 isAttackedByKing(sq
, colors
) {
899 return this.isAttackedBySlideNJump(
903 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
908 // Generic method for non-pawn pieces ("sliding or jumping"):
909 // is x,y attacked by a piece of color in array 'colors' ?
910 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
911 for (let step
of steps
) {
912 let rx
= x
+ step
[0],
914 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
920 this.getPiece(rx
, ry
) === piece
&&
921 colors
.includes(this.getColor(rx
, ry
))
929 // Is color under check after his move ?
931 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
937 // Apply a move on board
938 static PlayOnBoard(board
, move) {
939 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
940 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
942 // Un-apply the played move
943 static UndoOnBoard(board
, move) {
944 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
945 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
948 // After move is played, update variables + flags
949 updateVariables(move) {
950 let piece
= undefined;
952 if (move.vanish
.length
>= 1) {
953 // Usual case, something is moved
954 piece
= move.vanish
[0].p
;
955 c
= move.vanish
[0].c
;
957 // Crazyhouse-like variants
958 piece
= move.appear
[0].p
;
959 c
= move.appear
[0].c
;
962 //if (!["w","b"].includes(c))
963 // 'c = move.vanish[0].c' doesn't work for Checkered
964 c
= V
.GetOppCol(this.turn
);
966 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
968 // Update king position + flags
969 if (piece
== V
.KING
&& move.appear
.length
> 0) {
970 this.kingPos
[c
][0] = move.appear
[0].x
;
971 this.kingPos
[c
][1] = move.appear
[0].y
;
972 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
976 // Update castling flags if rooks are moved
977 const oppCol
= V
.GetOppCol(c
);
978 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
980 move.start
.x
== firstRank
&& //our rook moves?
981 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
983 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
984 this.castleFlags
[c
][flagIdx
] = false;
986 move.end
.x
== oppFirstRank
&& //we took opponent rook?
987 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
989 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
990 this.castleFlags
[oppCol
][flagIdx
] = false;
995 // After move is undo-ed *and flags resetted*, un-update other variables
996 // TODO: more symmetry, by storing flags increment in move (?!)
997 unupdateVariables(move) {
998 // (Potentially) Reset king position
999 const c
= this.getColor(move.start
.x
, move.start
.y
);
1000 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1001 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1006 // if (!this.states) this.states = [];
1007 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1008 // this.states.push(stateFen);
1010 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1011 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1012 V
.PlayOnBoard(this.board
, move);
1013 this.turn
= V
.GetOppCol(this.turn
);
1015 this.updateVariables(move);
1019 if (V
.HasEnpassant
) this.epSquares
.pop();
1020 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1021 V
.UndoOnBoard(this.board
, move);
1022 this.turn
= V
.GetOppCol(this.turn
);
1024 this.unupdateVariables(move);
1027 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1028 // if (stateFen != this.states[this.states.length-1]) debugger;
1029 // this.states.pop();
1035 // What is the score ? (Interesting if game is over)
1037 if (this.atLeastOneMove())
1042 const color
= this.turn
;
1043 // No valid move: stalemate or checkmate?
1044 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1047 return color
== "w" ? "0-1" : "1-0";
1054 static get VALUES() {
1065 // "Checkmate" (unreachable eval)
1066 static get INFINITY() {
1070 // At this value or above, the game is over
1071 static get THRESHOLD_MATE() {
1075 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1076 static get SEARCH_DEPTH() {
1080 // NOTE: works also for extinction chess because depth is 3...
1082 const maxeval
= V
.INFINITY
;
1083 const color
= this.turn
;
1084 // Some variants may show a bigger moves list to the human (Switching),
1085 // thus the argument "computer" below (which is generally ignored)
1086 let moves1
= this.getAllValidMoves("computer");
1087 if (moves1
.length
== 0)
1088 //TODO: this situation should not happen
1091 // Can I mate in 1 ? (for Magnetic & Extinction)
1092 for (let i
of shuffle(ArrayFun
.range(moves1
.length
))) {
1093 this.play(moves1
[i
]);
1094 let finish
= Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
;
1096 const score
= this.getCurrentScore();
1097 if (["1-0", "0-1"].includes(score
)) finish
= true;
1099 this.undo(moves1
[i
]);
1100 if (finish
) return moves1
[i
];
1103 // Rank moves using a min-max at depth 2
1104 for (let i
= 0; i
< moves1
.length
; i
++) {
1105 // Initial self evaluation is very low: "I'm checkmated"
1106 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1107 this.play(moves1
[i
]);
1108 const score1
= this.getCurrentScore();
1109 let eval2
= undefined;
1110 if (score1
== "*") {
1111 // Initial enemy evaluation is very low too, for him
1112 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1113 // Second half-move:
1114 let moves2
= this.getAllValidMoves("computer");
1115 for (let j
= 0; j
< moves2
.length
; j
++) {
1116 this.play(moves2
[j
]);
1117 const score2
= this.getCurrentScore();
1118 let evalPos
= 0; //1/2 value
1121 evalPos
= this.evalPosition();
1131 (color
== "w" && evalPos
< eval2
) ||
1132 (color
== "b" && evalPos
> eval2
)
1136 this.undo(moves2
[j
]);
1138 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1140 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1141 (color
== "b" && eval2
< moves1
[i
].eval
)
1143 moves1
[i
].eval
= eval2
;
1145 this.undo(moves1
[i
]);
1147 moves1
.sort((a
, b
) => {
1148 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1151 let candidates
= [0]; //indices of candidates moves
1152 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1154 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1156 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1157 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1158 // From here, depth >= 3: may take a while, so we control time
1159 const timeStart
= Date
.now();
1160 for (let i
= 0; i
< moves1
.length
; i
++) {
1161 if (Date
.now() - timeStart
>= 5000)
1162 //more than 5 seconds
1163 return currentBest
; //depth 2 at least
1164 this.play(moves1
[i
]);
1165 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1167 0.1 * moves1
[i
].eval
+
1168 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1169 this.undo(moves1
[i
]);
1171 moves1
.sort((a
, b
) => {
1172 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1174 } else return currentBest
;
1175 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1178 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1180 return moves1
[candidates
[randInt(candidates
.length
)]];
1183 alphabeta(depth
, alpha
, beta
) {
1184 const maxeval
= V
.INFINITY
;
1185 const color
= this.turn
;
1186 const score
= this.getCurrentScore();
1188 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1189 if (depth
== 0) return this.evalPosition();
1190 const moves
= this.getAllValidMoves("computer");
1191 let v
= color
== "w" ? -maxeval : maxeval
;
1193 for (let i
= 0; i
< moves
.length
; i
++) {
1194 this.play(moves
[i
]);
1195 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1196 this.undo(moves
[i
]);
1197 alpha
= Math
.max(alpha
, v
);
1198 if (alpha
>= beta
) break; //beta cutoff
1202 for (let i
= 0; i
< moves
.length
; i
++) {
1203 this.play(moves
[i
]);
1204 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1205 this.undo(moves
[i
]);
1206 beta
= Math
.min(beta
, v
);
1207 if (alpha
>= beta
) break; //alpha cutoff
1215 // Just count material for now
1216 for (let i
= 0; i
< V
.size
.x
; i
++) {
1217 for (let j
= 0; j
< V
.size
.y
; j
++) {
1218 if (this.board
[i
][j
] != V
.EMPTY
) {
1219 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1220 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1227 /////////////////////////
1228 // MOVES + GAME NOTATION
1229 /////////////////////////
1231 // Context: just before move is played, turn hasn't changed
1232 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1234 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1236 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1238 // Translate final square
1239 const finalSquare
= V
.CoordsToSquare(move.end
);
1241 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1242 if (piece
== V
.PAWN
) {
1245 if (move.vanish
.length
> move.appear
.length
) {
1247 const startColumn
= V
.CoordToColumn(move.start
.y
);
1248 notation
= startColumn
+ "x" + finalSquare
;
1250 else notation
= finalSquare
;
1251 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1253 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1258 piece
.toUpperCase() +
1259 (move.vanish
.length
> move.appear
.length
? "x" : "") +