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() {
49 // Patch: issues with javascript OOP, objects can't access static fields.
54 // Some variants show incomplete information,
55 // and thus show only a partial moves list or no list at all.
56 static get ShowMoves() {
63 // Some variants always show the same orientation
64 static get CanFlip() {
71 // Turn "wb" into "B" (for FEN)
73 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
76 // Turn "p" into "bp" (for board)
78 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
81 // Check if FEN describe a board situation correctly
82 static IsGoodFen(fen
) {
83 const fenParsed
= V
.ParseFen(fen
);
85 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
87 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
88 // 3) Check moves count
89 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
92 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
97 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
104 // Is position part of the FEN a priori correct?
105 static IsGoodPosition(position
) {
106 if (position
.length
== 0) return false;
107 const rows
= position
.split("/");
108 if (rows
.length
!= V
.size
.x
) return false;
110 for (let row
of rows
) {
112 for (let i
= 0; i
< row
.length
; i
++) {
113 if (['K','k'].includes(row
[i
]))
114 kings
[row
[i
]] = true;
115 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
117 const num
= parseInt(row
[i
]);
118 if (isNaN(num
)) return false;
122 if (sumElts
!= V
.size
.y
) return false;
124 // Both kings should be on board:
125 if (Object
.keys(kings
).length
!= 2)
131 static IsGoodTurn(turn
) {
132 return ["w", "b"].includes(turn
);
136 static IsGoodFlags(flags
) {
137 return !!flags
.match(/^[01]{4,4}$/);
140 static IsGoodEnpassant(enpassant
) {
141 if (enpassant
!= "-") {
142 const ep
= V
.SquareToCoords(enpassant
);
143 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
148 // 3 --> d (column number to letter)
149 static CoordToColumn(colnum
) {
150 return String
.fromCharCode(97 + colnum
);
153 // d --> 3 (column letter to number)
154 static ColumnToCoord(column
) {
155 return column
.charCodeAt(0) - 97;
159 static SquareToCoords(sq
) {
161 // NOTE: column is always one char => max 26 columns
162 // row is counted from black side => subtraction
163 x: V
.size
.x
- parseInt(sq
.substr(1)),
164 y: sq
[0].charCodeAt() - 97
169 static CoordsToSquare(coords
) {
170 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
175 return b
; //usual pieces in pieces/ folder
178 // Aggregates flags into one object
180 return this.castleFlags
;
184 disaggregateFlags(flags
) {
185 this.castleFlags
= flags
;
188 // En-passant square, if any
189 getEpSquare(moveOrSquare
) {
190 if (!moveOrSquare
) return undefined;
191 if (typeof moveOrSquare
=== "string") {
192 const square
= moveOrSquare
;
193 if (square
== "-") return undefined;
194 return V
.SquareToCoords(square
);
196 // Argument is a move:
197 const move = moveOrSquare
;
198 const s
= move.start
,
200 // NOTE: next conditions are first for Atomic, and last for Checkered
202 move.appear
.length
> 0 &&
203 Math
.abs(s
.x
- e
.x
) == 2 &&
205 move.appear
[0].p
== V
.PAWN
&&
206 ["w", "b"].includes(move.appear
[0].c
)
213 return undefined; //default
216 // Can thing on square1 take thing on square2
217 canTake([x1
, y1
], [x2
, y2
]) {
218 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
221 // Is (x,y) on the chessboard?
222 static OnBoard(x
, y
) {
223 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
226 // Used in interface: 'side' arg == player color
227 canIplay(side
, [x
, y
]) {
228 return this.turn
== side
&& this.getColor(x
, y
) == side
;
231 // On which squares is color under check ? (for interface)
232 getCheckSquares(color
) {
233 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
234 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
241 // Setup the initial random (assymetric) position
242 static GenRandInitFen() {
243 let pieces
= { w: new Array(8), b: new Array(8) };
244 // Shuffle pieces on first and last rank
245 for (let c
of ["w", "b"]) {
246 let positions
= ArrayFun
.range(8);
248 // Get random squares for bishops
249 let randIndex
= 2 * randInt(4);
250 const bishop1Pos
= positions
[randIndex
];
251 // The second bishop must be on a square of different color
252 let randIndex_tmp
= 2 * randInt(4) + 1;
253 const bishop2Pos
= positions
[randIndex_tmp
];
254 // Remove chosen squares
255 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
256 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
258 // Get random squares for knights
259 randIndex
= randInt(6);
260 const knight1Pos
= positions
[randIndex
];
261 positions
.splice(randIndex
, 1);
262 randIndex
= randInt(5);
263 const knight2Pos
= positions
[randIndex
];
264 positions
.splice(randIndex
, 1);
266 // Get random square for queen
267 randIndex
= randInt(4);
268 const queenPos
= positions
[randIndex
];
269 positions
.splice(randIndex
, 1);
271 // Rooks and king positions are now fixed,
272 // because of the ordering rook-king-rook
273 const rook1Pos
= positions
[0];
274 const kingPos
= positions
[1];
275 const rook2Pos
= positions
[2];
277 // Finally put the shuffled pieces in the board array
278 pieces
[c
][rook1Pos
] = "r";
279 pieces
[c
][knight1Pos
] = "n";
280 pieces
[c
][bishop1Pos
] = "b";
281 pieces
[c
][queenPos
] = "q";
282 pieces
[c
][kingPos
] = "k";
283 pieces
[c
][bishop2Pos
] = "b";
284 pieces
[c
][knight2Pos
] = "n";
285 pieces
[c
][rook2Pos
] = "r";
287 // Add turn + flags + enpassant
289 pieces
["b"].join("") +
290 "/pppppppp/8/8/8/8/PPPPPPPP/" +
291 pieces
["w"].join("").toUpperCase() +
296 // "Parse" FEN: just return untransformed string data
297 static ParseFen(fen
) {
298 const fenParts
= fen
.split(" ");
300 position: fenParts
[0],
302 movesCount: fenParts
[2]
305 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
306 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
310 // Return current fen (game state)
318 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
319 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
323 // Position part of the FEN string
326 for (let i
= 0; i
< V
.size
.x
; i
++) {
328 for (let j
= 0; j
< V
.size
.y
; j
++) {
329 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
331 if (emptyCount
> 0) {
332 // Add empty squares in-between
333 position
+= emptyCount
;
336 position
+= V
.board2fen(this.board
[i
][j
]);
339 if (emptyCount
> 0) {
341 position
+= emptyCount
;
343 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
352 // Flags part of the FEN string
355 // Add castling flags
356 for (let i
of ["w", "b"]) {
357 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
362 // Enpassant part of the FEN string
364 const L
= this.epSquares
.length
;
365 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
366 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
369 // Turn position fen into double array ["wb","wp","bk",...]
370 static GetBoard(position
) {
371 const rows
= position
.split("/");
372 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
373 for (let i
= 0; i
< rows
.length
; i
++) {
375 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
376 const character
= rows
[i
][indexInRow
];
377 const num
= parseInt(character
);
378 // If num is a number, just shift j:
379 if (!isNaN(num
)) j
+= num
;
380 // Else: something at position i,j
381 else board
[i
][j
++] = V
.fen2board(character
);
387 // Extract (relevant) flags from fen
389 // white a-castle, h-castle, black a-castle, h-castle
390 this.castleFlags
= { w: [true, true], b: [true, true] };
391 for (let i
= 0; i
< 4; i
++)
392 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
398 // Fen string fully describes the game state
401 // In printDiagram() fen isn't supply because only getPpath() is used
402 // TODO: find a better solution!
404 const fenParsed
= V
.ParseFen(fen
);
405 this.board
= V
.GetBoard(fenParsed
.position
);
406 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
407 this.movesCount
= parseInt(fenParsed
.movesCount
);
408 this.setOtherVariables(fen
);
411 // Scan board for kings and rooks positions
412 scanKingsRooks(fen
) {
413 this.INIT_COL_KING
= { w: -1, b: -1 };
414 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
415 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
416 const fenRows
= V
.ParseFen(fen
).position
.split("/");
417 for (let i
= 0; i
< fenRows
.length
; i
++) {
418 let k
= 0; //column index on board
419 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
420 switch (fenRows
[i
].charAt(j
)) {
422 this.kingPos
["b"] = [i
, k
];
423 this.INIT_COL_KING
["b"] = k
;
426 this.kingPos
["w"] = [i
, k
];
427 this.INIT_COL_KING
["w"] = k
;
430 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
431 else this.INIT_COL_ROOK
["b"][1] = k
;
434 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
435 else this.INIT_COL_ROOK
["w"][1] = k
;
438 const num
= parseInt(fenRows
[i
].charAt(j
));
439 if (!isNaN(num
)) k
+= num
- 1;
447 // Some additional variables from FEN (variant dependant)
448 setOtherVariables(fen
) {
449 // Set flags and enpassant:
450 const parsedFen
= V
.ParseFen(fen
);
451 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
452 if (V
.HasEnpassant
) {
454 parsedFen
.enpassant
!= "-"
455 ? this.getEpSquare(parsedFen
.enpassant
)
457 this.epSquares
= [epSq
];
459 // Search for king and rooks positions:
460 this.scanKingsRooks(fen
);
463 /////////////////////
467 return { x: 8, y: 8 };
470 // Color of thing on square (i,j). 'undefined' if square is empty
472 return this.board
[i
][j
].charAt(0);
475 // Piece type on square (i,j). 'undefined' if square is empty
477 return this.board
[i
][j
].charAt(1);
480 // Get opponent color
481 static GetOppCol(color
) {
482 return color
== "w" ? "b" : "w";
485 // Pieces codes (for a clearer code)
492 static get KNIGHT() {
495 static get BISHOP() {
506 static get PIECES() {
507 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
515 // Some pieces movements
546 // All possible moves from selected square
547 getPotentialMovesFrom([x
, y
]) {
548 switch (this.getPiece(x
, y
)) {
550 return this.getPotentialPawnMoves([x
, y
]);
552 return this.getPotentialRookMoves([x
, y
]);
554 return this.getPotentialKnightMoves([x
, y
]);
556 return this.getPotentialBishopMoves([x
, y
]);
558 return this.getPotentialQueenMoves([x
, y
]);
560 return this.getPotentialKingMoves([x
, y
]);
562 return []; //never reached
565 // Build a regular move from its initial and destination squares.
566 // tr: transformation
567 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
573 c: tr
? tr
.c : this.getColor(sx
, sy
),
574 p: tr
? tr
.p : this.getPiece(sx
, sy
)
581 c: this.getColor(sx
, sy
),
582 p: this.getPiece(sx
, sy
)
587 // The opponent piece disappears if we take it
588 if (this.board
[ex
][ey
] != V
.EMPTY
) {
593 c: this.getColor(ex
, ey
),
594 p: this.getPiece(ex
, ey
)
602 // Generic method to find possible moves of non-pawn pieces:
603 // "sliding or jumping"
604 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
606 outerLoop: for (let step
of steps
) {
609 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
610 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
611 if (oneStep
) continue outerLoop
;
615 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
616 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
621 // What are the pawn moves from square x,y ?
622 getPotentialPawnMoves([x
, y
]) {
623 const color
= this.turn
;
625 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
626 const shiftX
= color
== "w" ? -1 : 1;
627 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
628 const startRank
= color
== "w" ? sizeX
- 2 : 1;
629 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
630 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
632 // NOTE: next condition is generally true (no pawn on last rank)
633 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
635 x
+ shiftX
== lastRank
636 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
638 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
639 // One square forward
640 for (let piece
of finalPieces
) {
642 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
648 // Next condition because pawns on 1st rank can generally jump
650 [startRank
, firstRank
].includes(x
) &&
651 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
654 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
658 for (let shiftY
of [-1, 1]) {
661 y
+ shiftY
< sizeY
&&
662 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
663 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
665 for (let piece
of finalPieces
) {
667 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
677 if (V
.HasEnpassant
) {
679 const Lep
= this.epSquares
.length
;
680 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
683 epSquare
.x
== x
+ shiftX
&&
684 Math
.abs(epSquare
.y
- y
) == 1
686 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
687 enpassantMove
.vanish
.push({
691 c: this.getColor(x
, epSquare
.y
)
693 moves
.push(enpassantMove
);
700 // What are the rook moves from square x,y ?
701 getPotentialRookMoves(sq
) {
702 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
705 // What are the knight moves from square x,y ?
706 getPotentialKnightMoves(sq
) {
707 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
710 // What are the bishop moves from square x,y ?
711 getPotentialBishopMoves(sq
) {
712 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
715 // What are the queen moves from square x,y ?
716 getPotentialQueenMoves(sq
) {
717 return this.getSlideNJumpMoves(
719 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
723 // What are the king moves from square x,y ?
724 getPotentialKingMoves(sq
) {
725 // Initialize with normal moves
726 let moves
= this.getSlideNJumpMoves(
728 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
731 return moves
.concat(this.getCastleMoves(sq
));
734 getCastleMoves([x
, y
]) {
735 const c
= this.getColor(x
, y
);
736 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
737 return []; //x isn't first rank, or king has moved (shortcut)
740 const oppCol
= V
.GetOppCol(c
);
744 const finalSquares
= [
746 [V
.size
.y
- 2, V
.size
.y
- 3]
751 castleSide
++ //large, then small
753 if (!this.castleFlags
[c
][castleSide
]) continue;
754 // If this code is reached, rooks and king are on initial position
756 // Nothing on the path of the king ? (and no checks)
757 const finDist
= finalSquares
[castleSide
][0] - y
;
758 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
762 this.isAttacked([x
, i
], [oppCol
]) ||
763 (this.board
[x
][i
] != V
.EMPTY
&&
764 // NOTE: next check is enough, because of chessboard constraints
765 (this.getColor(x
, i
) != c
||
766 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
768 continue castlingCheck
;
771 } while (i
!= finalSquares
[castleSide
][0]);
773 // Nothing on the path to the rook?
774 step
= castleSide
== 0 ? -1 : 1;
775 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
776 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
778 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
780 // Nothing on final squares, except maybe king and castling rook?
781 for (i
= 0; i
< 2; i
++) {
783 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
784 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
785 finalSquares
[castleSide
][i
] != rookPos
787 continue castlingCheck
;
791 // If this code is reached, castle is valid
795 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
796 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
799 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
800 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
803 Math
.abs(y
- rookPos
) <= 2
804 ? { x: x
, y: rookPos
}
805 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
816 // For the interface: possible moves for the current turn from square sq
817 getPossibleMovesFrom(sq
) {
818 return this.filterValid(this.getPotentialMovesFrom(sq
));
821 // TODO: promotions (into R,B,N,Q) should be filtered only once
823 if (moves
.length
== 0) return [];
824 const color
= this.turn
;
825 return moves
.filter(m
=> {
827 const res
= !this.underCheck(color
);
833 // Search for all valid moves considering current turn
834 // (for engine and game end)
836 const color
= this.turn
;
837 let potentialMoves
= [];
838 for (let i
= 0; i
< V
.size
.x
; i
++) {
839 for (let j
= 0; j
< V
.size
.y
; j
++) {
840 if (this.getColor(i
, j
) == color
) {
841 Array
.prototype.push
.apply(
843 this.getPotentialMovesFrom([i
, j
])
848 return this.filterValid(potentialMoves
);
851 // Stop at the first move found
853 const color
= this.turn
;
854 for (let i
= 0; i
< V
.size
.x
; i
++) {
855 for (let j
= 0; j
< V
.size
.y
; j
++) {
856 if (this.getColor(i
, j
) == color
) {
857 const moves
= this.getPotentialMovesFrom([i
, j
]);
858 if (moves
.length
> 0) {
859 for (let k
= 0; k
< moves
.length
; k
++) {
860 if (this.filterValid([moves
[k
]]).length
> 0) return true;
869 // Check if pieces of color in 'colors' are attacking (king) on square x,y
870 isAttacked(sq
, colors
) {
872 this.isAttackedByPawn(sq
, colors
) ||
873 this.isAttackedByRook(sq
, colors
) ||
874 this.isAttackedByKnight(sq
, colors
) ||
875 this.isAttackedByBishop(sq
, colors
) ||
876 this.isAttackedByQueen(sq
, colors
) ||
877 this.isAttackedByKing(sq
, colors
)
881 // Generic method for non-pawn pieces ("sliding or jumping"):
882 // is x,y attacked by a piece of color in array 'colors' ?
883 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
884 for (let step
of steps
) {
885 let rx
= x
+ step
[0],
887 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
893 this.getPiece(rx
, ry
) === piece
&&
894 colors
.includes(this.getColor(rx
, ry
))
902 // Is square x,y attacked by 'colors' pawns ?
903 isAttackedByPawn([x
, y
], colors
) {
904 for (let c
of colors
) {
905 const pawnShift
= c
== "w" ? 1 : -1;
906 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
907 for (let i
of [-1, 1]) {
911 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
912 this.getColor(x
+ pawnShift
, y
+ i
) == c
922 // Is square x,y attacked by 'colors' rooks ?
923 isAttackedByRook(sq
, colors
) {
924 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
927 // Is square x,y attacked by 'colors' knights ?
928 isAttackedByKnight(sq
, colors
) {
929 return this.isAttackedBySlideNJump(
938 // Is square x,y attacked by 'colors' bishops ?
939 isAttackedByBishop(sq
, colors
) {
940 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
943 // Is square x,y attacked by 'colors' queens ?
944 isAttackedByQueen(sq
, colors
) {
945 return this.isAttackedBySlideNJump(
949 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
953 // Is square x,y attacked by 'colors' king(s) ?
954 isAttackedByKing(sq
, colors
) {
955 return this.isAttackedBySlideNJump(
959 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
964 // Is color under check after his move ?
966 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
972 // Apply a move on board
973 static PlayOnBoard(board
, move) {
974 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
975 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
977 // Un-apply the played move
978 static UndoOnBoard(board
, move) {
979 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
980 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
983 // After move is played, update variables + flags
984 updateVariables(move) {
985 let piece
= undefined;
986 // TODO: update variables before move is played, and just use this.turn ?
987 // (doesn't work in general, think MarseilleChess)
989 if (move.vanish
.length
>= 1) {
990 // Usual case, something is moved
991 piece
= move.vanish
[0].p
;
992 c
= move.vanish
[0].c
;
994 // Crazyhouse-like variants
995 piece
= move.appear
[0].p
;
996 c
= move.appear
[0].c
;
998 if (!['w','b'].includes(c
)) {
999 // Checkered, for example
1000 c
= V
.GetOppCol(this.turn
);
1002 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1004 // Update king position + flags
1005 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1006 this.kingPos
[c
][0] = move.appear
[0].x
;
1007 this.kingPos
[c
][1] = move.appear
[0].y
;
1008 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
1012 // Update castling flags if rooks are moved
1013 const oppCol
= V
.GetOppCol(c
);
1014 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1016 move.start
.x
== firstRank
&& //our rook moves?
1017 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
1019 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
1020 this.castleFlags
[c
][flagIdx
] = false;
1022 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1023 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1025 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1026 this.castleFlags
[oppCol
][flagIdx
] = false;
1031 // After move is undo-ed *and flags resetted*, un-update other variables
1032 // TODO: more symmetry, by storing flags increment in move (?!)
1033 unupdateVariables(move) {
1034 // (Potentially) Reset king position
1035 const c
= this.getColor(move.start
.x
, move.start
.y
);
1036 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1037 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1042 // if (!this.states) this.states = [];
1043 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1044 // this.states.push(stateFen);
1046 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1047 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1048 V
.PlayOnBoard(this.board
, move);
1049 this.turn
= V
.GetOppCol(this.turn
);
1051 this.updateVariables(move);
1055 if (V
.HasEnpassant
) this.epSquares
.pop();
1056 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1057 V
.UndoOnBoard(this.board
, move);
1058 this.turn
= V
.GetOppCol(this.turn
);
1060 this.unupdateVariables(move);
1063 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1064 // if (stateFen != this.states[this.states.length-1]) debugger;
1065 // this.states.pop();
1071 // What is the score ? (Interesting if game is over)
1073 if (this.atLeastOneMove())
1077 const color
= this.turn
;
1078 // No valid move: stalemate or checkmate?
1079 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1082 return color
== "w" ? "0-1" : "1-0";
1089 static get VALUES() {
1100 // "Checkmate" (unreachable eval)
1101 static get INFINITY() {
1105 // At this value or above, the game is over
1106 static get THRESHOLD_MATE() {
1110 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1111 static get SEARCH_DEPTH() {
1116 const maxeval
= V
.INFINITY
;
1117 const color
= this.turn
;
1118 // Some variants may show a bigger moves list to the human (Switching),
1119 // thus the argument "computer" below (which is generally ignored)
1120 let moves1
= this.getAllValidMoves();
1122 if (moves1
.length
== 0)
1123 // TODO: this situation should not happen
1126 // Rank moves using a min-max at depth 2
1127 for (let i
= 0; i
< moves1
.length
; i
++) {
1128 // Initial self evaluation is very low: "I'm checkmated"
1129 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1130 this.play(moves1
[i
]);
1131 const score1
= this.getCurrentScore();
1132 let eval2
= undefined;
1133 if (score1
== "*") {
1134 // Initial enemy evaluation is very low too, for him
1135 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1136 // Second half-move:
1137 let moves2
= this.getAllValidMoves();
1138 for (let j
= 0; j
< moves2
.length
; j
++) {
1139 this.play(moves2
[j
]);
1140 const score2
= this.getCurrentScore();
1141 let evalPos
= 0; //1/2 value
1144 evalPos
= this.evalPosition();
1154 (color
== "w" && evalPos
< eval2
) ||
1155 (color
== "b" && evalPos
> eval2
)
1159 this.undo(moves2
[j
]);
1161 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1163 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1164 (color
== "b" && eval2
< moves1
[i
].eval
)
1166 moves1
[i
].eval
= eval2
;
1168 this.undo(moves1
[i
]);
1170 moves1
.sort((a
, b
) => {
1171 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1173 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1175 let candidates
= [0]; //indices of candidates moves
1176 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1178 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1180 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1181 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1182 // From here, depth >= 3: may take a while, so we control time
1183 const timeStart
= Date
.now();
1184 for (let i
= 0; i
< moves1
.length
; i
++) {
1185 if (Date
.now() - timeStart
>= 5000)
1186 //more than 5 seconds
1187 return currentBest
; //depth 2 at least
1188 this.play(moves1
[i
]);
1189 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1191 0.1 * moves1
[i
].eval
+
1192 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1193 this.undo(moves1
[i
]);
1195 moves1
.sort((a
, b
) => {
1196 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1198 } else return currentBest
;
1199 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1202 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1204 return moves1
[candidates
[randInt(candidates
.length
)]];
1207 alphabeta(depth
, alpha
, beta
) {
1208 const maxeval
= V
.INFINITY
;
1209 const color
= this.turn
;
1210 const score
= this.getCurrentScore();
1212 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1213 if (depth
== 0) return this.evalPosition();
1214 const moves
= this.getAllValidMoves();
1215 let v
= color
== "w" ? -maxeval : maxeval
;
1217 for (let i
= 0; i
< moves
.length
; i
++) {
1218 this.play(moves
[i
]);
1219 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1220 this.undo(moves
[i
]);
1221 alpha
= Math
.max(alpha
, v
);
1222 if (alpha
>= beta
) break; //beta cutoff
1227 for (let i
= 0; i
< moves
.length
; i
++) {
1228 this.play(moves
[i
]);
1229 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1230 this.undo(moves
[i
]);
1231 beta
= Math
.min(beta
, v
);
1232 if (alpha
>= beta
) break; //alpha cutoff
1240 // Just count material for now
1241 for (let i
= 0; i
< V
.size
.x
; i
++) {
1242 for (let j
= 0; j
< V
.size
.y
; j
++) {
1243 if (this.board
[i
][j
] != V
.EMPTY
) {
1244 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1245 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1252 /////////////////////////
1253 // MOVES + GAME NOTATION
1254 /////////////////////////
1256 // Context: just before move is played, turn hasn't changed
1257 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1259 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1261 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1263 // Translate final square
1264 const finalSquare
= V
.CoordsToSquare(move.end
);
1266 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1267 if (piece
== V
.PAWN
) {
1270 if (move.vanish
.length
> move.appear
.length
) {
1272 const startColumn
= V
.CoordToColumn(move.start
.y
);
1273 notation
= startColumn
+ "x" + finalSquare
;
1275 else notation
= finalSquare
;
1276 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1278 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1283 piece
.toUpperCase() +
1284 (move.vanish
.length
> move.appear
.length
? "x" : "") +