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 [sx
, sy
, ex
] = [move.start
.x
, move.start
.y
, move.end
.x
];
199 // NOTE: next conditions are first for Atomic, and last for Checkered
201 move.appear
.length
> 0 &&
202 Math
.abs(sx
- ex
) == 2 &&
203 move.appear
[0].p
== V
.PAWN
&&
204 ["w", "b"].includes(move.appear
[0].c
)
211 return undefined; //default
214 // Can thing on square1 take thing on square2
215 canTake([x1
, y1
], [x2
, y2
]) {
216 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
219 // Is (x,y) on the chessboard?
220 static OnBoard(x
, y
) {
221 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
224 // Used in interface: 'side' arg == player color
225 canIplay(side
, [x
, y
]) {
226 return this.turn
== side
&& this.getColor(x
, y
) == side
;
229 // On which squares is color under check ? (for interface)
230 getCheckSquares(color
) {
231 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
232 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
239 // Setup the initial random (assymetric) position
240 static GenRandInitFen() {
241 let pieces
= { w: new Array(8), b: new Array(8) };
242 // Shuffle pieces on first and last rank
243 for (let c
of ["w", "b"]) {
244 let positions
= ArrayFun
.range(8);
246 // Get random squares for bishops
247 let randIndex
= 2 * randInt(4);
248 const bishop1Pos
= positions
[randIndex
];
249 // The second bishop must be on a square of different color
250 let randIndex_tmp
= 2 * randInt(4) + 1;
251 const bishop2Pos
= positions
[randIndex_tmp
];
252 // Remove chosen squares
253 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
254 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
256 // Get random squares for knights
257 randIndex
= randInt(6);
258 const knight1Pos
= positions
[randIndex
];
259 positions
.splice(randIndex
, 1);
260 randIndex
= randInt(5);
261 const knight2Pos
= positions
[randIndex
];
262 positions
.splice(randIndex
, 1);
264 // Get random square for queen
265 randIndex
= randInt(4);
266 const queenPos
= positions
[randIndex
];
267 positions
.splice(randIndex
, 1);
269 // Rooks and king positions are now fixed,
270 // because of the ordering rook-king-rook
271 const rook1Pos
= positions
[0];
272 const kingPos
= positions
[1];
273 const rook2Pos
= positions
[2];
275 // Finally put the shuffled pieces in the board array
276 pieces
[c
][rook1Pos
] = "r";
277 pieces
[c
][knight1Pos
] = "n";
278 pieces
[c
][bishop1Pos
] = "b";
279 pieces
[c
][queenPos
] = "q";
280 pieces
[c
][kingPos
] = "k";
281 pieces
[c
][bishop2Pos
] = "b";
282 pieces
[c
][knight2Pos
] = "n";
283 pieces
[c
][rook2Pos
] = "r";
285 // Add turn + flags + enpassant
287 pieces
["b"].join("") +
288 "/pppppppp/8/8/8/8/PPPPPPPP/" +
289 pieces
["w"].join("").toUpperCase() +
294 // "Parse" FEN: just return untransformed string data
295 static ParseFen(fen
) {
296 const fenParts
= fen
.split(" ");
298 position: fenParts
[0],
300 movesCount: fenParts
[2]
303 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
304 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
308 // Return current fen (game state)
316 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
317 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
321 // Position part of the FEN string
324 for (let i
= 0; i
< V
.size
.x
; i
++) {
326 for (let j
= 0; j
< V
.size
.y
; j
++) {
327 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
329 if (emptyCount
> 0) {
330 // Add empty squares in-between
331 position
+= emptyCount
;
334 position
+= V
.board2fen(this.board
[i
][j
]);
337 if (emptyCount
> 0) {
339 position
+= emptyCount
;
341 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
350 // Flags part of the FEN string
353 // Add castling flags
354 for (let i
of ["w", "b"]) {
355 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
360 // Enpassant part of the FEN string
362 const L
= this.epSquares
.length
;
363 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
364 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
367 // Turn position fen into double array ["wb","wp","bk",...]
368 static GetBoard(position
) {
369 const rows
= position
.split("/");
370 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
371 for (let i
= 0; i
< rows
.length
; i
++) {
373 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
374 const character
= rows
[i
][indexInRow
];
375 const num
= parseInt(character
);
376 // If num is a number, just shift j:
377 if (!isNaN(num
)) j
+= num
;
378 // Else: something at position i,j
379 else board
[i
][j
++] = V
.fen2board(character
);
385 // Extract (relevant) flags from fen
387 // white a-castle, h-castle, black a-castle, h-castle
388 this.castleFlags
= { w: [true, true], b: [true, true] };
389 for (let i
= 0; i
< 4; i
++)
390 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
397 // In printDiagram() fen isn't supply because only getPpath() is used
402 // Fen string fully describes the game state
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
)
601 // Generic method to find possible moves of non-pawn pieces:
602 // "sliding or jumping"
603 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
605 outerLoop: for (let step
of steps
) {
608 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
609 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
610 if (oneStep
!== undefined) continue outerLoop
;
614 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
615 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
620 // What are the pawn moves from square x,y ?
621 getPotentialPawnMoves([x
, y
]) {
622 const color
= this.turn
;
624 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
625 const shiftX
= color
== "w" ? -1 : 1;
626 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
627 const startRank
= color
== "w" ? sizeX
- 2 : 1;
628 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
629 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
631 // NOTE: next condition is generally true (no pawn on last rank)
632 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
634 x
+ shiftX
== lastRank
635 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
637 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
638 // One square forward
639 for (let piece
of finalPieces
) {
641 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
647 // Next condition because pawns on 1st rank can generally jump
649 [startRank
, firstRank
].includes(x
) &&
650 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
653 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
657 for (let shiftY
of [-1, 1]) {
660 y
+ shiftY
< sizeY
&&
661 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
662 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
664 for (let piece
of finalPieces
) {
666 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
676 if (V
.HasEnpassant
) {
678 const Lep
= this.epSquares
.length
;
679 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
682 epSquare
.x
== x
+ shiftX
&&
683 Math
.abs(epSquare
.y
- y
) == 1
685 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
686 enpassantMove
.vanish
.push({
690 c: this.getColor(x
, epSquare
.y
)
692 moves
.push(enpassantMove
);
699 // What are the rook moves from square x,y ?
700 getPotentialRookMoves(sq
) {
701 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
704 // What are the knight moves from square x,y ?
705 getPotentialKnightMoves(sq
) {
706 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
709 // What are the bishop moves from square x,y ?
710 getPotentialBishopMoves(sq
) {
711 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
714 // What are the queen moves from square x,y ?
715 getPotentialQueenMoves(sq
) {
716 return this.getSlideNJumpMoves(
718 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
722 // What are the king moves from square x,y ?
723 getPotentialKingMoves(sq
) {
724 // Initialize with normal moves
725 let moves
= this.getSlideNJumpMoves(
727 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
730 return moves
.concat(this.getCastleMoves(sq
));
733 getCastleMoves([x
, y
]) {
734 const c
= this.getColor(x
, y
);
735 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
736 return []; //x isn't first rank, or king has moved (shortcut)
739 const oppCol
= V
.GetOppCol(c
);
743 const finalSquares
= [
745 [V
.size
.y
- 2, V
.size
.y
- 3]
750 castleSide
++ //large, then small
752 if (!this.castleFlags
[c
][castleSide
]) continue;
753 // If this code is reached, rooks and king are on initial position
755 // Nothing on the path of the king ? (and no checks)
756 const finDist
= finalSquares
[castleSide
][0] - y
;
757 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
761 this.isAttacked([x
, i
], [oppCol
]) ||
762 (this.board
[x
][i
] != V
.EMPTY
&&
763 // NOTE: next check is enough, because of chessboard constraints
764 (this.getColor(x
, i
) != c
||
765 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
767 continue castlingCheck
;
770 } while (i
!= finalSquares
[castleSide
][0]);
772 // Nothing on the path to the rook?
773 step
= castleSide
== 0 ? -1 : 1;
774 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
775 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
777 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
779 // Nothing on final squares, except maybe king and castling rook?
780 for (i
= 0; i
< 2; i
++) {
782 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
783 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
784 finalSquares
[castleSide
][i
] != rookPos
786 continue castlingCheck
;
790 // If this code is reached, castle is valid
794 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
795 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
798 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
799 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
802 Math
.abs(y
- rookPos
) <= 2
803 ? { x: x
, y: rookPos
}
804 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
815 // For the interface: possible moves for the current turn from square sq
816 getPossibleMovesFrom(sq
) {
817 return this.filterValid(this.getPotentialMovesFrom(sq
));
820 // TODO: promotions (into R,B,N,Q) should be filtered only once
822 if (moves
.length
== 0) return [];
823 const color
= this.turn
;
824 return moves
.filter(m
=> {
826 const res
= !this.underCheck(color
);
832 // Search for all valid moves considering current turn
833 // (for engine and game end)
835 const color
= this.turn
;
836 const oppCol
= V
.GetOppCol(color
);
837 let potentialMoves
= [];
838 for (let i
= 0; i
< V
.size
.x
; i
++) {
839 for (let j
= 0; j
< V
.size
.y
; j
++) {
840 // Next condition "!= oppCol" to work with checkered variant
841 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
842 Array
.prototype.push
.apply(
844 this.getPotentialMovesFrom([i
, j
])
849 return this.filterValid(potentialMoves
);
852 // Stop at the first move found
854 const color
= this.turn
;
855 const oppCol
= V
.GetOppCol(color
);
856 for (let i
= 0; i
< V
.size
.x
; i
++) {
857 for (let j
= 0; j
< V
.size
.y
; j
++) {
858 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) != oppCol
) {
859 const moves
= this.getPotentialMovesFrom([i
, j
]);
860 if (moves
.length
> 0) {
861 for (let k
= 0; k
< moves
.length
; k
++) {
862 if (this.filterValid([moves
[k
]]).length
> 0) return true;
871 // Check if pieces of color in 'colors' are attacking (king) on square x,y
872 isAttacked(sq
, colors
) {
874 this.isAttackedByPawn(sq
, colors
) ||
875 this.isAttackedByRook(sq
, colors
) ||
876 this.isAttackedByKnight(sq
, colors
) ||
877 this.isAttackedByBishop(sq
, colors
) ||
878 this.isAttackedByQueen(sq
, colors
) ||
879 this.isAttackedByKing(sq
, colors
)
883 // Is square x,y attacked by 'colors' pawns ?
884 isAttackedByPawn([x
, y
], colors
) {
885 for (let c
of colors
) {
886 let pawnShift
= c
== "w" ? 1 : -1;
887 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
888 for (let i
of [-1, 1]) {
892 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
893 this.getColor(x
+ pawnShift
, y
+ i
) == c
903 // Is square x,y attacked by 'colors' rooks ?
904 isAttackedByRook(sq
, colors
) {
905 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
908 // Is square x,y attacked by 'colors' knights ?
909 isAttackedByKnight(sq
, colors
) {
910 return this.isAttackedBySlideNJump(
919 // Is square x,y attacked by 'colors' bishops ?
920 isAttackedByBishop(sq
, colors
) {
921 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
924 // Is square x,y attacked by 'colors' queens ?
925 isAttackedByQueen(sq
, colors
) {
926 return this.isAttackedBySlideNJump(
930 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
934 // Is square x,y attacked by 'colors' king(s) ?
935 isAttackedByKing(sq
, colors
) {
936 return this.isAttackedBySlideNJump(
940 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
945 // Generic method for non-pawn pieces ("sliding or jumping"):
946 // is x,y attacked by a piece of color in array 'colors' ?
947 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
948 for (let step
of steps
) {
949 let rx
= x
+ step
[0],
951 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
957 this.getPiece(rx
, ry
) === piece
&&
958 colors
.includes(this.getColor(rx
, ry
))
966 // Is color under check after his move ?
968 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
974 // Apply a move on board
975 static PlayOnBoard(board
, move) {
976 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
977 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
979 // Un-apply the played move
980 static UndoOnBoard(board
, move) {
981 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
982 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
985 // After move is played, update variables + flags
986 updateVariables(move) {
987 let piece
= undefined;
988 // TODO: update variables before move is played, and just use this.turn ?
989 // (doesn't work in general, think MarseilleChess)
991 if (move.vanish
.length
>= 1) {
992 // Usual case, something is moved
993 piece
= move.vanish
[0].p
;
994 c
= move.vanish
[0].c
;
996 // Crazyhouse-like variants
997 piece
= move.appear
[0].p
;
998 c
= move.appear
[0].c
;
1000 if (!['w','b'].includes(c
)) {
1001 // Checkered, for example
1002 c
= V
.GetOppCol(this.turn
);
1004 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1006 // Update king position + flags
1007 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1008 this.kingPos
[c
][0] = move.appear
[0].x
;
1009 this.kingPos
[c
][1] = move.appear
[0].y
;
1010 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
1014 // Update castling flags if rooks are moved
1015 const oppCol
= V
.GetOppCol(c
);
1016 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1018 move.start
.x
== firstRank
&& //our rook moves?
1019 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
1021 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
1022 this.castleFlags
[c
][flagIdx
] = false;
1024 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1025 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1027 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1028 this.castleFlags
[oppCol
][flagIdx
] = false;
1033 // After move is undo-ed *and flags resetted*, un-update other variables
1034 // TODO: more symmetry, by storing flags increment in move (?!)
1035 unupdateVariables(move) {
1036 // (Potentially) Reset king position
1037 const c
= this.getColor(move.start
.x
, move.start
.y
);
1038 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1039 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1044 // if (!this.states) this.states = [];
1045 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1046 // this.states.push(stateFen);
1048 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1049 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1050 V
.PlayOnBoard(this.board
, move);
1051 this.turn
= V
.GetOppCol(this.turn
);
1053 this.updateVariables(move);
1057 if (V
.HasEnpassant
) this.epSquares
.pop();
1058 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1059 V
.UndoOnBoard(this.board
, move);
1060 this.turn
= V
.GetOppCol(this.turn
);
1062 this.unupdateVariables(move);
1065 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1066 // if (stateFen != this.states[this.states.length-1]) debugger;
1067 // this.states.pop();
1073 // What is the score ? (Interesting if game is over)
1075 if (this.atLeastOneMove())
1079 const color
= this.turn
;
1080 // No valid move: stalemate or checkmate?
1081 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1084 return color
== "w" ? "0-1" : "1-0";
1091 static get VALUES() {
1102 // "Checkmate" (unreachable eval)
1103 static get INFINITY() {
1107 // At this value or above, the game is over
1108 static get THRESHOLD_MATE() {
1112 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1113 static get SEARCH_DEPTH() {
1117 // NOTE: works also for extinction chess because depth is 3...
1119 const maxeval
= V
.INFINITY
;
1120 const color
= this.turn
;
1121 // Some variants may show a bigger moves list to the human (Switching),
1122 // thus the argument "computer" below (which is generally ignored)
1123 let moves1
= this.getAllValidMoves("computer");
1124 if (moves1
.length
== 0)
1125 //TODO: this situation should not happen
1128 // Can I mate in 1 ? (for Magnetic & Extinction)
1129 for (let i
of shuffle(ArrayFun
.range(moves1
.length
))) {
1130 this.play(moves1
[i
]);
1131 let finish
= Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
;
1133 const score
= this.getCurrentScore();
1134 if (["1-0", "0-1"].includes(score
)) finish
= true;
1136 this.undo(moves1
[i
]);
1137 if (finish
) return moves1
[i
];
1140 // Rank moves using a min-max at depth 2
1141 for (let i
= 0; i
< moves1
.length
; i
++) {
1142 // Initial self evaluation is very low: "I'm checkmated"
1143 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1144 this.play(moves1
[i
]);
1145 const score1
= this.getCurrentScore();
1146 let eval2
= undefined;
1147 if (score1
== "*") {
1148 // Initial enemy evaluation is very low too, for him
1149 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1150 // Second half-move:
1151 let moves2
= this.getAllValidMoves("computer");
1152 for (let j
= 0; j
< moves2
.length
; j
++) {
1153 this.play(moves2
[j
]);
1154 const score2
= this.getCurrentScore();
1155 let evalPos
= 0; //1/2 value
1158 evalPos
= this.evalPosition();
1168 (color
== "w" && evalPos
< eval2
) ||
1169 (color
== "b" && evalPos
> eval2
)
1173 this.undo(moves2
[j
]);
1175 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1177 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1178 (color
== "b" && eval2
< moves1
[i
].eval
)
1180 moves1
[i
].eval
= eval2
;
1182 this.undo(moves1
[i
]);
1184 moves1
.sort((a
, b
) => {
1185 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1188 let candidates
= [0]; //indices of candidates moves
1189 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1191 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1193 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1194 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1195 // From here, depth >= 3: may take a while, so we control time
1196 const timeStart
= Date
.now();
1197 for (let i
= 0; i
< moves1
.length
; i
++) {
1198 if (Date
.now() - timeStart
>= 5000)
1199 //more than 5 seconds
1200 return currentBest
; //depth 2 at least
1201 this.play(moves1
[i
]);
1202 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1204 0.1 * moves1
[i
].eval
+
1205 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1206 this.undo(moves1
[i
]);
1208 moves1
.sort((a
, b
) => {
1209 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1211 } else return currentBest
;
1212 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1215 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1217 return moves1
[candidates
[randInt(candidates
.length
)]];
1220 alphabeta(depth
, alpha
, beta
) {
1221 const maxeval
= V
.INFINITY
;
1222 const color
= this.turn
;
1223 const score
= this.getCurrentScore();
1225 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1226 if (depth
== 0) return this.evalPosition();
1227 const moves
= this.getAllValidMoves("computer");
1228 let v
= color
== "w" ? -maxeval : maxeval
;
1230 for (let i
= 0; i
< moves
.length
; i
++) {
1231 this.play(moves
[i
]);
1232 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1233 this.undo(moves
[i
]);
1234 alpha
= Math
.max(alpha
, v
);
1235 if (alpha
>= beta
) break; //beta cutoff
1239 for (let i
= 0; i
< moves
.length
; i
++) {
1240 this.play(moves
[i
]);
1241 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1242 this.undo(moves
[i
]);
1243 beta
= Math
.min(beta
, v
);
1244 if (alpha
>= beta
) break; //alpha cutoff
1252 // Just count material for now
1253 for (let i
= 0; i
< V
.size
.x
; i
++) {
1254 for (let j
= 0; j
< V
.size
.y
; j
++) {
1255 if (this.board
[i
][j
] != V
.EMPTY
) {
1256 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1257 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1264 /////////////////////////
1265 // MOVES + GAME NOTATION
1266 /////////////////////////
1268 // Context: just before move is played, turn hasn't changed
1269 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1271 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1273 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1275 // Translate final square
1276 const finalSquare
= V
.CoordsToSquare(move.end
);
1278 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1279 if (piece
== V
.PAWN
) {
1282 if (move.vanish
.length
> move.appear
.length
) {
1284 const startColumn
= V
.CoordToColumn(move.start
.y
);
1285 notation
= startColumn
+ "x" + finalSquare
;
1287 else notation
= finalSquare
;
1288 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1290 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1295 piece
.toUpperCase() +
1296 (move.vanish
.length
> move.appear
.length
? "x" : "") +