d1348e71927b6bdf410659395bd5e3715f1f5372
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
31 // (from white player perspective)
32 export const ChessRules
= class ChessRules
{
36 // Some variants don't have flags:
37 static get HasFlags() {
42 static get HasCastle() {
46 // Pawns specifications
47 static get PawnSpecs() {
49 directions: { 'w': -1, 'b': 1 },
51 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
53 captureBackward: false,
58 // En-passant captures need a stack of squares:
59 static get HasEnpassant() {
63 // Some variants cannot have analyse mode
64 static get CanAnalyze() {
67 // Patch: issues with javascript OOP, objects can't access static fields.
72 // Some variants show incomplete information,
73 // and thus show only a partial moves list or no list at all.
74 static get ShowMoves() {
81 // Some variants always show the same orientation
82 static get CanFlip() {
89 static get IMAGE_EXTENSION() {
90 // All pieces should be in the SVG format
94 // Turn "wb" into "B" (for FEN)
96 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
99 // Turn "p" into "bp" (for board)
100 static fen2board(f
) {
101 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
104 // Check if FEN describes a board situation correctly
105 static IsGoodFen(fen
) {
106 const fenParsed
= V
.ParseFen(fen
);
108 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
110 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
111 // 3) Check moves count
112 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
115 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
117 // 5) Check enpassant
120 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
127 // Is position part of the FEN a priori correct?
128 static IsGoodPosition(position
) {
129 if (position
.length
== 0) return false;
130 const rows
= position
.split("/");
131 if (rows
.length
!= V
.size
.x
) return false;
132 let kings
= { "k": 0, "K": 0 };
133 for (let row
of rows
) {
135 for (let i
= 0; i
< row
.length
; i
++) {
136 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
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. Exactly one per color.
147 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
152 static IsGoodTurn(turn
) {
153 return ["w", "b"].includes(turn
);
157 static IsGoodFlags(flags
) {
158 // NOTE: a little too permissive to work with more variants
159 return !!flags
.match(/^[a-z]{4,4}$/);
162 static IsGoodEnpassant(enpassant
) {
163 if (enpassant
!= "-") {
164 const ep
= V
.SquareToCoords(enpassant
);
165 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
170 // 3 --> d (column number to letter)
171 static CoordToColumn(colnum
) {
172 return String
.fromCharCode(97 + colnum
);
175 // d --> 3 (column letter to number)
176 static ColumnToCoord(column
) {
177 return column
.charCodeAt(0) - 97;
181 static SquareToCoords(sq
) {
183 // NOTE: column is always one char => max 26 columns
184 // row is counted from black side => subtraction
185 x: V
.size
.x
- parseInt(sq
.substr(1)),
186 y: sq
[0].charCodeAt() - 97
191 static CoordsToSquare(coords
) {
192 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
195 // Path to pieces (standard ones in pieces/ folder)
200 // Path to promotion pieces (usually the same)
202 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
205 // Aggregates flags into one object
207 return this.castleFlags
;
211 disaggregateFlags(flags
) {
212 this.castleFlags
= flags
;
215 // En-passant square, if any
216 getEpSquare(moveOrSquare
) {
217 if (!moveOrSquare
) return undefined;
218 if (typeof moveOrSquare
=== "string") {
219 const square
= moveOrSquare
;
220 if (square
== "-") return undefined;
221 return V
.SquareToCoords(square
);
223 // Argument is a move:
224 const move = moveOrSquare
;
225 const s
= move.start
,
229 Math
.abs(s
.x
- e
.x
) == 2 &&
230 // Next conditions for variants like Atomic or Rifle, Recycle...
231 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
232 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
239 return undefined; //default
242 // Can thing on square1 take thing on square2
243 canTake([x1
, y1
], [x2
, y2
]) {
244 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
247 // Is (x,y) on the chessboard?
248 static OnBoard(x
, y
) {
249 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
252 // Used in interface: 'side' arg == player color
253 canIplay(side
, [x
, y
]) {
254 return this.turn
== side
&& this.getColor(x
, y
) == side
;
257 // On which squares is color under check ? (for interface)
258 getCheckSquares(color
) {
260 this.underCheck(color
)
261 // kingPos must be duplicated, because it may change:
262 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
270 // Setup the initial random (asymmetric) position
271 static GenRandInitFen(randomness
) {
274 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
276 let pieces
= { w: new Array(8), b: new Array(8) };
278 // Shuffle pieces on first (and last rank if randomness == 2)
279 for (let c
of ["w", "b"]) {
280 if (c
== 'b' && randomness
== 1) {
281 pieces
['b'] = pieces
['w'];
286 let positions
= ArrayFun
.range(8);
288 // Get random squares for bishops
289 let randIndex
= 2 * randInt(4);
290 const bishop1Pos
= positions
[randIndex
];
291 // The second bishop must be on a square of different color
292 let randIndex_tmp
= 2 * randInt(4) + 1;
293 const bishop2Pos
= positions
[randIndex_tmp
];
294 // Remove chosen squares
295 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
296 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
298 // Get random squares for knights
299 randIndex
= randInt(6);
300 const knight1Pos
= positions
[randIndex
];
301 positions
.splice(randIndex
, 1);
302 randIndex
= randInt(5);
303 const knight2Pos
= positions
[randIndex
];
304 positions
.splice(randIndex
, 1);
306 // Get random square for queen
307 randIndex
= randInt(4);
308 const queenPos
= positions
[randIndex
];
309 positions
.splice(randIndex
, 1);
311 // Rooks and king positions are now fixed,
312 // because of the ordering rook-king-rook
313 const rook1Pos
= positions
[0];
314 const kingPos
= positions
[1];
315 const rook2Pos
= positions
[2];
317 // Finally put the shuffled pieces in the board array
318 pieces
[c
][rook1Pos
] = "r";
319 pieces
[c
][knight1Pos
] = "n";
320 pieces
[c
][bishop1Pos
] = "b";
321 pieces
[c
][queenPos
] = "q";
322 pieces
[c
][kingPos
] = "k";
323 pieces
[c
][bishop2Pos
] = "b";
324 pieces
[c
][knight2Pos
] = "n";
325 pieces
[c
][rook2Pos
] = "r";
326 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
328 // Add turn + flags + enpassant
330 pieces
["b"].join("") +
331 "/pppppppp/8/8/8/8/PPPPPPPP/" +
332 pieces
["w"].join("").toUpperCase() +
333 " w 0 " + flags
+ " -"
337 // "Parse" FEN: just return untransformed string data
338 static ParseFen(fen
) {
339 const fenParts
= fen
.split(" ");
341 position: fenParts
[0],
343 movesCount: fenParts
[2]
346 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
347 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
351 // Return current fen (game state)
354 this.getBaseFen() + " " +
355 this.getTurnFen() + " " +
357 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
358 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
363 // Omit movesCount, only variable allowed to differ
365 this.getBaseFen() + "_" +
367 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
368 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
372 // Position part of the FEN string
374 const format
= (count
) => {
375 // if more than 9 consecutive free spaces, break the integer,
376 // otherwise FEN parsing will fail.
377 if (count
<= 9) return count
;
378 // Currently only boards of size up to 11 or 12:
379 return "9" + (count
- 9);
382 for (let i
= 0; i
< V
.size
.x
; i
++) {
384 for (let j
= 0; j
< V
.size
.y
; j
++) {
385 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
387 if (emptyCount
> 0) {
388 // Add empty squares in-between
389 position
+= format(emptyCount
);
392 position
+= V
.board2fen(this.board
[i
][j
]);
395 if (emptyCount
> 0) {
397 position
+= format(emptyCount
);
399 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
408 // Flags part of the FEN string
412 for (let c
of ["w", "b"])
413 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
417 // Enpassant part of the FEN string
419 const L
= this.epSquares
.length
;
420 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
421 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
424 // Turn position fen into double array ["wb","wp","bk",...]
425 static GetBoard(position
) {
426 const rows
= position
.split("/");
427 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
428 for (let i
= 0; i
< rows
.length
; i
++) {
430 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
431 const character
= rows
[i
][indexInRow
];
432 const num
= parseInt(character
);
433 // If num is a number, just shift j:
434 if (!isNaN(num
)) j
+= num
;
435 // Else: something at position i,j
436 else board
[i
][j
++] = V
.fen2board(character
);
442 // Extract (relevant) flags from fen
444 // white a-castle, h-castle, black a-castle, h-castle
445 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
446 for (let i
= 0; i
< 4; i
++) {
447 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
448 V
.ColumnToCoord(fenflags
.charAt(i
));
455 // Fen string fully describes the game state
458 // In printDiagram() fen isn't supply because only getPpath() is used
459 // TODO: find a better solution!
461 const fenParsed
= V
.ParseFen(fen
);
462 this.board
= V
.GetBoard(fenParsed
.position
);
463 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
464 this.movesCount
= parseInt(fenParsed
.movesCount
);
465 this.setOtherVariables(fen
);
468 // Scan board for kings positions
470 this.INIT_COL_KING
= { w: -1, b: -1 };
471 // Squares of white and black king:
472 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
473 const fenRows
= V
.ParseFen(fen
).position
.split("/");
474 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
475 for (let i
= 0; i
< fenRows
.length
; i
++) {
476 let k
= 0; //column index on board
477 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
478 switch (fenRows
[i
].charAt(j
)) {
480 this.kingPos
["b"] = [i
, k
];
481 this.INIT_COL_KING
["b"] = k
;
484 this.kingPos
["w"] = [i
, k
];
485 this.INIT_COL_KING
["w"] = k
;
488 const num
= parseInt(fenRows
[i
].charAt(j
));
489 if (!isNaN(num
)) k
+= num
- 1;
497 // Some additional variables from FEN (variant dependant)
498 setOtherVariables(fen
) {
499 // Set flags and enpassant:
500 const parsedFen
= V
.ParseFen(fen
);
501 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
502 if (V
.HasEnpassant
) {
504 parsedFen
.enpassant
!= "-"
505 ? this.getEpSquare(parsedFen
.enpassant
)
507 this.epSquares
= [epSq
];
509 // Search for kings positions:
513 /////////////////////
517 return { x: 8, y: 8 };
520 // Color of thing on square (i,j). 'undefined' if square is empty
522 return this.board
[i
][j
].charAt(0);
525 // Piece type on square (i,j). 'undefined' if square is empty
527 return this.board
[i
][j
].charAt(1);
530 // Get opponent color
531 static GetOppCol(color
) {
532 return color
== "w" ? "b" : "w";
535 // Pieces codes (for a clearer code)
542 static get KNIGHT() {
545 static get BISHOP() {
556 static get PIECES() {
557 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
565 // Some pieces movements
596 // All possible moves from selected square
597 getPotentialMovesFrom([x
, y
]) {
598 switch (this.getPiece(x
, y
)) {
600 return this.getPotentialPawnMoves([x
, y
]);
602 return this.getPotentialRookMoves([x
, y
]);
604 return this.getPotentialKnightMoves([x
, y
]);
606 return this.getPotentialBishopMoves([x
, y
]);
608 return this.getPotentialQueenMoves([x
, y
]);
610 return this.getPotentialKingMoves([x
, y
]);
612 return []; //never reached
615 // Build a regular move from its initial and destination squares.
616 // tr: transformation
617 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
618 const initColor
= this.getColor(sx
, sy
);
619 const initPiece
= this.getPiece(sx
, sy
);
625 c: tr
? tr
.c : initColor
,
626 p: tr
? tr
.p : initPiece
639 // The opponent piece disappears if we take it
640 if (this.board
[ex
][ey
] != V
.EMPTY
) {
645 c: this.getColor(ex
, ey
),
646 p: this.getPiece(ex
, ey
)
654 // Generic method to find possible moves of non-pawn pieces:
655 // "sliding or jumping"
656 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
658 outerLoop: for (let step
of steps
) {
661 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
662 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
663 if (oneStep
) continue outerLoop
;
667 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
668 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
673 // Special case of en-passant captures: treated separately
674 getEnpassantCaptures([x
, y
], shiftX
) {
675 const Lep
= this.epSquares
.length
;
676 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
677 let enpassantMove
= null;
680 epSquare
.x
== x
+ shiftX
&&
681 Math
.abs(epSquare
.y
- y
) == 1
683 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
684 enpassantMove
.vanish
.push({
687 // Captured piece is usually a pawn, but next line seems harmless
688 p: this.getPiece(x
, epSquare
.y
),
689 c: this.getColor(x
, epSquare
.y
)
692 return !!enpassantMove
? [enpassantMove
] : [];
695 // Consider all potential promotions:
696 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
697 let finalPieces
= [V
.PAWN
];
698 const color
= this.turn
;
699 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
700 if (x2
== lastRank
) {
701 // promotions arg: special override for Hiddenqueen variant
702 if (!!promotions
) finalPieces
= promotions
;
703 else if (!!V
.PawnSpecs
.promotions
)
704 finalPieces
= V
.PawnSpecs
.promotions
;
707 for (let piece
of finalPieces
) {
708 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
709 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
713 // What are the pawn moves from square x,y ?
714 getPotentialPawnMoves([x
, y
], promotions
) {
715 const color
= this.turn
;
716 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
717 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
718 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
719 const startRank
= (color
== "w" ? sizeX
- 2 : 1);
721 // Pawn movements in shiftX direction:
722 const getPawnMoves
= (shiftX
) => {
724 // NOTE: next condition is generally true (no pawn on last rank)
725 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
726 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
727 // One square forward
728 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
729 // Next condition because pawns on 1st rank can generally jump
731 V
.PawnSpecs
.twoSquares
&&
732 [startRank
, firstRank
].includes(x
) &&
733 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
736 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
740 if (V
.PawnSpecs
.canCapture
) {
741 for (let shiftY
of [-1, 1]) {
747 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
748 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
751 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
756 V
.PawnSpecs
.captureBackward
&&
757 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
758 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
759 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
762 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
773 let pMoves
= getPawnMoves(pawnShiftX
);
774 if (V
.PawnSpecs
.bidirectional
)
775 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
777 if (V
.HasEnpassant
) {
778 // NOTE: backward en-passant captures are not considered
779 // because no rules define them (for now).
780 Array
.prototype.push
.apply(
782 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
789 // What are the rook moves from square x,y ?
790 getPotentialRookMoves(sq
) {
791 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
794 // What are the knight moves from square x,y ?
795 getPotentialKnightMoves(sq
) {
796 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
799 // What are the bishop moves from square x,y ?
800 getPotentialBishopMoves(sq
) {
801 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
804 // What are the queen moves from square x,y ?
805 getPotentialQueenMoves(sq
) {
806 return this.getSlideNJumpMoves(
808 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
812 // What are the king moves from square x,y ?
813 getPotentialKingMoves(sq
) {
814 // Initialize with normal moves
815 let moves
= this.getSlideNJumpMoves(
817 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
820 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
824 // "castleInCheck" arg to let some variants castle under check
825 getCastleMoves([x
, y
], castleInCheck
) {
826 const c
= this.getColor(x
, y
);
827 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
828 return []; //x isn't first rank, or king has moved (shortcut)
831 const oppCol
= V
.GetOppCol(c
);
835 const finalSquares
= [
837 [V
.size
.y
- 2, V
.size
.y
- 3]
842 castleSide
++ //large, then small
844 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
845 // If this code is reached, rook and king are on initial position
847 // NOTE: in some variants this is not a rook
848 const rookPos
= this.castleFlags
[c
][castleSide
];
849 const castlingPiece
= this.getPiece(x
, rookPos
);
850 if (this.getColor(x
, rookPos
) != c
)
851 // Rook is here but changed color (see Benedict)
854 // Nothing on the path of the king ? (and no checks)
855 const finDist
= finalSquares
[castleSide
][0] - y
;
856 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
860 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
861 (this.board
[x
][i
] != V
.EMPTY
&&
862 // NOTE: next check is enough, because of chessboard constraints
863 (this.getColor(x
, i
) != c
||
864 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
866 continue castlingCheck
;
869 } while (i
!= finalSquares
[castleSide
][0]);
871 // Nothing on the path to the rook?
872 step
= castleSide
== 0 ? -1 : 1;
873 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
874 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
877 // Nothing on final squares, except maybe king and castling rook?
878 for (i
= 0; i
< 2; i
++) {
880 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
881 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
882 finalSquares
[castleSide
][i
] != rookPos
884 continue castlingCheck
;
888 // If this code is reached, castle is valid
894 y: finalSquares
[castleSide
][0],
900 y: finalSquares
[castleSide
][1],
906 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
907 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
910 Math
.abs(y
- rookPos
) <= 2
911 ? { x: x
, y: rookPos
}
912 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
923 // For the interface: possible moves for the current turn from square sq
924 getPossibleMovesFrom(sq
) {
925 return this.filterValid(this.getPotentialMovesFrom(sq
));
928 // TODO: promotions (into R,B,N,Q) should be filtered only once
930 if (moves
.length
== 0) return [];
931 const color
= this.turn
;
932 return moves
.filter(m
=> {
934 const res
= !this.underCheck(color
);
940 // Search for all valid moves considering current turn
941 // (for engine and game end)
943 const color
= this.turn
;
944 let potentialMoves
= [];
945 for (let i
= 0; i
< V
.size
.x
; i
++) {
946 for (let j
= 0; j
< V
.size
.y
; j
++) {
947 if (this.getColor(i
, j
) == color
) {
948 Array
.prototype.push
.apply(
950 this.getPotentialMovesFrom([i
, j
])
955 return this.filterValid(potentialMoves
);
958 // Stop at the first move found
959 // TODO: not really, it explores all moves from a square (one is enough).
961 const color
= this.turn
;
962 for (let i
= 0; i
< V
.size
.x
; i
++) {
963 for (let j
= 0; j
< V
.size
.y
; j
++) {
964 if (this.getColor(i
, j
) == color
) {
965 const moves
= this.getPotentialMovesFrom([i
, j
]);
966 if (moves
.length
> 0) {
967 for (let k
= 0; k
< moves
.length
; k
++) {
968 if (this.filterValid([moves
[k
]]).length
> 0) return true;
977 // Check if pieces of given color are attacking (king) on square x,y
978 isAttacked(sq
, color
) {
980 this.isAttackedByPawn(sq
, color
) ||
981 this.isAttackedByRook(sq
, color
) ||
982 this.isAttackedByKnight(sq
, color
) ||
983 this.isAttackedByBishop(sq
, color
) ||
984 this.isAttackedByQueen(sq
, color
) ||
985 this.isAttackedByKing(sq
, color
)
989 // Generic method for non-pawn pieces ("sliding or jumping"):
990 // is x,y attacked by a piece of given color ?
991 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
992 for (let step
of steps
) {
993 let rx
= x
+ step
[0],
995 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1000 V
.OnBoard(rx
, ry
) &&
1001 this.getPiece(rx
, ry
) == piece
&&
1002 this.getColor(rx
, ry
) == color
1010 // Is square x,y attacked by 'color' pawns ?
1011 isAttackedByPawn([x
, y
], color
) {
1012 const pawnShift
= (color
== "w" ? 1 : -1);
1013 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
1014 for (let i
of [-1, 1]) {
1018 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
1019 this.getColor(x
+ pawnShift
, y
+ i
) == color
1028 // Is square x,y attacked by 'color' rooks ?
1029 isAttackedByRook(sq
, color
) {
1030 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1033 // Is square x,y attacked by 'color' knights ?
1034 isAttackedByKnight(sq
, color
) {
1035 return this.isAttackedBySlideNJump(
1044 // Is square x,y attacked by 'color' bishops ?
1045 isAttackedByBishop(sq
, color
) {
1046 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1049 // Is square x,y attacked by 'color' queens ?
1050 isAttackedByQueen(sq
, color
) {
1051 return this.isAttackedBySlideNJump(
1055 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1059 // Is square x,y attacked by 'color' king(s) ?
1060 isAttackedByKing(sq
, color
) {
1061 return this.isAttackedBySlideNJump(
1065 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1070 // Is color under check after his move ?
1072 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1078 // Apply a move on board
1079 static PlayOnBoard(board
, move) {
1080 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1081 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1083 // Un-apply the played move
1084 static UndoOnBoard(board
, move) {
1085 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1086 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1093 // if (!this.states) this.states = [];
1094 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1095 // this.states.push(stateFen);
1098 // Save flags (for undo)
1099 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1100 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1101 V
.PlayOnBoard(this.board
, move);
1102 this.turn
= V
.GetOppCol(this.turn
);
1104 this.postPlay(move);
1107 updateCastleFlags(move, piece
) {
1108 const c
= V
.GetOppCol(this.turn
);
1109 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1110 // Update castling flags if rooks are moved
1111 const oppCol
= this.turn
;
1112 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1113 if (piece
== V
.KING
&& move.appear
.length
> 0)
1114 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1116 move.start
.x
== firstRank
&& //our rook moves?
1117 this.castleFlags
[c
].includes(move.start
.y
)
1119 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1120 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1122 // NOTE: not "else if" because a rook could take an opposing rook
1124 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1125 this.castleFlags
[oppCol
].includes(move.end
.y
)
1127 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1128 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1132 // After move is played, update variables + flags
1134 const c
= V
.GetOppCol(this.turn
);
1135 let piece
= undefined;
1136 if (move.vanish
.length
>= 1)
1137 // Usual case, something is moved
1138 piece
= move.vanish
[0].p
;
1140 // Crazyhouse-like variants
1141 piece
= move.appear
[0].p
;
1143 // Update king position + flags
1144 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1145 this.kingPos
[c
][0] = move.appear
[0].x
;
1146 this.kingPos
[c
][1] = move.appear
[0].y
;
1149 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1156 if (V
.HasEnpassant
) this.epSquares
.pop();
1157 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1158 V
.UndoOnBoard(this.board
, move);
1159 this.turn
= V
.GetOppCol(this.turn
);
1161 this.postUndo(move);
1164 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1165 // if (stateFen != this.states[this.states.length-1]) debugger;
1166 // this.states.pop();
1169 // After move is undo-ed *and flags resetted*, un-update other variables
1170 // TODO: more symmetry, by storing flags increment in move (?!)
1172 // (Potentially) Reset king position
1173 const c
= this.getColor(move.start
.x
, move.start
.y
);
1174 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1175 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1181 // What is the score ? (Interesting if game is over)
1183 if (this.atLeastOneMove()) return "*";
1185 const color
= this.turn
;
1186 // No valid move: stalemate or checkmate?
1187 if (!this.underCheck(color
)) return "1/2";
1189 return (color
== "w" ? "0-1" : "1-0");
1196 static get VALUES() {
1207 // "Checkmate" (unreachable eval)
1208 static get INFINITY() {
1212 // At this value or above, the game is over
1213 static get THRESHOLD_MATE() {
1217 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1218 static get SEARCH_DEPTH() {
1223 const maxeval
= V
.INFINITY
;
1224 const color
= this.turn
;
1225 let moves1
= this.getAllValidMoves();
1227 if (moves1
.length
== 0)
1228 // TODO: this situation should not happen
1231 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1232 for (let i
= 0; i
< moves1
.length
; i
++) {
1233 this.play(moves1
[i
]);
1234 const score1
= this.getCurrentScore();
1235 if (score1
!= "*") {
1239 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1241 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1242 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1243 this.undo(moves1
[i
]);
1246 // Initial self evaluation is very low: "I'm checkmated"
1247 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1248 // Initial enemy evaluation is very low too, for him
1249 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1250 // Second half-move:
1251 let moves2
= this.getAllValidMoves();
1252 for (let j
= 0; j
< moves2
.length
; j
++) {
1253 this.play(moves2
[j
]);
1254 const score2
= this.getCurrentScore();
1255 let evalPos
= 0; //1/2 value
1258 evalPos
= this.evalPosition();
1268 (color
== "w" && evalPos
< eval2
) ||
1269 (color
== "b" && evalPos
> eval2
)
1273 this.undo(moves2
[j
]);
1276 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1277 (color
== "b" && eval2
< moves1
[i
].eval
)
1279 moves1
[i
].eval
= eval2
;
1281 this.undo(moves1
[i
]);
1283 moves1
.sort((a
, b
) => {
1284 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1286 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1288 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1289 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1290 for (let i
= 0; i
< moves1
.length
; i
++) {
1291 this.play(moves1
[i
]);
1292 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1294 0.1 * moves1
[i
].eval
+
1295 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1296 this.undo(moves1
[i
]);
1298 moves1
.sort((a
, b
) => {
1299 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1303 let candidates
= [0];
1304 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1306 return moves1
[candidates
[randInt(candidates
.length
)]];
1309 alphabeta(depth
, alpha
, beta
) {
1310 const maxeval
= V
.INFINITY
;
1311 const color
= this.turn
;
1312 const score
= this.getCurrentScore();
1314 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1315 if (depth
== 0) return this.evalPosition();
1316 const moves
= this.getAllValidMoves();
1317 let v
= color
== "w" ? -maxeval : maxeval
;
1319 for (let i
= 0; i
< moves
.length
; i
++) {
1320 this.play(moves
[i
]);
1321 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1322 this.undo(moves
[i
]);
1323 alpha
= Math
.max(alpha
, v
);
1324 if (alpha
>= beta
) break; //beta cutoff
1329 for (let i
= 0; i
< moves
.length
; i
++) {
1330 this.play(moves
[i
]);
1331 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1332 this.undo(moves
[i
]);
1333 beta
= Math
.min(beta
, v
);
1334 if (alpha
>= beta
) break; //alpha cutoff
1342 // Just count material for now
1343 for (let i
= 0; i
< V
.size
.x
; i
++) {
1344 for (let j
= 0; j
< V
.size
.y
; j
++) {
1345 if (this.board
[i
][j
] != V
.EMPTY
) {
1346 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1347 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1354 /////////////////////////
1355 // MOVES + GAME NOTATION
1356 /////////////////////////
1358 // Context: just before move is played, turn hasn't changed
1359 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1361 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1363 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1365 // Translate final square
1366 const finalSquare
= V
.CoordsToSquare(move.end
);
1368 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1369 if (piece
== V
.PAWN
) {
1372 if (move.vanish
.length
> move.appear
.length
) {
1374 const startColumn
= V
.CoordToColumn(move.start
.y
);
1375 notation
= startColumn
+ "x" + finalSquare
;
1377 else notation
= finalSquare
;
1378 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1380 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1385 piece
.toUpperCase() +
1386 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1391 static GetUnambiguousNotation(move) {
1392 // Machine-readable format with all the informations about the move
1394 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1395 ? V
.CoordsToSquare(move.start
)
1398 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1399 ? V
.CoordsToSquare(move.end
)
1402 (!!move.appear
&& move.appear
.length
> 0
1403 ? move.appear
.map(a
=>
1404 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1407 (!!move.vanish
&& move.vanish
.length
> 0
1408 ? move.vanish
.map(a
=>
1409 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")