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 (asymmetric) position
242 static GenRandInitFen(randomness
) {
245 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 1111 -";
247 let pieces
= { w: new Array(8), b: new Array(8) };
248 // Shuffle pieces on first (and last rank if randomness == 2)
249 for (let c
of ["w", "b"]) {
250 if (c
== 'b' && randomness
== 1) {
251 pieces
['b'] = pieces
['w'];
255 let positions
= ArrayFun
.range(8);
257 // Get random squares for bishops
258 let randIndex
= 2 * randInt(4);
259 const bishop1Pos
= positions
[randIndex
];
260 // The second bishop must be on a square of different color
261 let randIndex_tmp
= 2 * randInt(4) + 1;
262 const bishop2Pos
= positions
[randIndex_tmp
];
263 // Remove chosen squares
264 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
265 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
267 // Get random squares for knights
268 randIndex
= randInt(6);
269 const knight1Pos
= positions
[randIndex
];
270 positions
.splice(randIndex
, 1);
271 randIndex
= randInt(5);
272 const knight2Pos
= positions
[randIndex
];
273 positions
.splice(randIndex
, 1);
275 // Get random square for queen
276 randIndex
= randInt(4);
277 const queenPos
= positions
[randIndex
];
278 positions
.splice(randIndex
, 1);
280 // Rooks and king positions are now fixed,
281 // because of the ordering rook-king-rook
282 const rook1Pos
= positions
[0];
283 const kingPos
= positions
[1];
284 const rook2Pos
= positions
[2];
286 // Finally put the shuffled pieces in the board array
287 pieces
[c
][rook1Pos
] = "r";
288 pieces
[c
][knight1Pos
] = "n";
289 pieces
[c
][bishop1Pos
] = "b";
290 pieces
[c
][queenPos
] = "q";
291 pieces
[c
][kingPos
] = "k";
292 pieces
[c
][bishop2Pos
] = "b";
293 pieces
[c
][knight2Pos
] = "n";
294 pieces
[c
][rook2Pos
] = "r";
296 // Add turn + flags + enpassant
298 pieces
["b"].join("") +
299 "/pppppppp/8/8/8/8/PPPPPPPP/" +
300 pieces
["w"].join("").toUpperCase() +
305 // "Parse" FEN: just return untransformed string data
306 static ParseFen(fen
) {
307 const fenParts
= fen
.split(" ");
309 position: fenParts
[0],
311 movesCount: fenParts
[2]
314 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
315 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
319 // Return current fen (game state)
327 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
328 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
332 // Position part of the FEN string
335 for (let i
= 0; i
< V
.size
.x
; i
++) {
337 for (let j
= 0; j
< V
.size
.y
; j
++) {
338 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
340 if (emptyCount
> 0) {
341 // Add empty squares in-between
342 position
+= emptyCount
;
345 position
+= V
.board2fen(this.board
[i
][j
]);
348 if (emptyCount
> 0) {
350 position
+= emptyCount
;
352 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
361 // Flags part of the FEN string
364 // Add castling flags
365 for (let i
of ["w", "b"]) {
366 for (let j
= 0; j
< 2; j
++) flags
+= this.castleFlags
[i
][j
] ? "1" : "0";
371 // Enpassant part of the FEN string
373 const L
= this.epSquares
.length
;
374 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
375 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
378 // Turn position fen into double array ["wb","wp","bk",...]
379 static GetBoard(position
) {
380 const rows
= position
.split("/");
381 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
382 for (let i
= 0; i
< rows
.length
; i
++) {
384 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
385 const character
= rows
[i
][indexInRow
];
386 const num
= parseInt(character
);
387 // If num is a number, just shift j:
388 if (!isNaN(num
)) j
+= num
;
389 // Else: something at position i,j
390 else board
[i
][j
++] = V
.fen2board(character
);
396 // Extract (relevant) flags from fen
398 // white a-castle, h-castle, black a-castle, h-castle
399 this.castleFlags
= { w: [true, true], b: [true, true] };
400 for (let i
= 0; i
< 4; i
++)
401 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] = fenflags
.charAt(i
) == "1";
407 // Fen string fully describes the game state
410 // In printDiagram() fen isn't supply because only getPpath() is used
411 // TODO: find a better solution!
413 const fenParsed
= V
.ParseFen(fen
);
414 this.board
= V
.GetBoard(fenParsed
.position
);
415 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
416 this.movesCount
= parseInt(fenParsed
.movesCount
);
417 this.setOtherVariables(fen
);
420 // Scan board for kings and rooks positions
421 scanKingsRooks(fen
) {
422 this.INIT_COL_KING
= { w: -1, b: -1 };
423 this.INIT_COL_ROOK
= { w: [-1, -1], b: [-1, -1] };
424 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
425 const fenRows
= V
.ParseFen(fen
).position
.split("/");
426 for (let i
= 0; i
< fenRows
.length
; i
++) {
427 let k
= 0; //column index on board
428 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
429 switch (fenRows
[i
].charAt(j
)) {
431 this.kingPos
["b"] = [i
, k
];
432 this.INIT_COL_KING
["b"] = k
;
435 this.kingPos
["w"] = [i
, k
];
436 this.INIT_COL_KING
["w"] = k
;
439 if (this.INIT_COL_ROOK
["b"][0] < 0) this.INIT_COL_ROOK
["b"][0] = k
;
440 else this.INIT_COL_ROOK
["b"][1] = k
;
443 if (this.INIT_COL_ROOK
["w"][0] < 0) this.INIT_COL_ROOK
["w"][0] = k
;
444 else this.INIT_COL_ROOK
["w"][1] = k
;
447 const num
= parseInt(fenRows
[i
].charAt(j
));
448 if (!isNaN(num
)) k
+= num
- 1;
456 // Some additional variables from FEN (variant dependant)
457 setOtherVariables(fen
) {
458 // Set flags and enpassant:
459 const parsedFen
= V
.ParseFen(fen
);
460 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
461 if (V
.HasEnpassant
) {
463 parsedFen
.enpassant
!= "-"
464 ? this.getEpSquare(parsedFen
.enpassant
)
466 this.epSquares
= [epSq
];
468 // Search for king and rooks positions:
469 this.scanKingsRooks(fen
);
472 /////////////////////
476 return { x: 8, y: 8 };
479 // Color of thing on square (i,j). 'undefined' if square is empty
481 return this.board
[i
][j
].charAt(0);
484 // Piece type on square (i,j). 'undefined' if square is empty
486 return this.board
[i
][j
].charAt(1);
489 // Get opponent color
490 static GetOppCol(color
) {
491 return color
== "w" ? "b" : "w";
494 // Pieces codes (for a clearer code)
501 static get KNIGHT() {
504 static get BISHOP() {
515 static get PIECES() {
516 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
524 // Some pieces movements
555 // All possible moves from selected square
556 getPotentialMovesFrom([x
, y
]) {
557 switch (this.getPiece(x
, y
)) {
559 return this.getPotentialPawnMoves([x
, y
]);
561 return this.getPotentialRookMoves([x
, y
]);
563 return this.getPotentialKnightMoves([x
, y
]);
565 return this.getPotentialBishopMoves([x
, y
]);
567 return this.getPotentialQueenMoves([x
, y
]);
569 return this.getPotentialKingMoves([x
, y
]);
571 return []; //never reached
574 // Build a regular move from its initial and destination squares.
575 // tr: transformation
576 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
582 c: tr
? tr
.c : this.getColor(sx
, sy
),
583 p: tr
? tr
.p : this.getPiece(sx
, sy
)
590 c: this.getColor(sx
, sy
),
591 p: this.getPiece(sx
, sy
)
596 // The opponent piece disappears if we take it
597 if (this.board
[ex
][ey
] != V
.EMPTY
) {
602 c: this.getColor(ex
, ey
),
603 p: this.getPiece(ex
, ey
)
611 // Generic method to find possible moves of non-pawn pieces:
612 // "sliding or jumping"
613 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
615 outerLoop: for (let step
of steps
) {
618 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
619 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
620 if (oneStep
) continue outerLoop
;
624 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
625 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
630 // What are the pawn moves from square x,y ?
631 getPotentialPawnMoves([x
, y
]) {
632 const color
= this.turn
;
634 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
635 const shiftX
= color
== "w" ? -1 : 1;
636 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
637 const startRank
= color
== "w" ? sizeX
- 2 : 1;
638 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
639 const pawnColor
= this.getColor(x
, y
); //can be different for checkered
641 // NOTE: next condition is generally true (no pawn on last rank)
642 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
644 x
+ shiftX
== lastRank
645 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
647 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
648 // One square forward
649 for (let piece
of finalPieces
) {
651 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
657 // Next condition because pawns on 1st rank can generally jump
659 [startRank
, firstRank
].includes(x
) &&
660 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
663 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
667 for (let shiftY
of [-1, 1]) {
670 y
+ shiftY
< sizeY
&&
671 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
672 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
674 for (let piece
of finalPieces
) {
676 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
686 if (V
.HasEnpassant
) {
688 const Lep
= this.epSquares
.length
;
689 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
692 epSquare
.x
== x
+ shiftX
&&
693 Math
.abs(epSquare
.y
- y
) == 1
695 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
696 enpassantMove
.vanish
.push({
700 c: this.getColor(x
, epSquare
.y
)
702 moves
.push(enpassantMove
);
709 // What are the rook moves from square x,y ?
710 getPotentialRookMoves(sq
) {
711 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
714 // What are the knight moves from square x,y ?
715 getPotentialKnightMoves(sq
) {
716 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
719 // What are the bishop moves from square x,y ?
720 getPotentialBishopMoves(sq
) {
721 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
724 // What are the queen moves from square x,y ?
725 getPotentialQueenMoves(sq
) {
726 return this.getSlideNJumpMoves(
728 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
732 // What are the king moves from square x,y ?
733 getPotentialKingMoves(sq
) {
734 // Initialize with normal moves
735 let moves
= this.getSlideNJumpMoves(
737 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
740 return moves
.concat(this.getCastleMoves(sq
));
743 getCastleMoves([x
, y
]) {
744 const c
= this.getColor(x
, y
);
745 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
746 return []; //x isn't first rank, or king has moved (shortcut)
749 const oppCol
= V
.GetOppCol(c
);
753 const finalSquares
= [
755 [V
.size
.y
- 2, V
.size
.y
- 3]
760 castleSide
++ //large, then small
762 if (!this.castleFlags
[c
][castleSide
]) continue;
763 // If this code is reached, rooks and king are on initial position
765 // Nothing on the path of the king ? (and no checks)
766 const finDist
= finalSquares
[castleSide
][0] - y
;
767 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
771 this.isAttacked([x
, i
], [oppCol
]) ||
772 (this.board
[x
][i
] != V
.EMPTY
&&
773 // NOTE: next check is enough, because of chessboard constraints
774 (this.getColor(x
, i
) != c
||
775 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
777 continue castlingCheck
;
780 } while (i
!= finalSquares
[castleSide
][0]);
782 // Nothing on the path to the rook?
783 step
= castleSide
== 0 ? -1 : 1;
784 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
) {
785 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
787 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
789 // Nothing on final squares, except maybe king and castling rook?
790 for (i
= 0; i
< 2; i
++) {
792 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
793 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
794 finalSquares
[castleSide
][i
] != rookPos
796 continue castlingCheck
;
800 // If this code is reached, castle is valid
804 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
805 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
808 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
809 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
812 Math
.abs(y
- rookPos
) <= 2
813 ? { x: x
, y: rookPos
}
814 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
825 // For the interface: possible moves for the current turn from square sq
826 getPossibleMovesFrom(sq
) {
827 return this.filterValid(this.getPotentialMovesFrom(sq
));
830 // TODO: promotions (into R,B,N,Q) should be filtered only once
832 if (moves
.length
== 0) return [];
833 const color
= this.turn
;
834 return moves
.filter(m
=> {
836 const res
= !this.underCheck(color
);
842 // Search for all valid moves considering current turn
843 // (for engine and game end)
845 const color
= this.turn
;
846 let potentialMoves
= [];
847 for (let i
= 0; i
< V
.size
.x
; i
++) {
848 for (let j
= 0; j
< V
.size
.y
; j
++) {
849 if (this.getColor(i
, j
) == color
) {
850 Array
.prototype.push
.apply(
852 this.getPotentialMovesFrom([i
, j
])
857 return this.filterValid(potentialMoves
);
860 // Stop at the first move found
862 const color
= this.turn
;
863 for (let i
= 0; i
< V
.size
.x
; i
++) {
864 for (let j
= 0; j
< V
.size
.y
; j
++) {
865 if (this.getColor(i
, j
) == color
) {
866 const moves
= this.getPotentialMovesFrom([i
, j
]);
867 if (moves
.length
> 0) {
868 for (let k
= 0; k
< moves
.length
; k
++) {
869 if (this.filterValid([moves
[k
]]).length
> 0) return true;
878 // Check if pieces of color in 'colors' are attacking (king) on square x,y
879 isAttacked(sq
, colors
) {
881 this.isAttackedByPawn(sq
, colors
) ||
882 this.isAttackedByRook(sq
, colors
) ||
883 this.isAttackedByKnight(sq
, colors
) ||
884 this.isAttackedByBishop(sq
, colors
) ||
885 this.isAttackedByQueen(sq
, colors
) ||
886 this.isAttackedByKing(sq
, colors
)
890 // Generic method for non-pawn pieces ("sliding or jumping"):
891 // is x,y attacked by a piece of color in array 'colors' ?
892 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
893 for (let step
of steps
) {
894 let rx
= x
+ step
[0],
896 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
902 this.getPiece(rx
, ry
) === piece
&&
903 colors
.includes(this.getColor(rx
, ry
))
911 // Is square x,y attacked by 'colors' pawns ?
912 isAttackedByPawn([x
, y
], colors
) {
913 for (let c
of colors
) {
914 const pawnShift
= c
== "w" ? 1 : -1;
915 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
916 for (let i
of [-1, 1]) {
920 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
921 this.getColor(x
+ pawnShift
, y
+ i
) == c
931 // Is square x,y attacked by 'colors' rooks ?
932 isAttackedByRook(sq
, colors
) {
933 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
936 // Is square x,y attacked by 'colors' knights ?
937 isAttackedByKnight(sq
, colors
) {
938 return this.isAttackedBySlideNJump(
947 // Is square x,y attacked by 'colors' bishops ?
948 isAttackedByBishop(sq
, colors
) {
949 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
952 // Is square x,y attacked by 'colors' queens ?
953 isAttackedByQueen(sq
, colors
) {
954 return this.isAttackedBySlideNJump(
958 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
962 // Is square x,y attacked by 'colors' king(s) ?
963 isAttackedByKing(sq
, colors
) {
964 return this.isAttackedBySlideNJump(
968 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
973 // Is color under check after his move ?
975 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
981 // Apply a move on board
982 static PlayOnBoard(board
, move) {
983 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
984 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
986 // Un-apply the played move
987 static UndoOnBoard(board
, move) {
988 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
989 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
992 // After move is played, update variables + flags
993 updateVariables(move) {
994 let piece
= undefined;
995 // TODO: update variables before move is played, and just use this.turn ?
996 // (doesn't work in general, think MarseilleChess)
998 if (move.vanish
.length
>= 1) {
999 // Usual case, something is moved
1000 piece
= move.vanish
[0].p
;
1001 c
= move.vanish
[0].c
;
1003 // Crazyhouse-like variants
1004 piece
= move.appear
[0].p
;
1005 c
= move.appear
[0].c
;
1007 if (!['w','b'].includes(c
)) {
1008 // Checkered, for example
1009 c
= V
.GetOppCol(this.turn
);
1011 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1013 // Update king position + flags
1014 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1015 this.kingPos
[c
][0] = move.appear
[0].x
;
1016 this.kingPos
[c
][1] = move.appear
[0].y
;
1017 if (V
.HasFlags
) this.castleFlags
[c
] = [false, false];
1021 // Update castling flags if rooks are moved
1022 const oppCol
= V
.GetOppCol(c
);
1023 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1025 move.start
.x
== firstRank
&& //our rook moves?
1026 this.INIT_COL_ROOK
[c
].includes(move.start
.y
)
1028 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
1029 this.castleFlags
[c
][flagIdx
] = false;
1031 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1032 this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
)
1034 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
1035 this.castleFlags
[oppCol
][flagIdx
] = false;
1040 // After move is undo-ed *and flags resetted*, un-update other variables
1041 // TODO: more symmetry, by storing flags increment in move (?!)
1042 unupdateVariables(move) {
1043 // (Potentially) Reset king position
1044 const c
= this.getColor(move.start
.x
, move.start
.y
);
1045 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1046 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1051 // if (!this.states) this.states = [];
1052 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1053 // this.states.push(stateFen);
1055 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1056 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1057 V
.PlayOnBoard(this.board
, move);
1058 this.turn
= V
.GetOppCol(this.turn
);
1060 this.updateVariables(move);
1064 if (V
.HasEnpassant
) this.epSquares
.pop();
1065 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1066 V
.UndoOnBoard(this.board
, move);
1067 this.turn
= V
.GetOppCol(this.turn
);
1069 this.unupdateVariables(move);
1072 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1073 // if (stateFen != this.states[this.states.length-1]) debugger;
1074 // this.states.pop();
1080 // What is the score ? (Interesting if game is over)
1082 if (this.atLeastOneMove())
1086 const color
= this.turn
;
1087 // No valid move: stalemate or checkmate?
1088 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1091 return color
== "w" ? "0-1" : "1-0";
1098 static get VALUES() {
1109 // "Checkmate" (unreachable eval)
1110 static get INFINITY() {
1114 // At this value or above, the game is over
1115 static get THRESHOLD_MATE() {
1119 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1120 static get SEARCH_DEPTH() {
1125 const maxeval
= V
.INFINITY
;
1126 const color
= this.turn
;
1127 // Some variants may show a bigger moves list to the human (Switching),
1128 // thus the argument "computer" below (which is generally ignored)
1129 let moves1
= this.getAllValidMoves();
1131 if (moves1
.length
== 0)
1132 // TODO: this situation should not happen
1135 // Rank moves using a min-max at depth 2
1136 for (let i
= 0; i
< moves1
.length
; i
++) {
1137 // Initial self evaluation is very low: "I'm checkmated"
1138 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1139 this.play(moves1
[i
]);
1140 const score1
= this.getCurrentScore();
1141 let eval2
= undefined;
1142 if (score1
== "*") {
1143 // Initial enemy evaluation is very low too, for him
1144 eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1145 // Second half-move:
1146 let moves2
= this.getAllValidMoves();
1147 for (let j
= 0; j
< moves2
.length
; j
++) {
1148 this.play(moves2
[j
]);
1149 const score2
= this.getCurrentScore();
1150 let evalPos
= 0; //1/2 value
1153 evalPos
= this.evalPosition();
1163 (color
== "w" && evalPos
< eval2
) ||
1164 (color
== "b" && evalPos
> eval2
)
1168 this.undo(moves2
[j
]);
1170 } else eval2
= score1
== "1/2" ? 0 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1172 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1173 (color
== "b" && eval2
< moves1
[i
].eval
)
1175 moves1
[i
].eval
= eval2
;
1177 this.undo(moves1
[i
]);
1179 moves1
.sort((a
, b
) => {
1180 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1182 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1184 let candidates
= [0]; //indices of candidates moves
1185 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1187 let currentBest
= moves1
[candidates
[randInt(candidates
.length
)]];
1189 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1190 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1191 // From here, depth >= 3: may take a while, so we control time
1192 const timeStart
= Date
.now();
1193 for (let i
= 0; i
< moves1
.length
; i
++) {
1194 if (Date
.now() - timeStart
>= 5000)
1195 //more than 5 seconds
1196 return currentBest
; //depth 2 at least
1197 this.play(moves1
[i
]);
1198 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1200 0.1 * moves1
[i
].eval
+
1201 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1202 this.undo(moves1
[i
]);
1204 moves1
.sort((a
, b
) => {
1205 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1207 } else return currentBest
;
1208 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
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" : "") +