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 export const PiPo
= class PiPo
{
9 // o: {piece[p], color[c], posX[x], posY[y]}
18 // TODO: for animation, moves should contains "moving" and "fading" maybe...
19 export const Move
= class Move
{
20 // o: {appear, vanish, [start,] [end,]}
21 // appear,vanish = arrays of PiPo
22 // start,end = coordinates to apply to trigger move visually (think castle)
24 this.appear
= o
.appear
;
25 this.vanish
= o
.vanish
;
26 this.start
= o
.start
? o
.start : { x: o
.vanish
[0].x
, y: o
.vanish
[0].y
};
27 this.end
= o
.end
? o
.end : { x: o
.appear
[0].x
, y: o
.appear
[0].y
};
31 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
32 export const ChessRules
= class ChessRules
{
36 static get HasFlags() {
38 } //some variants don't have flags
40 static get HasEnpassant() {
42 } //some variants don't have ep.
46 return b
; //usual pieces in pieces/ folder
49 // Turn "wb" into "B" (for FEN)
51 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
54 // Turn "p" into "bp" (for board)
56 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
59 // Check if FEN describe a board situation correctly
60 static IsGoodFen(fen
) {
61 const fenParsed
= V
.ParseFen(fen
);
63 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
65 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
66 // 3) Check moves count
67 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
70 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
75 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
82 // Is position part of the FEN a priori correct?
83 static IsGoodPosition(position
) {
84 if (position
.length
== 0) return false;
85 const rows
= position
.split("/");
86 if (rows
.length
!= V
.size
.x
) return false;
87 for (let row
of rows
) {
89 for (let i
= 0; i
< row
.length
; i
++) {
90 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
92 const num
= parseInt(row
[i
]);
93 if (isNaN(num
)) return false;
97 if (sumElts
!= V
.size
.y
) return false;
103 static IsGoodTurn(turn
) {
104 return ["w", "b"].includes(turn
);
108 static IsGoodFlags(flags
) {
109 return !!flags
.match(/^[01]{4,4}$/);
112 static IsGoodEnpassant(enpassant
) {
113 if (enpassant
!= "-") {
114 const ep
= V
.SquareToCoords(enpassant
);
115 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
120 // 3 --> d (column number to letter)
121 static CoordToColumn(colnum
) {
122 return String
.fromCharCode(97 + colnum
);
125 // d --> 3 (column letter to number)
126 static ColumnToCoord(column
) {
127 return column
.charCodeAt(0) - 97;
131 static SquareToCoords(sq
) {
133 // NOTE: column is always one char => max 26 columns
134 // row is counted from black side => subtraction
135 x: V
.size
.x
- parseInt(sq
.substr(1)),
136 y: sq
[0].charCodeAt() - 97
141 static CoordsToSquare(coords
) {
142 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
145 // Aggregates flags into one object
147 return this.castleFlags
;
151 disaggregateFlags(flags
) {
152 this.castleFlags
= flags
;
155 // En-passant square, if any
156 getEpSquare(moveOrSquare
) {
157 if (!moveOrSquare
) return undefined;
158 if (typeof moveOrSquare
=== "string") {
159 const square
= moveOrSquare
;
160 if (square
== "-") return undefined;
161 return V
.SquareToCoords(square
);
163 // Argument is a move:
164 const move = moveOrSquare
;
165 const [sx
, sy
, ex
] = [move.start
.x
, move.start
.y
, move.end
.x
];
166 // NOTE: next conditions are first for Atomic, and last for Checkered
168 move.appear
.length
> 0 &&
169 Math
.abs(sx
- ex
) == 2 &&
170 move.appear
[0].p
== V
.PAWN
&&
171 ["w", "b"].includes(move.appear
[0].c
)
178 return undefined; //default
181 // Can thing on square1 take thing on square2
182 canTake([x1
, y1
], [x2
, y2
]) {
183 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
186 // Is (x,y) on the chessboard?
187 static OnBoard(x
, y
) {
188 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
191 // Used in interface: 'side' arg == player color
192 canIplay(side
, [x
, y
]) {
193 return this.turn
== side
&& this.getColor(x
, y
) == side
;
196 // On which squares is color under check ? (for interface)
197 getCheckSquares(color
) {
198 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
199 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
206 // Setup the initial random (assymetric) position
207 static GenRandInitFen() {
208 let pieces
= { w: new Array(8), b: new Array(8) };
209 // Shuffle pieces on first and last rank
210 for (let c
of ["w", "b"]) {
211 let positions
= ArrayFun
.range(8);
213 // Get random squares for bishops
214 let randIndex
= 2 * randInt(4);
215 const bishop1Pos
= positions
[randIndex
];
216 // The second bishop must be on a square of different color
217 let randIndex_tmp
= 2 * randInt(4) + 1;
218 const bishop2Pos
= positions
[randIndex_tmp
];
219 // Remove chosen squares
220 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
221 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
223 // Get random squares for knights
224 randIndex
= randInt(6);
225 const knight1Pos
= positions
[randIndex
];
226 positions
.splice(randIndex
, 1);
227 randIndex
= randInt(5);
228 const knight2Pos
= positions
[randIndex
];
229 positions
.splice(randIndex
, 1);
231 // Get random square for queen
232 randIndex
= randInt(4);
233 const queenPos
= positions
[randIndex
];
234 positions
.splice(randIndex
, 1);
236 // Rooks and king positions are now fixed,
237 // because of the ordering rook-king-rook
238 const rook1Pos
= positions
[0];
239 const kingPos
= positions
[1];
240 const rook2Pos
= positions
[2];
242 // Finally put the shuffled pieces in the board array
243 pieces
[c
][rook1Pos
] = "r";
244 pieces
[c
][knight1Pos
] = "n";
245 pieces
[c
][bishop1Pos
] = "b";
246 pieces
[c
][queenPos
] = "q";
247 pieces
[c
][kingPos
] = "k";
248 pieces
[c
][bishop2Pos
] = "b";
249 pieces
[c
][knight2Pos
] = "n";
250 pieces
[c
][rook2Pos
] = "r";
253 pieces
["b"].join("") +
254 "/pppppppp/8/8/8/8/PPPPPPPP/" +
255 pieces
["w"].join("").toUpperCase() +
257 ); //add turn + flags + enpassant
260 // "Parse" FEN: just return untransformed string data
261 static ParseFen(fen
) {
262 const fenParts
= fen
.split(" ");
264 position: fenParts
[0],
266 movesCount: fenParts
[2]
269 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
270 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
274 // Return current fen (game state)
282 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
283 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
287 // Position part of the FEN string
290 for (let i
= 0; i
< V
.size
.x
; i
++) {
292 for (let j
= 0; j
< V
.size
.y
; j
++) {
293 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
295 if (emptyCount
> 0) {
296 // Add empty squares in-between
297 position
+= emptyCount
;
300 position
+= V
.board2fen(this.board
[i
][j
]);
303 if (emptyCount
> 0) {
305 position
+= emptyCount
;
307 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
316 // Flags part of the FEN string
319 // Add castling flags
320 for (let i
of ["w", "b"]) {
321 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
326 // Enpassant part of the FEN string
328 const L
= this.epSquares
.length
;
329 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
330 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
333 // Turn position fen into double array ["wb","wp","bk",...]
334 static GetBoard(position
) {
335 const rows
= position
.split("/");
336 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
337 for (let i
= 0; i
< rows
.length
; i
++) {
339 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
340 const character
= rows
[i
][indexInRow
];
341 const num
= parseInt(character
);
342 if (!isNaN(num
)) j
+= num
;
344 //something at position i,j
345 else board
[i
][j
++] = V
.fen2board(character
);
351 // Extract (relevant) flags from fen
353 // white a-castle, h-castle, black a-castle, h-castle
354 this.castleFlags
= { w: [true, true], b: [true, true] };
355 if (!fenflags
) return;
356 for (let i
= 0; i
< 4; i
++)
357 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
367 // Fen string fully describes the game state
369 const fenParsed
= V
.ParseFen(fen
);
370 this.board
= V
.GetBoard(fenParsed
.position
);
371 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
372 this.movesCount
= parseInt(fenParsed
.movesCount
);
373 this.setOtherVariables(fen
);
376 // Scan board for kings and rooks positions
377 scanKingsRooks(fen
) {
378 this.INIT_COL_KING
= { w: -1, b: -1 };
379 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
380 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
381 const fenRows
= V
.ParseFen(fen
).position
.split("/");
382 for (let i
= 0; i
< fenRows
.length
; i
++) {
383 let k
= 0; //column index on board
384 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
385 switch (fenRows
[i
].charAt(j
)) {
387 this.kingPos
["b"] = [i
, k
];
388 this.INIT_COL_KING
["b"] = k
;
391 this.kingPos
["w"] = [i
, k
];
392 this.INIT_COL_KING
["w"] = k
;
395 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
396 else this.INIT_COL_ROOK
["b"][1] = k
;
399 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
400 else this.INIT_COL_ROOK
["w"][1] = k
;
403 const num
= parseInt(fenRows
[i
].charAt(j
));
404 if (!isNaN(num
)) k
+= num
- 1;
412 // Some additional variables from FEN (variant dependant)
413 setOtherVariables(fen
) {
414 // Set flags and enpassant:
415 const parsedFen
= V
.ParseFen(fen
);
416 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
417 if (V
.HasEnpassant
) {
419 parsedFen
.enpassant
!= "-"
420 ? V
.SquareToCoords(parsedFen
.enpassant
)
422 this.epSquares
= [epSq
];
424 // Search for king and rooks positions:
425 this.scanKingsRooks(fen
);
428 /////////////////////
432 return { x: 8, y: 8 };
435 // Color of thing on suqare (i,j). 'undefined' if square is empty
437 return this.board
[i
][j
].charAt(0);
440 // Piece type on square (i,j). 'undefined' if square is empty
442 return this.board
[i
][j
].charAt(1);
445 // Get opponent color
446 static GetOppCol(color
) {
447 return color
== "w" ? "b" : "w";
450 // Pieces codes (for a clearer code)
457 static get KNIGHT() {
460 static get BISHOP() {
471 static get PIECES() {
472 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
480 // Some pieces movements
511 // All possible moves from selected square (assumption: color is OK)
512 getPotentialMovesFrom([x
, y
]) {
513 switch (this.getPiece(x
, y
)) {
515 return this.getPotentialPawnMoves([x
, y
]);
517 return this.getPotentialRookMoves([x
, y
]);
519 return this.getPotentialKnightMoves([x
, y
]);
521 return this.getPotentialBishopMoves([x
, y
]);
523 return this.getPotentialQueenMoves([x
, y
]);
525 return this.getPotentialKingMoves([x
, y
]);
527 return []; //never reached
530 // Build a regular move from its initial and destination squares.
531 // tr: transformation
532 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
538 c: tr
? tr
.c : this.getColor(sx
, sy
),
539 p: tr
? tr
.p : this.getPiece(sx
, sy
)
546 c: this.getColor(sx
, sy
),
547 p: this.getPiece(sx
, sy
)
552 // The opponent piece disappears if we take it
553 if (this.board
[ex
][ey
] != V
.EMPTY
) {
558 c: this.getColor(ex
, ey
),
559 p: this.getPiece(ex
, ey
)
566 // Generic method to find possible moves of non-pawn pieces:
567 // "sliding or jumping"
568 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
570 outerLoop: for (let step
of steps
) {
573 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
574 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
575 if (oneStep
!== undefined) continue outerLoop
;
579 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
580 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
585 // What are the pawn moves from square x,y ?
586 getPotentialPawnMoves([x
, y
]) {
587 const color
= this.turn
;
589 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
590 const shiftX
= color
== "w" ? -1 : 1;
591 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
592 const startRank
= color
== "w" ? sizeX
- 2 : 1;
593 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
594 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
596 // NOTE: next condition is generally true (no pawn on last rank)
597 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
599 x
+ shiftX
== lastRank
600 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
602 // One square forward
603 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
604 for (let piece
of finalPieces
) {
606 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
612 // Next condition because pawns on 1st rank can generally jump
614 [startRank
, firstRank
].includes(x
) &&
615 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
618 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
622 for (let shiftY
of [-1, 1]) {
625 y
+ shiftY
< sizeY
&&
626 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
627 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
629 for (let piece
of finalPieces
) {
631 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
641 if (V
.HasEnpassant
) {
643 const Lep
= this.epSquares
.length
;
644 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
647 epSquare
.x
== x
+ shiftX
&&
648 Math
.abs(epSquare
.y
- y
) == 1
650 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
651 enpassantMove
.vanish
.push({
655 c: this.getColor(x
, epSquare
.y
)
657 moves
.push(enpassantMove
);
664 // What are the rook moves from square x,y ?
665 getPotentialRookMoves(sq
) {
666 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
669 // What are the knight moves from square x,y ?
670 getPotentialKnightMoves(sq
) {
671 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
674 // What are the bishop moves from square x,y ?
675 getPotentialBishopMoves(sq
) {
676 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
679 // What are the queen moves from square x,y ?
680 getPotentialQueenMoves(sq
) {
681 return this.getSlideNJumpMoves(
683 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
687 // What are the king moves from square x,y ?
688 getPotentialKingMoves(sq
) {
689 // Initialize with normal moves
690 let moves
= this.getSlideNJumpMoves(
692 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
695 return moves
.concat(this.getCastleMoves(sq
));
698 getCastleMoves([x
, y
]) {
699 const c
= this.getColor(x
, y
);
700 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
701 return []; //x isn't first rank, or king has moved (shortcut)
704 const oppCol
= V
.GetOppCol(c
);
707 const finalSquares
= [
709 [V
.size
.y
- 2, V
.size
.y
- 3]
714 castleSide
++ //large, then small
716 if (!this.castleFlags
[c
][castleSide
]) continue;
717 // If this code is reached, rooks and king are on initial position
719 // Nothing on the path of the king ? (and no checks)
720 const finDist
= finalSquares
[castleSide
][0] - y
;
721 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
725 this.isAttacked([x
, i
], [oppCol
]) ||
726 (this.board
[x
][i
] != V
.EMPTY
&&
727 // NOTE: next check is enough, because of chessboard constraints
728 (this.getColor(x
, i
) != c
||
729 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
731 continue castlingCheck
;
734 } while (i
!= finalSquares
[castleSide
][0]);
736 // Nothing on the path to the rook?
737 step
= castleSide
== 0 ? -1 : 1;
738 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
739 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
741 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
743 // Nothing on final squares, except maybe king and castling rook?
744 for (i
= 0; i
< 2; i
++) {
746 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
747 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
748 finalSquares
[castleSide
][i
] != rookPos
750 continue castlingCheck
;
754 // If this code is reached, castle is valid
758 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
759 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
762 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
763 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
766 Math
.abs(y
- rookPos
) <= 2
767 ? { x: x
, y: rookPos
}
768 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
779 // For the interface: possible moves for the current turn from square sq
780 getPossibleMovesFrom(sq
) {
781 return this.filterValid(this.getPotentialMovesFrom(sq
));
784 // TODO: promotions (into R,B,N,Q) should be filtered only once
786 if (moves
.length
== 0) return [];
787 const color
= this.turn
;
788 return moves
.filter(m
=> {
790 const res
= !this.underCheck(color
);
796 // Search for all valid moves considering current turn
797 // (for engine and game end)
799 const color
= this.turn
;
800 const oppCol
= V
.GetOppCol(color
);
801 let potentialMoves
= [];
802 for (let i
= 0; i
< V
.size
.x
; i
++) {
803 for (let j
= 0; j
< V
.size
.y
; j
++) {
804 // Next condition "!= oppCol" to work with checkered variant
805 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
806 Array
.prototype.push
.apply(
808 this.getPotentialMovesFrom([i
, j
])
813 return this.filterValid(potentialMoves
);
816 // Stop at the first move found
818 const color
= this.turn
;
819 const oppCol
= V
.GetOppCol(color
);
820 for (let i
= 0; i
< V
.size
.x
; i
++) {
821 for (let j
= 0; j
< V
.size
.y
; j
++) {
822 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
823 const moves
= this.getPotentialMovesFrom([i
, j
]);
824 if (moves
.length
> 0) {
825 for (let k
= 0; k
< moves
.length
; k
++) {
826 if (this.filterValid([moves
[k
]]).length
> 0) return true;
835 // Check if pieces of color in 'colors' are attacking (king) on square x,y
836 isAttacked(sq
, colors
) {
838 this.isAttackedByPawn(sq
, colors
) ||
839 this.isAttackedByRook(sq
, colors
) ||
840 this.isAttackedByKnight(sq
, colors
) ||
841 this.isAttackedByBishop(sq
, colors
) ||
842 this.isAttackedByQueen(sq
, colors
) ||
843 this.isAttackedByKing(sq
, colors
)
847 // Is square x,y attacked by 'colors' pawns ?
848 isAttackedByPawn([x
, y
], colors
) {
849 for (let c
of colors
) {
850 let pawnShift
= c
== "w" ? 1 : -1;
851 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
852 for (let i
of [-1, 1]) {
856 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
857 this.getColor(x
+ pawnShift
, y
+ i
) == c
867 // Is square x,y attacked by 'colors' rooks ?
868 isAttackedByRook(sq
, colors
) {
869 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
872 // Is square x,y attacked by 'colors' knights ?
873 isAttackedByKnight(sq
, colors
) {
874 return this.isAttackedBySlideNJump(
883 // Is square x,y attacked by 'colors' bishops ?
884 isAttackedByBishop(sq
, colors
) {
885 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
888 // Is square x,y attacked by 'colors' queens ?
889 isAttackedByQueen(sq
, colors
) {
890 return this.isAttackedBySlideNJump(
894 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
898 // Is square x,y attacked by 'colors' king(s) ?
899 isAttackedByKing(sq
, colors
) {
900 return this.isAttackedBySlideNJump(
904 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
909 // Generic method for non-pawn pieces ("sliding or jumping"):
910 // is x,y attacked by a piece of color in array 'colors' ?
911 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
912 for (let step
of steps
) {
913 let rx
= x
+ step
[0],
915 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
921 this.getPiece(rx
, ry
) === piece
&&
922 colors
.includes(this.getColor(rx
, ry
))
930 // Is color under check after his move ?
932 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
938 // Apply a move on board
939 static PlayOnBoard(board
, move) {
940 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
941 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
943 // Un-apply the played move
944 static UndoOnBoard(board
, move) {
945 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
946 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
949 // After move is played, update variables + flags
950 updateVariables(move) {
951 let piece
= undefined;
953 if (move.vanish
.length
>= 1) {
954 // Usual case, something is moved
955 piece
= move.vanish
[0].p
;
956 c
= move.vanish
[0].c
;
958 // Crazyhouse-like variants
959 piece
= move.appear
[0].p
;
960 c
= move.appear
[0].c
;
963 //if (!["w","b"].includes(c))
964 // 'c = move.vanish[0].c' doesn't work for Checkered
965 c
= V
.GetOppCol(this.turn
);
967 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
969 // Update king position + flags
970 if (piece
== V
.KING
&& move.appear
.length
> 0) {
971 this.kingPos
[c
][0] = move.appear
[0].x
;
972 this.kingPos
[c
][1] = move.appear
[0].y
;
973 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
977 // Update castling flags if rooks are moved
978 const oppCol
= V
.GetOppCol(c
);
979 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
981 move.start
.x
== firstRank
&& //our rook moves?
982 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
984 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
985 this.castleFlags
[c
][flagIdx
] = false;
987 move.end
.x
== oppFirstRank
&& //we took opponent rook?
988 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
990 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
991 this.castleFlags
[oppCol
][flagIdx
] = false;
996 // After move is undo-ed *and flags resetted*, un-update other variables
997 // TODO: more symmetry, by storing flags increment in move (?!)
998 unupdateVariables(move) {
999 // (Potentially) Reset king position
1000 const c
= this.getColor(move.start
.x
, move.start
.y
);
1001 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1002 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1007 // if (!this.states) this.states = [];
1008 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1009 // this.states.push(stateFen);
1011 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1012 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1013 V
.PlayOnBoard(this.board
, move);
1014 this.turn
= V
.GetOppCol(this.turn
);
1016 this.updateVariables(move);
1020 if (V
.HasEnpassant
) this.epSquares
.pop();
1021 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1022 V
.UndoOnBoard(this.board
, move);
1023 this.turn
= V
.GetOppCol(this.turn
);
1025 this.unupdateVariables(move);
1028 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1029 // if (stateFen != this.states[this.states.length-1]) debugger;
1030 // this.states.pop();
1036 // What is the score ? (Interesting if game is over)
1038 if (this.atLeastOneMove())
1043 const color
= this.turn
;
1044 // No valid move: stalemate or checkmate?
1045 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1048 return color
== "w" ? "0-1" : "1-0";
1055 static get VALUES() {
1066 // "Checkmate" (unreachable eval)
1067 static get INFINITY() {
1071 // At this value or above, the game is over
1072 static get THRESHOLD_MATE() {
1076 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1077 static get SEARCH_DEPTH() {
1081 // NOTE: works also for extinction chess because depth is 3...
1083 const maxeval
= V
.INFINITY
;
1084 const color
= this.turn
;
1085 // Some variants may show a bigger moves list to the human (Switching),
1086 // thus the argument "computer" below (which is generally ignored)
1087 let moves1
= this.getAllValidMoves("computer");
1088 if (moves1
.length
== 0)
1089 //TODO: this situation should not happen
1092 // Can I mate in 1 ? (for Magnetic & Extinction)
1093 for (let i
of shuffle(ArrayFun
.range(moves1
.length
))) {
1094 this.play(moves1
[i
]);
1095 let finish
= Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
;
1097 const score
= this.getCurrentScore();
1098 if (["1-0", "0-1"].includes(score
)) finish
= true;
1100 this.undo(moves1
[i
]);
1101 if (finish
) return moves1
[i
];
1104 // Rank moves using a min-max at depth 2
1105 for (let i
= 0; i
< moves1
.length
; i
++) {
1106 // Initial self evaluation is very low: "I'm checkmated"
1107 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1108 this.play(moves1
[i
]);
1109 const score1
= this.getCurrentScore();
1110 let eval2
= undefined;
1111 if (score1
== "*") {
1112 // Initial enemy evaluation is very low too, for him
1113 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1114 // Second half-move:
1115 let moves2
= this.getAllValidMoves("computer");
1116 for (let j
= 0; j
< moves2
.length
; j
++) {
1117 this.play(moves2
[j
]);
1118 const score2
= this.getCurrentScore();
1119 let evalPos
= 0; //1/2 value
1122 evalPos
= this.evalPosition();
1132 (color
== "w" && evalPos
< eval2
) ||
1133 (color
== "b" && evalPos
> eval2
)
1137 this.undo(moves2
[j
]);
1139 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1141 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1142 (color
== "b" && eval2
< moves1
[i
].eval
)
1144 moves1
[i
].eval
= eval2
;
1146 this.undo(moves1
[i
]);
1148 moves1
.sort((a
, b
) => {
1149 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1152 let candidates
= [0]; //indices of candidates moves
1153 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1155 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1157 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1158 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1159 // From here, depth >= 3: may take a while, so we control time
1160 const timeStart
= Date
.now();
1161 for (let i
= 0; i
< moves1
.length
; i
++) {
1162 if (Date
.now() - timeStart
>= 5000)
1163 //more than 5 seconds
1164 return currentBest
; //depth 2 at least
1165 this.play(moves1
[i
]);
1166 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1168 0.1 * moves1
[i
].eval
+
1169 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1170 this.undo(moves1
[i
]);
1172 moves1
.sort((a
, b
) => {
1173 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1175 } else return currentBest
;
1176 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1179 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1181 return moves1
[candidates
[randInt(candidates
.length
)]];
1184 alphabeta(depth
, alpha
, beta
) {
1185 const maxeval
= V
.INFINITY
;
1186 const color
= this.turn
;
1187 const score
= this.getCurrentScore();
1189 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1190 if (depth
== 0) return this.evalPosition();
1191 const moves
= this.getAllValidMoves("computer");
1192 let v
= color
== "w" ? -maxeval : maxeval
;
1194 for (let i
= 0; i
< moves
.length
; i
++) {
1195 this.play(moves
[i
]);
1196 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1197 this.undo(moves
[i
]);
1198 alpha
= Math
.max(alpha
, v
);
1199 if (alpha
>= beta
) break; //beta cutoff
1203 for (let i
= 0; i
< moves
.length
; i
++) {
1204 this.play(moves
[i
]);
1205 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1206 this.undo(moves
[i
]);
1207 beta
= Math
.min(beta
, v
);
1208 if (alpha
>= beta
) break; //alpha cutoff
1216 // Just count material for now
1217 for (let i
= 0; i
< V
.size
.x
; i
++) {
1218 for (let j
= 0; j
< V
.size
.y
; j
++) {
1219 if (this.board
[i
][j
] != V
.EMPTY
) {
1220 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1221 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1228 /////////////////////////
1229 // MOVES + GAME NOTATION
1230 /////////////////////////
1232 // Context: just before move is played, turn hasn't changed
1233 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1235 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1237 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1239 // Translate final square
1240 const finalSquare
= V
.CoordsToSquare(move.end
);
1242 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1243 if (piece
== V
.PAWN
) {
1246 if (move.vanish
.length
> move.appear
.length
) {
1248 const startColumn
= V
.CoordToColumn(move.start
.y
);
1249 notation
= startColumn
+ "x" + finalSquare
;
1251 else notation
= finalSquare
;
1252 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1254 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1259 piece
.toUpperCase() +
1260 (move.vanish
.length
> move.appear
.length
? "x" : "") +