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
,
201 Math
.abs(s
.x
- e
.x
) == 2 &&
203 move.appear
[0].p
== V
.PAWN
210 return undefined; //default
213 // Can thing on square1 take thing on square2
214 canTake([x1
, y1
], [x2
, y2
]) {
215 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
218 // Is (x,y) on the chessboard?
219 static OnBoard(x
, y
) {
220 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
223 // Used in interface: 'side' arg == player color
224 canIplay(side
, [x
, y
]) {
225 return this.turn
== side
&& this.getColor(x
, y
) == side
;
228 // On which squares is color under check ? (for interface)
229 getCheckSquares(color
) {
230 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
231 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
238 // Setup the initial random (asymmetric) position
239 static GenRandInitFen(randomness
) {
242 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 1111 -";
244 let pieces
= { w: new Array(8), b: new Array(8) };
245 // Shuffle pieces on first (and last rank if randomness == 2)
246 for (let c
of ["w", "b"]) {
247 if (c
== 'b' && randomness
== 1) {
248 pieces
['b'] = pieces
['w'];
252 let positions
= ArrayFun
.range(8);
254 // Get random squares for bishops
255 let randIndex
= 2 * randInt(4);
256 const bishop1Pos
= positions
[randIndex
];
257 // The second bishop must be on a square of different color
258 let randIndex_tmp
= 2 * randInt(4) + 1;
259 const bishop2Pos
= positions
[randIndex_tmp
];
260 // Remove chosen squares
261 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
262 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
264 // Get random squares for knights
265 randIndex
= randInt(6);
266 const knight1Pos
= positions
[randIndex
];
267 positions
.splice(randIndex
, 1);
268 randIndex
= randInt(5);
269 const knight2Pos
= positions
[randIndex
];
270 positions
.splice(randIndex
, 1);
272 // Get random square for queen
273 randIndex
= randInt(4);
274 const queenPos
= positions
[randIndex
];
275 positions
.splice(randIndex
, 1);
277 // Rooks and king positions are now fixed,
278 // because of the ordering rook-king-rook
279 const rook1Pos
= positions
[0];
280 const kingPos
= positions
[1];
281 const rook2Pos
= positions
[2];
283 // Finally put the shuffled pieces in the board array
284 pieces
[c
][rook1Pos
] = "r";
285 pieces
[c
][knight1Pos
] = "n";
286 pieces
[c
][bishop1Pos
] = "b";
287 pieces
[c
][queenPos
] = "q";
288 pieces
[c
][kingPos
] = "k";
289 pieces
[c
][bishop2Pos
] = "b";
290 pieces
[c
][knight2Pos
] = "n";
291 pieces
[c
][rook2Pos
] = "r";
293 // Add turn + flags + enpassant
295 pieces
["b"].join("") +
296 "/pppppppp/8/8/8/8/PPPPPPPP/" +
297 pieces
["w"].join("").toUpperCase() +
302 // "Parse" FEN: just return untransformed string data
303 static ParseFen(fen
) {
304 const fenParts
= fen
.split(" ");
306 position: fenParts
[0],
308 movesCount: fenParts
[2]
311 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
312 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
316 // Return current fen (game state)
319 this.getBaseFen() + " " +
320 this.getTurnFen() + " " +
322 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
323 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
328 // Omit movesCount, only variable allowed to differ
330 this.getBaseFen() + "_" +
332 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
333 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
337 // Position part of the FEN string
340 for (let i
= 0; i
< V
.size
.x
; i
++) {
342 for (let j
= 0; j
< V
.size
.y
; j
++) {
343 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
345 if (emptyCount
> 0) {
346 // Add empty squares in-between
347 position
+= emptyCount
;
350 position
+= V
.board2fen(this.board
[i
][j
]);
353 if (emptyCount
> 0) {
355 position
+= emptyCount
;
357 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
366 // Flags part of the FEN string
369 // Add castling flags
370 for (let i
of ["w", "b"]) {
371 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
376 // Enpassant part of the FEN string
378 const L
= this.epSquares
.length
;
379 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
380 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
383 // Turn position fen into double array ["wb","wp","bk",...]
384 static GetBoard(position
) {
385 const rows
= position
.split("/");
386 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
387 for (let i
= 0; i
< rows
.length
; i
++) {
389 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
390 const character
= rows
[i
][indexInRow
];
391 const num
= parseInt(character
);
392 // If num is a number, just shift j:
393 if (!isNaN(num
)) j
+= num
;
394 // Else: something at position i,j
395 else board
[i
][j
++] = V
.fen2board(character
);
401 // Extract (relevant) flags from fen
403 // white a-castle, h-castle, black a-castle, h-castle
404 this.castleFlags
= { w: [true, true], b: [true, true] };
405 for (let i
= 0; i
< 4; i
++)
406 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
412 // Fen string fully describes the game state
415 // In printDiagram() fen isn't supply because only getPpath() is used
416 // TODO: find a better solution!
418 const fenParsed
= V
.ParseFen(fen
);
419 this.board
= V
.GetBoard(fenParsed
.position
);
420 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
421 this.movesCount
= parseInt(fenParsed
.movesCount
);
422 this.setOtherVariables(fen
);
425 // Scan board for kings and rooks positions
426 scanKingsRooks(fen
) {
427 this.INIT_COL_KING
= { w: -1, b: -1 };
428 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
429 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
430 const fenRows
= V
.ParseFen(fen
).position
.split("/");
431 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
432 for (let i
= 0; i
< fenRows
.length
; i
++) {
433 let k
= 0; //column index on board
434 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
435 switch (fenRows
[i
].charAt(j
)) {
437 this.kingPos
["b"] = [i
, k
];
438 this.INIT_COL_KING
["b"] = k
;
441 this.kingPos
["w"] = [i
, k
];
442 this.INIT_COL_KING
["w"] = k
;
445 if (i
== startRow
['b']) {
446 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
447 else this.INIT_COL_ROOK
["b"][1] = k
;
451 if (i
== startRow
['w']) {
452 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
453 else this.INIT_COL_ROOK
["w"][1] = k
;
457 const num
= parseInt(fenRows
[i
].charAt(j
));
458 if (!isNaN(num
)) k
+= num
- 1;
466 // Some additional variables from FEN (variant dependant)
467 setOtherVariables(fen
) {
468 // Set flags and enpassant:
469 const parsedFen
= V
.ParseFen(fen
);
470 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
471 if (V
.HasEnpassant
) {
473 parsedFen
.enpassant
!= "-"
474 ? this.getEpSquare(parsedFen
.enpassant
)
476 this.epSquares
= [epSq
];
478 // Search for king and rooks positions:
479 this.scanKingsRooks(fen
);
482 /////////////////////
486 return { x: 8, y: 8 };
489 // Color of thing on square (i,j). 'undefined' if square is empty
491 return this.board
[i
][j
].charAt(0);
494 // Piece type on square (i,j). 'undefined' if square is empty
496 return this.board
[i
][j
].charAt(1);
499 // Get opponent color
500 static GetOppCol(color
) {
501 return color
== "w" ? "b" : "w";
504 // Pieces codes (for a clearer code)
511 static get KNIGHT() {
514 static get BISHOP() {
525 static get PIECES() {
526 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
534 // Some pieces movements
565 // All possible moves from selected square
566 getPotentialMovesFrom([x
, y
]) {
567 switch (this.getPiece(x
, y
)) {
569 return this.getPotentialPawnMoves([x
, y
]);
571 return this.getPotentialRookMoves([x
, y
]);
573 return this.getPotentialKnightMoves([x
, y
]);
575 return this.getPotentialBishopMoves([x
, y
]);
577 return this.getPotentialQueenMoves([x
, y
]);
579 return this.getPotentialKingMoves([x
, y
]);
581 return []; //never reached
584 // Build a regular move from its initial and destination squares.
585 // tr: transformation
586 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
592 c: tr
? tr
.c : this.getColor(sx
, sy
),
593 p: tr
? tr
.p : this.getPiece(sx
, sy
)
600 c: this.getColor(sx
, sy
),
601 p: this.getPiece(sx
, sy
)
606 // The opponent piece disappears if we take it
607 if (this.board
[ex
][ey
] != V
.EMPTY
) {
612 c: this.getColor(ex
, ey
),
613 p: this.getPiece(ex
, ey
)
621 // Generic method to find possible moves of non-pawn pieces:
622 // "sliding or jumping"
623 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
625 outerLoop: for (let step
of steps
) {
628 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
629 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
630 if (oneStep
) continue outerLoop
;
634 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
635 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
640 // What are the pawn moves from square x,y ?
641 getPotentialPawnMoves([x
, y
]) {
642 const color
= this.turn
;
644 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
645 const shiftX
= color
== "w" ? -1 : 1;
646 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
647 const startRank
= color
== "w" ? sizeX
- 2 : 1;
648 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
650 // NOTE: next condition is generally true (no pawn on last rank)
651 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
653 x
+ shiftX
== lastRank
654 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
656 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
657 // One square forward
658 for (let piece
of finalPieces
) {
660 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
666 // Next condition because pawns on 1st rank can generally jump
668 [startRank
, firstRank
].includes(x
) &&
669 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
672 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
676 for (let shiftY
of [-1, 1]) {
679 y
+ shiftY
< sizeY
&&
680 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
681 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
683 for (let piece
of finalPieces
) {
685 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
695 if (V
.HasEnpassant
) {
697 const Lep
= this.epSquares
.length
;
698 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
701 epSquare
.x
== x
+ shiftX
&&
702 Math
.abs(epSquare
.y
- y
) == 1
704 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
705 enpassantMove
.vanish
.push({
709 c: this.getColor(x
, epSquare
.y
)
711 moves
.push(enpassantMove
);
718 // What are the rook moves from square x,y ?
719 getPotentialRookMoves(sq
) {
720 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
723 // What are the knight moves from square x,y ?
724 getPotentialKnightMoves(sq
) {
725 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
728 // What are the bishop moves from square x,y ?
729 getPotentialBishopMoves(sq
) {
730 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
733 // What are the queen moves from square x,y ?
734 getPotentialQueenMoves(sq
) {
735 return this.getSlideNJumpMoves(
737 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
741 // What are the king moves from square x,y ?
742 getPotentialKingMoves(sq
) {
743 // Initialize with normal moves
744 let moves
= this.getSlideNJumpMoves(
746 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
749 return moves
.concat(this.getCastleMoves(sq
));
752 getCastleMoves([x
, y
]) {
753 const c
= this.getColor(x
, y
);
754 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
755 return []; //x isn't first rank, or king has moved (shortcut)
758 const oppCol
= V
.GetOppCol(c
);
762 const finalSquares
= [
764 [V
.size
.y
- 2, V
.size
.y
- 3]
769 castleSide
++ //large, then small
771 if (!this.castleFlags
[c
][castleSide
]) continue;
772 // If this code is reached, rooks and king are on initial position
774 // Nothing on the path of the king ? (and no checks)
775 const finDist
= finalSquares
[castleSide
][0] - y
;
776 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
780 this.isAttacked([x
, i
], [oppCol
]) ||
781 (this.board
[x
][i
] != V
.EMPTY
&&
782 // NOTE: next check is enough, because of chessboard constraints
783 (this.getColor(x
, i
) != c
||
784 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
786 continue castlingCheck
;
789 } while (i
!= finalSquares
[castleSide
][0]);
791 // Nothing on the path to the rook?
792 step
= castleSide
== 0 ? -1 : 1;
793 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
794 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
796 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
798 // Nothing on final squares, except maybe king and castling rook?
799 for (i
= 0; i
< 2; i
++) {
801 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
802 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
803 finalSquares
[castleSide
][i
] != rookPos
805 continue castlingCheck
;
809 // If this code is reached, castle is valid
813 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
814 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
817 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
818 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
821 Math
.abs(y
- rookPos
) <= 2
822 ? { x: x
, y: rookPos
}
823 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
834 // For the interface: possible moves for the current turn from square sq
835 getPossibleMovesFrom(sq
) {
836 return this.filterValid(this.getPotentialMovesFrom(sq
));
839 // TODO: promotions (into R,B,N,Q) should be filtered only once
841 if (moves
.length
== 0) return [];
842 const color
= this.turn
;
843 return moves
.filter(m
=> {
845 const res
= !this.underCheck(color
);
851 // Search for all valid moves considering current turn
852 // (for engine and game end)
854 const color
= this.turn
;
855 let potentialMoves
= [];
856 for (let i
= 0; i
< V
.size
.x
; i
++) {
857 for (let j
= 0; j
< V
.size
.y
; j
++) {
858 if (this.getColor(i
, j
) == color
) {
859 Array
.prototype.push
.apply(
861 this.getPotentialMovesFrom([i
, j
])
866 return this.filterValid(potentialMoves
);
869 // Stop at the first move found
871 const color
= this.turn
;
872 for (let i
= 0; i
< V
.size
.x
; i
++) {
873 for (let j
= 0; j
< V
.size
.y
; j
++) {
874 if (this.getColor(i
, j
) == color
) {
875 const moves
= this.getPotentialMovesFrom([i
, j
]);
876 if (moves
.length
> 0) {
877 for (let k
= 0; k
< moves
.length
; k
++) {
878 if (this.filterValid([moves
[k
]]).length
> 0) return true;
887 // Check if pieces of color in 'colors' are attacking (king) on square x,y
888 isAttacked(sq
, colors
) {
890 this.isAttackedByPawn(sq
, colors
) ||
891 this.isAttackedByRook(sq
, colors
) ||
892 this.isAttackedByKnight(sq
, colors
) ||
893 this.isAttackedByBishop(sq
, colors
) ||
894 this.isAttackedByQueen(sq
, colors
) ||
895 this.isAttackedByKing(sq
, colors
)
899 // Generic method for non-pawn pieces ("sliding or jumping"):
900 // is x,y attacked by a piece of color in array 'colors' ?
901 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
902 for (let step
of steps
) {
903 let rx
= x
+ step
[0],
905 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
911 this.getPiece(rx
, ry
) === piece
&&
912 colors
.includes(this.getColor(rx
, ry
))
920 // Is square x,y attacked by 'colors' pawns ?
921 isAttackedByPawn([x
, y
], colors
) {
922 for (let c
of colors
) {
923 const pawnShift
= c
== "w" ? 1 : -1;
924 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
925 for (let i
of [-1, 1]) {
929 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
930 this.getColor(x
+ pawnShift
, y
+ i
) == c
940 // Is square x,y attacked by 'colors' rooks ?
941 isAttackedByRook(sq
, colors
) {
942 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
945 // Is square x,y attacked by 'colors' knights ?
946 isAttackedByKnight(sq
, colors
) {
947 return this.isAttackedBySlideNJump(
956 // Is square x,y attacked by 'colors' bishops ?
957 isAttackedByBishop(sq
, colors
) {
958 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
961 // Is square x,y attacked by 'colors' queens ?
962 isAttackedByQueen(sq
, colors
) {
963 return this.isAttackedBySlideNJump(
967 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
971 // Is square x,y attacked by 'colors' king(s) ?
972 isAttackedByKing(sq
, colors
) {
973 return this.isAttackedBySlideNJump(
977 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
982 // Is color under check after his move ?
984 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
990 // Apply a move on board
991 static PlayOnBoard(board
, move) {
992 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
993 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
995 // Un-apply the played move
996 static UndoOnBoard(board
, move) {
997 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
998 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1001 // After move is played, update variables + flags
1002 updateVariables(move) {
1003 let piece
= undefined;
1004 // TODO: update variables before move is played, and just use this.turn?
1005 // (doesn't work in general, think MarseilleChess)
1007 if (move.vanish
.length
>= 1) {
1008 // Usual case, something is moved
1009 piece
= move.vanish
[0].p
;
1010 c
= move.vanish
[0].c
;
1012 // Crazyhouse-like variants
1013 piece
= move.appear
[0].p
;
1014 c
= move.appear
[0].c
;
1016 if (!['w','b'].includes(c
)) {
1017 // Checkered, for example
1018 c
= V
.GetOppCol(this.turn
);
1020 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1022 // Update king position + flags
1023 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1024 this.kingPos
[c
][0] = move.appear
[0].x
;
1025 this.kingPos
[c
][1] = move.appear
[0].y
;
1026 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
1030 // Update castling flags if rooks are moved
1031 const oppCol
= V
.GetOppCol(c
);
1032 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1034 move.start
.x
== firstRank
&& //our rook moves?
1035 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
1037 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
1038 this.castleFlags
[c
][flagIdx
] = false;
1040 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1041 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1043 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1044 this.castleFlags
[oppCol
][flagIdx
] = false;
1049 // After move is undo-ed *and flags resetted*, un-update other variables
1050 // TODO: more symmetry, by storing flags increment in move (?!)
1051 unupdateVariables(move) {
1052 // (Potentially) Reset king position
1053 const c
= this.getColor(move.start
.x
, move.start
.y
);
1054 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1055 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1060 // if (!this.states) this.states = [];
1061 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1062 // this.states.push(stateFen);
1064 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1065 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1066 V
.PlayOnBoard(this.board
, move);
1067 this.turn
= V
.GetOppCol(this.turn
);
1069 this.updateVariables(move);
1073 if (V
.HasEnpassant
) this.epSquares
.pop();
1074 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1075 V
.UndoOnBoard(this.board
, move);
1076 this.turn
= V
.GetOppCol(this.turn
);
1078 this.unupdateVariables(move);
1081 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1082 // if (stateFen != this.states[this.states.length-1]) debugger;
1083 // this.states.pop();
1089 // What is the score ? (Interesting if game is over)
1091 if (this.atLeastOneMove())
1095 const color
= this.turn
;
1096 // No valid move: stalemate or checkmate?
1097 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1100 return color
== "w" ? "0-1" : "1-0";
1107 static get VALUES() {
1118 // "Checkmate" (unreachable eval)
1119 static get INFINITY() {
1123 // At this value or above, the game is over
1124 static get THRESHOLD_MATE() {
1128 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1129 static get SEARCH_DEPTH() {
1134 const maxeval
= V
.INFINITY
;
1135 const color
= this.turn
;
1136 let moves1
= this.getAllValidMoves();
1138 if (moves1
.length
== 0)
1139 // TODO: this situation should not happen
1142 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1143 for (let i
= 0; i
< moves1
.length
; i
++) {
1144 if (V
.SEARCH_DEPTH
== 1) {
1145 moves1
[i
].eval
= this.evalPosition();
1148 // Initial self evaluation is very low: "I'm checkmated"
1149 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1150 this.play(moves1
[i
]);
1151 const score1
= this.getCurrentScore();
1152 let eval2
= undefined;
1153 if (score1
== "*") {
1154 // Initial enemy evaluation is very low too, for him
1155 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1156 // Second half-move:
1157 let moves2
= this.getAllValidMoves();
1158 for (let j
= 0; j
< moves2
.length
; j
++) {
1159 this.play(moves2
[j
]);
1160 const score2
= this.getCurrentScore();
1161 let evalPos
= 0; //1/2 value
1164 evalPos
= this.evalPosition();
1174 (color
== "w" && evalPos
< eval2
) ||
1175 (color
== "b" && evalPos
> eval2
)
1179 this.undo(moves2
[j
]);
1181 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1183 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1184 (color
== "b" && eval2
< moves1
[i
].eval
)
1186 moves1
[i
].eval
= eval2
;
1188 this.undo(moves1
[i
]);
1190 moves1
.sort((a
, b
) => {
1191 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1193 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1195 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1196 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1197 for (let i
= 0; i
< moves1
.length
; i
++) {
1198 this.play(moves1
[i
]);
1199 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1201 0.1 * moves1
[i
].eval
+
1202 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1203 this.undo(moves1
[i
]);
1205 moves1
.sort((a
, b
) => {
1206 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1210 let candidates
= [0];
1211 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1213 return moves1
[candidates
[randInt(candidates
.length
)]];
1216 alphabeta(depth
, alpha
, beta
) {
1217 const maxeval
= V
.INFINITY
;
1218 const color
= this.turn
;
1219 const score
= this.getCurrentScore();
1221 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1222 if (depth
== 0) return this.evalPosition();
1223 const moves
= this.getAllValidMoves();
1224 let v
= color
== "w" ? -maxeval : maxeval
;
1226 for (let i
= 0; i
< moves
.length
; i
++) {
1227 this.play(moves
[i
]);
1228 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1229 this.undo(moves
[i
]);
1230 alpha
= Math
.max(alpha
, v
);
1231 if (alpha
>= beta
) break; //beta cutoff
1236 for (let i
= 0; i
< moves
.length
; i
++) {
1237 this.play(moves
[i
]);
1238 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1239 this.undo(moves
[i
]);
1240 beta
= Math
.min(beta
, v
);
1241 if (alpha
>= beta
) break; //alpha cutoff
1249 // Just count material for now
1250 for (let i
= 0; i
< V
.size
.x
; i
++) {
1251 for (let j
= 0; j
< V
.size
.y
; j
++) {
1252 if (this.board
[i
][j
] != V
.EMPTY
) {
1253 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1254 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1261 /////////////////////////
1262 // MOVES + GAME NOTATION
1263 /////////////////////////
1265 // Context: just before move is played, turn hasn't changed
1266 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1268 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1270 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1272 // Translate final square
1273 const finalSquare
= V
.CoordsToSquare(move.end
);
1275 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1276 if (piece
== V
.PAWN
) {
1279 if (move.vanish
.length
> move.appear
.length
) {
1281 const startColumn
= V
.CoordToColumn(move.start
.y
);
1282 notation
= startColumn
+ "x" + finalSquare
;
1284 else notation
= finalSquare
;
1285 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1287 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1292 piece
.toUpperCase() +
1293 (move.vanish
.length
> move.appear
.length
? "x" : "") +