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() {
41 static get HasCastle() {
45 // Pawns specifications
46 static get PawnSpecs() {
48 directions: { 'w': -1, 'b': 1 },
50 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
52 captureBackward: false,
57 // En-passant captures need a stack of squares:
58 static get HasEnpassant() {
62 // Some variants cannot have analyse mode
63 static get CanAnalyze() {
66 // Patch: issues with javascript OOP, objects can't access static fields.
71 // Some variants show incomplete information,
72 // and thus show only a partial moves list or no list at all.
73 static get ShowMoves() {
80 // Some variants always show the same orientation
81 static get CanFlip() {
88 static get IMAGE_EXTENSION() {
89 // All pieces should be in the SVG format
93 // Turn "wb" into "B" (for FEN)
95 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
98 // Turn "p" into "bp" (for board)
100 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
103 // Check if FEN describes a board situation correctly
104 static IsGoodFen(fen
) {
105 const fenParsed
= V
.ParseFen(fen
);
107 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
109 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
110 // 3) Check moves count
111 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
114 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
116 // 5) Check enpassant
119 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
126 // Is position part of the FEN a priori correct?
127 static IsGoodPosition(position
) {
128 if (position
.length
== 0) return false;
129 const rows
= position
.split("/");
130 if (rows
.length
!= V
.size
.x
) return false;
132 for (let row
of rows
) {
134 for (let i
= 0; i
< row
.length
; i
++) {
135 if (['K','k'].includes(row
[i
]))
136 kings
[row
[i
]] = true;
137 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
139 const num
= parseInt(row
[i
]);
140 if (isNaN(num
)) return false;
144 if (sumElts
!= V
.size
.y
) return false;
146 // Both kings should be on board:
147 if (Object
.keys(kings
).length
!= 2)
153 static IsGoodTurn(turn
) {
154 return ["w", "b"].includes(turn
);
158 static IsGoodFlags(flags
) {
159 // NOTE: a little too permissive to work with more variants
160 return !!flags
.match(/^[a-z]{4,4}$/);
163 static IsGoodEnpassant(enpassant
) {
164 if (enpassant
!= "-") {
165 const ep
= V
.SquareToCoords(enpassant
);
166 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
171 // 3 --> d (column number to letter)
172 static CoordToColumn(colnum
) {
173 return String
.fromCharCode(97 + colnum
);
176 // d --> 3 (column letter to number)
177 static ColumnToCoord(column
) {
178 return column
.charCodeAt(0) - 97;
182 static SquareToCoords(sq
) {
184 // NOTE: column is always one char => max 26 columns
185 // row is counted from black side => subtraction
186 x: V
.size
.x
- parseInt(sq
.substr(1)),
187 y: sq
[0].charCodeAt() - 97
192 static CoordsToSquare(coords
) {
193 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
198 return b
; //usual pieces in pieces/ folder
201 // Path to promotion pieces (usually the same)
203 return this.getPpath(b
);
206 // Aggregates flags into one object
208 return this.castleFlags
;
212 disaggregateFlags(flags
) {
213 this.castleFlags
= flags
;
216 // En-passant square, if any
217 getEpSquare(moveOrSquare
) {
218 if (!moveOrSquare
) return undefined;
219 if (typeof moveOrSquare
=== "string") {
220 const square
= moveOrSquare
;
221 if (square
== "-") return undefined;
222 return V
.SquareToCoords(square
);
224 // Argument is a move:
225 const move = moveOrSquare
;
226 const s
= move.start
,
229 Math
.abs(s
.x
- e
.x
) == 2 &&
231 move.appear
[0].p
== V
.PAWN
238 return undefined; //default
241 // Can thing on square1 take thing on square2
242 canTake([x1
, y1
], [x2
, y2
]) {
243 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
246 // Is (x,y) on the chessboard?
247 static OnBoard(x
, y
) {
248 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
251 // Used in interface: 'side' arg == player color
252 canIplay(side
, [x
, y
]) {
253 return this.turn
== side
&& this.getColor(x
, y
) == side
;
256 // On which squares is color under check ? (for interface)
257 getCheckSquares(color
) {
259 this.underCheck(color
)
260 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
268 // Setup the initial random (asymmetric) position
269 static GenRandInitFen(randomness
) {
272 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
274 let pieces
= { w: new Array(8), b: new Array(8) };
276 // Shuffle pieces on first (and last rank if randomness == 2)
277 for (let c
of ["w", "b"]) {
278 if (c
== 'b' && randomness
== 1) {
279 pieces
['b'] = pieces
['w'];
284 let positions
= ArrayFun
.range(8);
286 // Get random squares for bishops
287 let randIndex
= 2 * randInt(4);
288 const bishop1Pos
= positions
[randIndex
];
289 // The second bishop must be on a square of different color
290 let randIndex_tmp
= 2 * randInt(4) + 1;
291 const bishop2Pos
= positions
[randIndex_tmp
];
292 // Remove chosen squares
293 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
294 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
296 // Get random squares for knights
297 randIndex
= randInt(6);
298 const knight1Pos
= positions
[randIndex
];
299 positions
.splice(randIndex
, 1);
300 randIndex
= randInt(5);
301 const knight2Pos
= positions
[randIndex
];
302 positions
.splice(randIndex
, 1);
304 // Get random square for queen
305 randIndex
= randInt(4);
306 const queenPos
= positions
[randIndex
];
307 positions
.splice(randIndex
, 1);
309 // Rooks and king positions are now fixed,
310 // because of the ordering rook-king-rook
311 const rook1Pos
= positions
[0];
312 const kingPos
= positions
[1];
313 const rook2Pos
= positions
[2];
315 // Finally put the shuffled pieces in the board array
316 pieces
[c
][rook1Pos
] = "r";
317 pieces
[c
][knight1Pos
] = "n";
318 pieces
[c
][bishop1Pos
] = "b";
319 pieces
[c
][queenPos
] = "q";
320 pieces
[c
][kingPos
] = "k";
321 pieces
[c
][bishop2Pos
] = "b";
322 pieces
[c
][knight2Pos
] = "n";
323 pieces
[c
][rook2Pos
] = "r";
324 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
326 // Add turn + flags + enpassant
328 pieces
["b"].join("") +
329 "/pppppppp/8/8/8/8/PPPPPPPP/" +
330 pieces
["w"].join("").toUpperCase() +
331 " w 0 " + flags
+ " -"
335 // "Parse" FEN: just return untransformed string data
336 static ParseFen(fen
) {
337 const fenParts
= fen
.split(" ");
339 position: fenParts
[0],
341 movesCount: fenParts
[2]
344 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
345 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
349 // Return current fen (game state)
352 this.getBaseFen() + " " +
353 this.getTurnFen() + " " +
355 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
356 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
361 // Omit movesCount, only variable allowed to differ
363 this.getBaseFen() + "_" +
365 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
366 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
370 // Position part of the FEN string
373 for (let i
= 0; i
< V
.size
.x
; i
++) {
375 for (let j
= 0; j
< V
.size
.y
; j
++) {
376 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
378 if (emptyCount
> 0) {
379 // Add empty squares in-between
380 position
+= emptyCount
;
383 position
+= V
.board2fen(this.board
[i
][j
]);
386 if (emptyCount
> 0) {
388 position
+= emptyCount
;
390 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
399 // Flags part of the FEN string
403 for (let c
of ["w", "b"])
404 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
408 // Enpassant part of the FEN string
410 const L
= this.epSquares
.length
;
411 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
412 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
415 // Turn position fen into double array ["wb","wp","bk",...]
416 static GetBoard(position
) {
417 const rows
= position
.split("/");
418 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
419 for (let i
= 0; i
< rows
.length
; i
++) {
421 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
422 const character
= rows
[i
][indexInRow
];
423 const num
= parseInt(character
);
424 // If num is a number, just shift j:
425 if (!isNaN(num
)) j
+= num
;
426 // Else: something at position i,j
427 else board
[i
][j
++] = V
.fen2board(character
);
433 // Extract (relevant) flags from fen
435 // white a-castle, h-castle, black a-castle, h-castle
436 this.castleFlags
= { w: [true, true], b: [true, true] };
437 for (let i
= 0; i
< 4; i
++) {
438 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
439 V
.ColumnToCoord(fenflags
.charAt(i
));
446 // Fen string fully describes the game state
449 // In printDiagram() fen isn't supply because only getPpath() is used
450 // TODO: find a better solution!
452 const fenParsed
= V
.ParseFen(fen
);
453 this.board
= V
.GetBoard(fenParsed
.position
);
454 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
455 this.movesCount
= parseInt(fenParsed
.movesCount
);
456 this.setOtherVariables(fen
);
459 // Scan board for kings positions
461 this.INIT_COL_KING
= { w: -1, b: -1 };
462 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
463 const fenRows
= V
.ParseFen(fen
).position
.split("/");
464 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
465 for (let i
= 0; i
< fenRows
.length
; i
++) {
466 let k
= 0; //column index on board
467 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
468 switch (fenRows
[i
].charAt(j
)) {
470 this.kingPos
["b"] = [i
, k
];
471 this.INIT_COL_KING
["b"] = k
;
474 this.kingPos
["w"] = [i
, k
];
475 this.INIT_COL_KING
["w"] = k
;
478 const num
= parseInt(fenRows
[i
].charAt(j
));
479 if (!isNaN(num
)) k
+= num
- 1;
487 // Some additional variables from FEN (variant dependant)
488 setOtherVariables(fen
) {
489 // Set flags and enpassant:
490 const parsedFen
= V
.ParseFen(fen
);
491 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
492 if (V
.HasEnpassant
) {
494 parsedFen
.enpassant
!= "-"
495 ? this.getEpSquare(parsedFen
.enpassant
)
497 this.epSquares
= [epSq
];
499 // Search for kings positions:
503 /////////////////////
507 return { x: 8, y: 8 };
510 // Color of thing on square (i,j). 'undefined' if square is empty
512 return this.board
[i
][j
].charAt(0);
515 // Piece type on square (i,j). 'undefined' if square is empty
517 return this.board
[i
][j
].charAt(1);
520 // Get opponent color
521 static GetOppCol(color
) {
522 return color
== "w" ? "b" : "w";
525 // Pieces codes (for a clearer code)
532 static get KNIGHT() {
535 static get BISHOP() {
546 static get PIECES() {
547 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
555 // Some pieces movements
586 // All possible moves from selected square
587 getPotentialMovesFrom([x
, y
]) {
588 switch (this.getPiece(x
, y
)) {
590 return this.getPotentialPawnMoves([x
, y
]);
592 return this.getPotentialRookMoves([x
, y
]);
594 return this.getPotentialKnightMoves([x
, y
]);
596 return this.getPotentialBishopMoves([x
, y
]);
598 return this.getPotentialQueenMoves([x
, y
]);
600 return this.getPotentialKingMoves([x
, y
]);
602 return []; //never reached
605 // Build a regular move from its initial and destination squares.
606 // tr: transformation
607 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
613 c: tr
? tr
.c : this.getColor(sx
, sy
),
614 p: tr
? tr
.p : this.getPiece(sx
, sy
)
621 c: this.getColor(sx
, sy
),
622 p: this.getPiece(sx
, sy
)
627 // The opponent piece disappears if we take it
628 if (this.board
[ex
][ey
] != V
.EMPTY
) {
633 c: this.getColor(ex
, ey
),
634 p: this.getPiece(ex
, ey
)
642 // Generic method to find possible moves of non-pawn pieces:
643 // "sliding or jumping"
644 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
646 outerLoop: for (let step
of steps
) {
649 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
650 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
651 if (oneStep
) continue outerLoop
;
655 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
656 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
661 // Special case of en-passant captures: treated separately
662 getEnpassantCaptures([x
, y
], shiftX
) {
663 const Lep
= this.epSquares
.length
;
664 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
665 let enpassantMove
= null;
668 epSquare
.x
== x
+ shiftX
&&
669 Math
.abs(epSquare
.y
- y
) == 1
671 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
672 enpassantMove
.vanish
.push({
676 c: this.getColor(x
, epSquare
.y
)
679 return !!enpassantMove
? [enpassantMove
] : [];
682 // What are the pawn moves from square x,y ?
683 getPotentialPawnMoves([x
, y
], promotions
) {
684 const color
= this.turn
;
685 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
686 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
687 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
688 const startRank
= color
== "w" ? sizeX
- 2 : 1;
689 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
691 // Consider all potential promotions:
692 const addMoves
= ([x1
, y1
], [x2
, y2
], moves
) => {
693 let finalPieces
= [V
.PAWN
];
694 if (x2
== lastRank
) {
695 // promotions arg: special override for Hiddenqueen variant
696 if (!!promotions
) finalPieces
= promotions
;
697 else if (!!V
.PawnSpecs
.promotions
)
698 finalPieces
= V
.PawnSpecs
.promotions
;
700 for (let piece
of finalPieces
) {
702 this.getBasicMove([x1
, y1
], [x2
, y2
], {
710 // Pawn movements in shiftX direction:
711 const getPawnMoves
= (shiftX
) => {
713 // NOTE: next condition is generally true (no pawn on last rank)
714 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
715 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
716 // One square forward
717 addMoves([x
, y
], [x
+ shiftX
, y
], moves
);
718 // Next condition because pawns on 1st rank can generally jump
720 V
.PawnSpecs
.twoSquares
&&
721 [startRank
, firstRank
].includes(x
) &&
722 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
725 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
729 if (V
.PawnSpecs
.canCapture
) {
730 for (let shiftY
of [-1, 1]) {
736 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
737 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
739 addMoves([x
, y
], [x
+ shiftX
, y
+ shiftY
], moves
);
742 V
.PawnSpecs
.captureBackward
&&
743 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
744 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
745 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
747 addMoves([x
, y
], [x
+ shiftX
, y
+ shiftY
], moves
);
756 let pMoves
= getPawnMoves(pawnShiftX
);
757 if (V
.PawnSpecs
.bidirectional
)
758 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
760 if (V
.HasEnpassant
) {
761 // NOTE: backward en-passant captures are not considered
762 // because no rules define them (for now).
763 Array
.prototype.push
.apply(
765 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
772 // What are the rook moves from square x,y ?
773 getPotentialRookMoves(sq
) {
774 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
777 // What are the knight moves from square x,y ?
778 getPotentialKnightMoves(sq
) {
779 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
782 // What are the bishop moves from square x,y ?
783 getPotentialBishopMoves(sq
) {
784 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
787 // What are the queen moves from square x,y ?
788 getPotentialQueenMoves(sq
) {
789 return this.getSlideNJumpMoves(
791 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
795 // What are the king moves from square x,y ?
796 getPotentialKingMoves(sq
) {
797 // Initialize with normal moves
798 let moves
= this.getSlideNJumpMoves(
800 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
803 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
807 getCastleMoves([x
, y
]) {
808 const c
= this.getColor(x
, y
);
809 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
810 return []; //x isn't first rank, or king has moved (shortcut)
813 const oppCol
= V
.GetOppCol(c
);
817 const finalSquares
= [
819 [V
.size
.y
- 2, V
.size
.y
- 3]
824 castleSide
++ //large, then small
826 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
827 // If this code is reached, rooks and king are on initial position
829 const rookPos
= this.castleFlags
[c
][castleSide
];
830 if (this.getColor(x
, rookPos
) != c
)
831 // Rook is here but changed color (see Benedict)
834 // Nothing on the path of the king ? (and no checks)
835 const finDist
= finalSquares
[castleSide
][0] - y
;
836 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
840 this.isAttacked([x
, i
], oppCol
) ||
841 (this.board
[x
][i
] != V
.EMPTY
&&
842 // NOTE: next check is enough, because of chessboard constraints
843 (this.getColor(x
, i
) != c
||
844 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
846 continue castlingCheck
;
849 } while (i
!= finalSquares
[castleSide
][0]);
851 // Nothing on the path to the rook?
852 step
= castleSide
== 0 ? -1 : 1;
853 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
854 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
857 // Nothing on final squares, except maybe king and castling rook?
858 for (i
= 0; i
< 2; i
++) {
860 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
861 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
862 finalSquares
[castleSide
][i
] != rookPos
864 continue castlingCheck
;
868 // If this code is reached, castle is valid
872 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
873 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
876 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
877 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
880 Math
.abs(y
- rookPos
) <= 2
881 ? { x: x
, y: rookPos
}
882 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
893 // For the interface: possible moves for the current turn from square sq
894 getPossibleMovesFrom(sq
) {
895 return this.filterValid(this.getPotentialMovesFrom(sq
));
898 // TODO: promotions (into R,B,N,Q) should be filtered only once
900 if (moves
.length
== 0) return [];
901 const color
= this.turn
;
902 return moves
.filter(m
=> {
904 const res
= !this.underCheck(color
);
910 // Search for all valid moves considering current turn
911 // (for engine and game end)
913 const color
= this.turn
;
914 let potentialMoves
= [];
915 for (let i
= 0; i
< V
.size
.x
; i
++) {
916 for (let j
= 0; j
< V
.size
.y
; j
++) {
917 if (this.getColor(i
, j
) == color
) {
918 Array
.prototype.push
.apply(
920 this.getPotentialMovesFrom([i
, j
])
925 return this.filterValid(potentialMoves
);
928 // Stop at the first move found
930 const color
= this.turn
;
931 for (let i
= 0; i
< V
.size
.x
; i
++) {
932 for (let j
= 0; j
< V
.size
.y
; j
++) {
933 if (this.getColor(i
, j
) == color
) {
934 const moves
= this.getPotentialMovesFrom([i
, j
]);
935 if (moves
.length
> 0) {
936 for (let k
= 0; k
< moves
.length
; k
++) {
937 if (this.filterValid([moves
[k
]]).length
> 0) return true;
946 // Check if pieces of given color are attacking (king) on square x,y
947 isAttacked(sq
, color
) {
949 this.isAttackedByPawn(sq
, color
) ||
950 this.isAttackedByRook(sq
, color
) ||
951 this.isAttackedByKnight(sq
, color
) ||
952 this.isAttackedByBishop(sq
, color
) ||
953 this.isAttackedByQueen(sq
, color
) ||
954 this.isAttackedByKing(sq
, color
)
958 // Generic method for non-pawn pieces ("sliding or jumping"):
959 // is x,y attacked by a piece of given color ?
960 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
961 for (let step
of steps
) {
962 let rx
= x
+ step
[0],
964 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
970 this.getPiece(rx
, ry
) == piece
&&
971 this.getColor(rx
, ry
) == color
979 // Is square x,y attacked by 'color' pawns ?
980 isAttackedByPawn([x
, y
], color
) {
981 const pawnShift
= (color
== "w" ? 1 : -1);
982 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
983 for (let i
of [-1, 1]) {
987 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
988 this.getColor(x
+ pawnShift
, y
+ i
) == color
997 // Is square x,y attacked by 'color' rooks ?
998 isAttackedByRook(sq
, color
) {
999 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1002 // Is square x,y attacked by 'color' knights ?
1003 isAttackedByKnight(sq
, color
) {
1004 return this.isAttackedBySlideNJump(
1013 // Is square x,y attacked by 'color' bishops ?
1014 isAttackedByBishop(sq
, color
) {
1015 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1018 // Is square x,y attacked by 'color' queens ?
1019 isAttackedByQueen(sq
, color
) {
1020 return this.isAttackedBySlideNJump(
1024 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1028 // Is square x,y attacked by 'color' king(s) ?
1029 isAttackedByKing(sq
, color
) {
1030 return this.isAttackedBySlideNJump(
1034 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1039 // Is color under check after his move ?
1041 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
1047 // Apply a move on board
1048 static PlayOnBoard(board
, move) {
1049 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1050 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1052 // Un-apply the played move
1053 static UndoOnBoard(board
, move) {
1054 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1055 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1062 // if (!this.states) this.states = [];
1063 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1064 // this.states.push(stateFen);
1067 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1068 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1069 V
.PlayOnBoard(this.board
, move);
1070 this.turn
= V
.GetOppCol(this.turn
);
1072 this.postPlay(move);
1075 // After move is played, update variables + flags
1077 const c
= V
.GetOppCol(this.turn
);
1078 let piece
= undefined;
1079 if (move.vanish
.length
>= 1)
1080 // Usual case, something is moved
1081 piece
= move.vanish
[0].p
;
1083 // Crazyhouse-like variants
1084 piece
= move.appear
[0].p
;
1085 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1087 // Update king position + flags
1088 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1089 this.kingPos
[c
][0] = move.appear
[0].x
;
1090 this.kingPos
[c
][1] = move.appear
[0].y
;
1091 if (V
.HasCastle
) this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1095 // Update castling flags if rooks are moved
1096 const oppCol
= V
.GetOppCol(c
);
1097 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1099 move.start
.x
== firstRank
&& //our rook moves?
1100 this.castleFlags
[c
].includes(move.start
.y
)
1102 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1103 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1105 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1106 this.castleFlags
[oppCol
].includes(move.end
.y
)
1108 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1109 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1118 if (V
.HasEnpassant
) this.epSquares
.pop();
1119 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1120 V
.UndoOnBoard(this.board
, move);
1121 this.turn
= V
.GetOppCol(this.turn
);
1123 this.postUndo(move);
1126 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1127 // if (stateFen != this.states[this.states.length-1]) debugger;
1128 // this.states.pop();
1131 // After move is undo-ed *and flags resetted*, un-update other variables
1132 // TODO: more symmetry, by storing flags increment in move (?!)
1134 // (Potentially) Reset king position
1135 const c
= this.getColor(move.start
.x
, move.start
.y
);
1136 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1137 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1143 // What is the score ? (Interesting if game is over)
1145 if (this.atLeastOneMove())
1149 const color
= this.turn
;
1150 // No valid move: stalemate or checkmate?
1151 if (!this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
)))
1154 return (color
== "w" ? "0-1" : "1-0");
1161 static get VALUES() {
1172 // "Checkmate" (unreachable eval)
1173 static get INFINITY() {
1177 // At this value or above, the game is over
1178 static get THRESHOLD_MATE() {
1182 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1183 static get SEARCH_DEPTH() {
1188 const maxeval
= V
.INFINITY
;
1189 const color
= this.turn
;
1190 let moves1
= this.getAllValidMoves();
1192 if (moves1
.length
== 0)
1193 // TODO: this situation should not happen
1196 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1197 for (let i
= 0; i
< moves1
.length
; i
++) {
1198 this.play(moves1
[i
]);
1199 const score1
= this.getCurrentScore();
1200 if (score1
!= "*") {
1204 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1206 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1207 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1208 this.undo(moves1
[i
]);
1211 // Initial self evaluation is very low: "I'm checkmated"
1212 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1213 // Initial enemy evaluation is very low too, for him
1214 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1215 // Second half-move:
1216 let moves2
= this.getAllValidMoves();
1217 for (let j
= 0; j
< moves2
.length
; j
++) {
1218 this.play(moves2
[j
]);
1219 const score2
= this.getCurrentScore();
1220 let evalPos
= 0; //1/2 value
1223 evalPos
= this.evalPosition();
1233 (color
== "w" && evalPos
< eval2
) ||
1234 (color
== "b" && evalPos
> eval2
)
1238 this.undo(moves2
[j
]);
1241 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1242 (color
== "b" && eval2
< moves1
[i
].eval
)
1244 moves1
[i
].eval
= eval2
;
1246 this.undo(moves1
[i
]);
1248 moves1
.sort((a
, b
) => {
1249 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1251 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1253 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1254 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1255 for (let i
= 0; i
< moves1
.length
; i
++) {
1256 this.play(moves1
[i
]);
1257 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1259 0.1 * moves1
[i
].eval
+
1260 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1261 this.undo(moves1
[i
]);
1263 moves1
.sort((a
, b
) => {
1264 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1268 let candidates
= [0];
1269 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1271 return moves1
[candidates
[randInt(candidates
.length
)]];
1274 alphabeta(depth
, alpha
, beta
) {
1275 const maxeval
= V
.INFINITY
;
1276 const color
= this.turn
;
1277 const score
= this.getCurrentScore();
1279 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1280 if (depth
== 0) return this.evalPosition();
1281 const moves
= this.getAllValidMoves();
1282 let v
= color
== "w" ? -maxeval : maxeval
;
1284 for (let i
= 0; i
< moves
.length
; i
++) {
1285 this.play(moves
[i
]);
1286 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1287 this.undo(moves
[i
]);
1288 alpha
= Math
.max(alpha
, v
);
1289 if (alpha
>= beta
) break; //beta cutoff
1294 for (let i
= 0; i
< moves
.length
; i
++) {
1295 this.play(moves
[i
]);
1296 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1297 this.undo(moves
[i
]);
1298 beta
= Math
.min(beta
, v
);
1299 if (alpha
>= beta
) break; //alpha cutoff
1307 // Just count material for now
1308 for (let i
= 0; i
< V
.size
.x
; i
++) {
1309 for (let j
= 0; j
< V
.size
.y
; j
++) {
1310 if (this.board
[i
][j
] != V
.EMPTY
) {
1311 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1312 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1319 /////////////////////////
1320 // MOVES + GAME NOTATION
1321 /////////////////////////
1323 // Context: just before move is played, turn hasn't changed
1324 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1326 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1328 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1330 // Translate final square
1331 const finalSquare
= V
.CoordsToSquare(move.end
);
1333 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1334 if (piece
== V
.PAWN
) {
1337 if (move.vanish
.length
> move.appear
.length
) {
1339 const startColumn
= V
.CoordToColumn(move.start
.y
);
1340 notation
= startColumn
+ "x" + finalSquare
;
1342 else notation
= finalSquare
;
1343 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1345 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1350 piece
.toUpperCase() +
1351 (move.vanish
.length
> move.appear
.length
? "x" : "") +