1795b5fa97f9a8cd46adb202b857c1a879cf76ff
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 },
50 initShift: { w: 1, b: 1 },
53 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
55 captureBackward: false,
60 // En-passant captures need a stack of squares:
61 static get HasEnpassant() {
65 // Some variants cannot have analyse mode
66 static get CanAnalyze() {
69 // Patch: issues with javascript OOP, objects can't access static fields.
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
83 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
88 // Some variants always show the same orientation
89 static get CanFlip() {
96 // For (generally old) variants without checkered board
97 static get Monochrome() {
101 // Some variants require lines drawing
105 // Draw all inter-squares lines
106 for (let i
= 0; i
<= V
.size
.x
; i
++)
107 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
108 for (let j
= 0; j
<= V
.size
.y
; j
++)
109 lines
.push([[0, j
], [V
.size
.x
, j
]]);
115 // Some variants use click infos:
120 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
125 static get IMAGE_EXTENSION() {
126 // All pieces should be in the SVG format
130 // Turn "wb" into "B" (for FEN)
131 static board2fen(b
) {
132 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
135 // Turn "p" into "bp" (for board)
136 static fen2board(f
) {
137 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
140 // Check if FEN describes a board situation correctly
141 static IsGoodFen(fen
) {
142 const fenParsed
= V
.ParseFen(fen
);
144 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
146 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
147 // 3) Check moves count
148 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
151 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
153 // 5) Check enpassant
156 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
163 // Is position part of the FEN a priori correct?
164 static IsGoodPosition(position
) {
165 if (position
.length
== 0) return false;
166 const rows
= position
.split("/");
167 if (rows
.length
!= V
.size
.x
) return false;
168 let kings
= { "k": 0, "K": 0 };
169 for (let row
of rows
) {
171 for (let i
= 0; i
< row
.length
; i
++) {
172 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
173 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
175 const num
= parseInt(row
[i
]);
176 if (isNaN(num
)) return false;
180 if (sumElts
!= V
.size
.y
) return false;
182 // Both kings should be on board. Exactly one per color.
183 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
188 static IsGoodTurn(turn
) {
189 return ["w", "b"].includes(turn
);
193 static IsGoodFlags(flags
) {
194 // NOTE: a little too permissive to work with more variants
195 return !!flags
.match(/^[a-z]{4,4}$/);
198 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
199 static IsGoodEnpassant(enpassant
) {
200 if (enpassant
!= "-") {
201 const ep
= V
.SquareToCoords(enpassant
);
202 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
207 // 3 --> d (column number to letter)
208 static CoordToColumn(colnum
) {
209 return String
.fromCharCode(97 + colnum
);
212 // d --> 3 (column letter to number)
213 static ColumnToCoord(column
) {
214 return column
.charCodeAt(0) - 97;
218 static SquareToCoords(sq
) {
220 // NOTE: column is always one char => max 26 columns
221 // row is counted from black side => subtraction
222 x: V
.size
.x
- parseInt(sq
.substr(1)),
223 y: sq
[0].charCodeAt() - 97
228 static CoordsToSquare(coords
) {
229 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
232 // Path to pieces (standard ones in pieces/ folder)
237 // Path to promotion pieces (usually the same)
239 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
242 // Aggregates flags into one object
244 return this.castleFlags
;
248 disaggregateFlags(flags
) {
249 this.castleFlags
= flags
;
252 // En-passant square, if any
253 getEpSquare(moveOrSquare
) {
254 if (!moveOrSquare
) return undefined;
255 if (typeof moveOrSquare
=== "string") {
256 const square
= moveOrSquare
;
257 if (square
== "-") return undefined;
258 return V
.SquareToCoords(square
);
260 // Argument is a move:
261 const move = moveOrSquare
;
262 const s
= move.start
,
266 Math
.abs(s
.x
- e
.x
) == 2 &&
267 // Next conditions for variants like Atomic or Rifle, Recycle...
268 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
269 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
276 return undefined; //default
279 // Can thing on square1 take thing on square2
280 canTake([x1
, y1
], [x2
, y2
]) {
281 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
284 // Is (x,y) on the chessboard?
285 static OnBoard(x
, y
) {
286 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
289 // Used in interface: 'side' arg == player color
290 canIplay(side
, [x
, y
]) {
291 return this.turn
== side
&& this.getColor(x
, y
) == side
;
294 // On which squares is color under check ? (for interface)
296 const color
= this.turn
;
298 this.underCheck(color
)
299 // kingPos must be duplicated, because it may change:
300 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
308 // Setup the initial random (asymmetric) position
309 static GenRandInitFen(randomness
) {
312 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
314 let pieces
= { w: new Array(8), b: new Array(8) };
316 // Shuffle pieces on first (and last rank if randomness == 2)
317 for (let c
of ["w", "b"]) {
318 if (c
== 'b' && randomness
== 1) {
319 pieces
['b'] = pieces
['w'];
324 let positions
= ArrayFun
.range(8);
326 // Get random squares for bishops
327 let randIndex
= 2 * randInt(4);
328 const bishop1Pos
= positions
[randIndex
];
329 // The second bishop must be on a square of different color
330 let randIndex_tmp
= 2 * randInt(4) + 1;
331 const bishop2Pos
= positions
[randIndex_tmp
];
332 // Remove chosen squares
333 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
334 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
336 // Get random squares for knights
337 randIndex
= randInt(6);
338 const knight1Pos
= positions
[randIndex
];
339 positions
.splice(randIndex
, 1);
340 randIndex
= randInt(5);
341 const knight2Pos
= positions
[randIndex
];
342 positions
.splice(randIndex
, 1);
344 // Get random square for queen
345 randIndex
= randInt(4);
346 const queenPos
= positions
[randIndex
];
347 positions
.splice(randIndex
, 1);
349 // Rooks and king positions are now fixed,
350 // because of the ordering rook-king-rook
351 const rook1Pos
= positions
[0];
352 const kingPos
= positions
[1];
353 const rook2Pos
= positions
[2];
355 // Finally put the shuffled pieces in the board array
356 pieces
[c
][rook1Pos
] = "r";
357 pieces
[c
][knight1Pos
] = "n";
358 pieces
[c
][bishop1Pos
] = "b";
359 pieces
[c
][queenPos
] = "q";
360 pieces
[c
][kingPos
] = "k";
361 pieces
[c
][bishop2Pos
] = "b";
362 pieces
[c
][knight2Pos
] = "n";
363 pieces
[c
][rook2Pos
] = "r";
364 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
366 // Add turn + flags + enpassant
368 pieces
["b"].join("") +
369 "/pppppppp/8/8/8/8/PPPPPPPP/" +
370 pieces
["w"].join("").toUpperCase() +
371 " w 0 " + flags
+ " -"
375 // "Parse" FEN: just return untransformed string data
376 static ParseFen(fen
) {
377 const fenParts
= fen
.split(" ");
379 position: fenParts
[0],
381 movesCount: fenParts
[2]
384 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
385 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
389 // Return current fen (game state)
392 this.getBaseFen() + " " +
393 this.getTurnFen() + " " +
395 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
396 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
401 // Omit movesCount, only variable allowed to differ
403 this.getBaseFen() + "_" +
405 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
406 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
410 // Position part of the FEN string
412 const format
= (count
) => {
413 // if more than 9 consecutive free spaces, break the integer,
414 // otherwise FEN parsing will fail.
415 if (count
<= 9) return count
;
416 // Currently only boards of size up to 11 or 12:
417 return "9" + (count
- 9);
420 for (let i
= 0; i
< V
.size
.x
; i
++) {
422 for (let j
= 0; j
< V
.size
.y
; j
++) {
423 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
425 if (emptyCount
> 0) {
426 // Add empty squares in-between
427 position
+= format(emptyCount
);
430 position
+= V
.board2fen(this.board
[i
][j
]);
433 if (emptyCount
> 0) {
435 position
+= format(emptyCount
);
437 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
446 // Flags part of the FEN string
450 for (let c
of ["w", "b"])
451 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
455 // Enpassant part of the FEN string
457 const L
= this.epSquares
.length
;
458 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
459 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
462 // Turn position fen into double array ["wb","wp","bk",...]
463 static GetBoard(position
) {
464 const rows
= position
.split("/");
465 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
466 for (let i
= 0; i
< rows
.length
; i
++) {
468 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
469 const character
= rows
[i
][indexInRow
];
470 const num
= parseInt(character
);
471 // If num is a number, just shift j:
472 if (!isNaN(num
)) j
+= num
;
473 // Else: something at position i,j
474 else board
[i
][j
++] = V
.fen2board(character
);
480 // Extract (relevant) flags from fen
482 // white a-castle, h-castle, black a-castle, h-castle
483 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
484 for (let i
= 0; i
< 4; i
++) {
485 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
486 V
.ColumnToCoord(fenflags
.charAt(i
));
493 // Fen string fully describes the game state
496 // In printDiagram() fen isn't supply because only getPpath() is used
497 // TODO: find a better solution!
499 const fenParsed
= V
.ParseFen(fen
);
500 this.board
= V
.GetBoard(fenParsed
.position
);
501 this.turn
= fenParsed
.turn
;
502 this.movesCount
= parseInt(fenParsed
.movesCount
);
503 this.setOtherVariables(fen
);
506 // Scan board for kings positions
508 this.INIT_COL_KING
= { w: -1, b: -1 };
509 // Squares of white and black king:
510 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
511 const fenRows
= V
.ParseFen(fen
).position
.split("/");
512 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
513 for (let i
= 0; i
< fenRows
.length
; i
++) {
514 let k
= 0; //column index on board
515 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
516 switch (fenRows
[i
].charAt(j
)) {
518 this.kingPos
["b"] = [i
, k
];
519 this.INIT_COL_KING
["b"] = k
;
522 this.kingPos
["w"] = [i
, k
];
523 this.INIT_COL_KING
["w"] = k
;
526 const num
= parseInt(fenRows
[i
].charAt(j
));
527 if (!isNaN(num
)) k
+= num
- 1;
535 // Some additional variables from FEN (variant dependant)
536 setOtherVariables(fen
) {
537 // Set flags and enpassant:
538 const parsedFen
= V
.ParseFen(fen
);
539 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
540 if (V
.HasEnpassant
) {
542 parsedFen
.enpassant
!= "-"
543 ? this.getEpSquare(parsedFen
.enpassant
)
545 this.epSquares
= [epSq
];
547 // Search for kings positions:
551 /////////////////////
555 return { x: 8, y: 8 };
558 // Color of thing on square (i,j). 'undefined' if square is empty
560 return this.board
[i
][j
].charAt(0);
563 // Piece type on square (i,j). 'undefined' if square is empty
565 return this.board
[i
][j
].charAt(1);
568 // Get opponent color
569 static GetOppCol(color
) {
570 return color
== "w" ? "b" : "w";
573 // Pieces codes (for a clearer code)
580 static get KNIGHT() {
583 static get BISHOP() {
594 static get PIECES() {
595 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
603 // Some pieces movements
634 // All possible moves from selected square
635 getPotentialMovesFrom([x
, y
]) {
636 switch (this.getPiece(x
, y
)) {
638 return this.getPotentialPawnMoves([x
, y
]);
640 return this.getPotentialRookMoves([x
, y
]);
642 return this.getPotentialKnightMoves([x
, y
]);
644 return this.getPotentialBishopMoves([x
, y
]);
646 return this.getPotentialQueenMoves([x
, y
]);
648 return this.getPotentialKingMoves([x
, y
]);
650 return []; //never reached
653 // Build a regular move from its initial and destination squares.
654 // tr: transformation
655 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
656 const initColor
= this.getColor(sx
, sy
);
657 const initPiece
= this.getPiece(sx
, sy
);
663 c: tr
? tr
.c : initColor
,
664 p: tr
? tr
.p : initPiece
677 // The opponent piece disappears if we take it
678 if (this.board
[ex
][ey
] != V
.EMPTY
) {
683 c: this.getColor(ex
, ey
),
684 p: this.getPiece(ex
, ey
)
692 // Generic method to find possible moves of non-pawn pieces:
693 // "sliding or jumping"
694 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
696 outerLoop: for (let step
of steps
) {
699 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
700 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
701 if (oneStep
) continue outerLoop
;
705 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
706 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
711 // Special case of en-passant captures: treated separately
712 getEnpassantCaptures([x
, y
], shiftX
) {
713 const Lep
= this.epSquares
.length
;
714 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
715 let enpassantMove
= null;
718 epSquare
.x
== x
+ shiftX
&&
719 Math
.abs(epSquare
.y
- y
) == 1
721 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
722 enpassantMove
.vanish
.push({
725 // Captured piece is usually a pawn, but next line seems harmless
726 p: this.getPiece(x
, epSquare
.y
),
727 c: this.getColor(x
, epSquare
.y
)
730 return !!enpassantMove
? [enpassantMove
] : [];
733 // Consider all potential promotions:
734 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
735 let finalPieces
= [V
.PAWN
];
736 const color
= this.turn
; //this.getColor(x1, y1);
737 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
738 if (x2
== lastRank
) {
739 // promotions arg: special override for Hiddenqueen variant
740 if (!!promotions
) finalPieces
= promotions
;
741 else if (!!V
.PawnSpecs
.promotions
)
742 finalPieces
= V
.PawnSpecs
.promotions
;
745 for (let piece
of finalPieces
) {
746 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
747 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
751 // What are the pawn moves from square x,y ?
752 getPotentialPawnMoves([x
, y
], promotions
) {
753 const color
= this.turn
; //this.getColor(x, y);
754 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
755 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
756 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
758 // Pawn movements in shiftX direction:
759 const getPawnMoves
= (shiftX
) => {
761 // NOTE: next condition is generally true (no pawn on last rank)
762 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
763 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
764 // One square forward
765 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
766 // Next condition because pawns on 1st rank can generally jump
768 V
.PawnSpecs
.twoSquares
&&
770 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
772 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
775 if (this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
) {
777 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
779 V
.PawnSpecs
.threeSquares
&&
780 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
782 // Three squares jump
783 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
789 if (V
.PawnSpecs
.canCapture
) {
790 for (let shiftY
of [-1, 1]) {
796 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
797 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
800 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
805 V
.PawnSpecs
.captureBackward
&&
806 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
807 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
808 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
811 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
822 let pMoves
= getPawnMoves(pawnShiftX
);
823 if (V
.PawnSpecs
.bidirectional
)
824 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
826 if (V
.HasEnpassant
) {
827 // NOTE: backward en-passant captures are not considered
828 // because no rules define them (for now).
829 Array
.prototype.push
.apply(
831 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
838 // What are the rook moves from square x,y ?
839 getPotentialRookMoves(sq
) {
840 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
843 // What are the knight moves from square x,y ?
844 getPotentialKnightMoves(sq
) {
845 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
848 // What are the bishop moves from square x,y ?
849 getPotentialBishopMoves(sq
) {
850 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
853 // What are the queen moves from square x,y ?
854 getPotentialQueenMoves(sq
) {
855 return this.getSlideNJumpMoves(
857 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
861 // What are the king moves from square x,y ?
862 getPotentialKingMoves(sq
) {
863 // Initialize with normal moves
864 let moves
= this.getSlideNJumpMoves(
866 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
869 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
873 // "castleInCheck" arg to let some variants castle under check
874 getCastleMoves([x
, y
], castleInCheck
) {
875 const c
= this.getColor(x
, y
);
876 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
877 return []; //x isn't first rank, or king has moved (shortcut)
880 const oppCol
= V
.GetOppCol(c
);
884 const finalSquares
= [
886 [V
.size
.y
- 2, V
.size
.y
- 3]
891 castleSide
++ //large, then small
893 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
894 // If this code is reached, rook and king are on initial position
896 // NOTE: in some variants this is not a rook
897 const rookPos
= this.castleFlags
[c
][castleSide
];
898 if (this.board
[x
][rookPos
] == V
.EMPTY
|| this.getColor(x
, rookPos
) != c
)
899 // Rook is not here, or changed color (see Benedict)
902 // Nothing on the path of the king ? (and no checks)
903 const castlingPiece
= this.getPiece(x
, rookPos
);
904 const finDist
= finalSquares
[castleSide
][0] - y
;
905 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
909 // NOTE: "castling" arg is used by some variants (Monster),
910 // where "isAttacked" is overloaded in an infinite-recursive way.
911 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
, "castling")) ||
912 (this.board
[x
][i
] != V
.EMPTY
&&
913 // NOTE: next check is enough, because of chessboard constraints
914 (this.getColor(x
, i
) != c
||
915 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
917 continue castlingCheck
;
920 } while (i
!= finalSquares
[castleSide
][0]);
922 // Nothing on the path to the rook?
923 step
= castleSide
== 0 ? -1 : 1;
924 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
925 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
928 // Nothing on final squares, except maybe king and castling rook?
929 for (i
= 0; i
< 2; i
++) {
931 finalSquares
[castleSide
][i
] != rookPos
&&
932 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
934 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
||
935 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
938 continue castlingCheck
;
942 // If this code is reached, castle is valid
948 y: finalSquares
[castleSide
][0],
954 y: finalSquares
[castleSide
][1],
960 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
961 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
964 Math
.abs(y
- rookPos
) <= 2
965 ? { x: x
, y: rookPos
}
966 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
977 // For the interface: possible moves for the current turn from square sq
978 getPossibleMovesFrom(sq
) {
979 return this.filterValid(this.getPotentialMovesFrom(sq
));
982 // TODO: promotions (into R,B,N,Q) should be filtered only once
984 if (moves
.length
== 0) return [];
985 const color
= this.turn
;
986 return moves
.filter(m
=> {
988 const res
= !this.underCheck(color
);
994 getAllPotentialMoves() {
995 const color
= this.turn
;
996 let potentialMoves
= [];
997 for (let i
= 0; i
< V
.size
.x
; i
++) {
998 for (let j
= 0; j
< V
.size
.y
; j
++) {
999 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1000 Array
.prototype.push
.apply(
1002 this.getPotentialMovesFrom([i
, j
])
1007 return potentialMoves
;
1010 // Search for all valid moves considering current turn
1011 // (for engine and game end)
1012 getAllValidMoves() {
1013 return this.filterValid(this.getAllPotentialMoves());
1016 // Stop at the first move found
1017 // TODO: not really, it explores all moves from a square (one is enough).
1019 const color
= this.turn
;
1020 for (let i
= 0; i
< V
.size
.x
; i
++) {
1021 for (let j
= 0; j
< V
.size
.y
; j
++) {
1022 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1023 const moves
= this.getPotentialMovesFrom([i
, j
]);
1024 if (moves
.length
> 0) {
1025 for (let k
= 0; k
< moves
.length
; k
++)
1026 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1034 // Check if pieces of given color are attacking (king) on square x,y
1035 isAttacked(sq
, color
) {
1037 this.isAttackedByPawn(sq
, color
) ||
1038 this.isAttackedByRook(sq
, color
) ||
1039 this.isAttackedByKnight(sq
, color
) ||
1040 this.isAttackedByBishop(sq
, color
) ||
1041 this.isAttackedByQueen(sq
, color
) ||
1042 this.isAttackedByKing(sq
, color
)
1046 // Generic method for non-pawn pieces ("sliding or jumping"):
1047 // is x,y attacked by a piece of given color ?
1048 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1049 for (let step
of steps
) {
1050 let rx
= x
+ step
[0],
1052 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1057 V
.OnBoard(rx
, ry
) &&
1058 this.getPiece(rx
, ry
) == piece
&&
1059 this.getColor(rx
, ry
) == color
1067 // Is square x,y attacked by 'color' pawns ?
1068 isAttackedByPawn(sq
, color
) {
1069 const pawnShift
= (color
== "w" ? 1 : -1);
1070 return this.isAttackedBySlideNJump(
1074 [[pawnShift
, 1], [pawnShift
, -1]],
1079 // Is square x,y attacked by 'color' rooks ?
1080 isAttackedByRook(sq
, color
) {
1081 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1084 // Is square x,y attacked by 'color' knights ?
1085 isAttackedByKnight(sq
, color
) {
1086 return this.isAttackedBySlideNJump(
1095 // Is square x,y attacked by 'color' bishops ?
1096 isAttackedByBishop(sq
, color
) {
1097 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1100 // Is square x,y attacked by 'color' queens ?
1101 isAttackedByQueen(sq
, color
) {
1102 return this.isAttackedBySlideNJump(
1106 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1110 // Is square x,y attacked by 'color' king(s) ?
1111 isAttackedByKing(sq
, color
) {
1112 return this.isAttackedBySlideNJump(
1116 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1121 // Is color under check after his move ?
1123 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1129 // Apply a move on board
1130 static PlayOnBoard(board
, move) {
1131 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1132 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1134 // Un-apply the played move
1135 static UndoOnBoard(board
, move) {
1136 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1137 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1144 // if (!this.states) this.states = [];
1145 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1146 // this.states.push(stateFen);
1149 // Save flags (for undo)
1150 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1151 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1152 V
.PlayOnBoard(this.board
, move);
1153 this.turn
= V
.GetOppCol(this.turn
);
1155 this.postPlay(move);
1158 updateCastleFlags(move, piece
) {
1159 const c
= V
.GetOppCol(this.turn
);
1160 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1161 // Update castling flags if rooks are moved
1162 const oppCol
= this.turn
;
1163 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1164 if (piece
== V
.KING
&& move.appear
.length
> 0)
1165 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1167 move.start
.x
== firstRank
&& //our rook moves?
1168 this.castleFlags
[c
].includes(move.start
.y
)
1170 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1171 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1173 // NOTE: not "else if" because a rook could take an opposing rook
1175 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1176 this.castleFlags
[oppCol
].includes(move.end
.y
)
1178 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1179 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1183 // After move is played, update variables + flags
1185 const c
= V
.GetOppCol(this.turn
);
1186 let piece
= undefined;
1187 if (move.vanish
.length
>= 1)
1188 // Usual case, something is moved
1189 piece
= move.vanish
[0].p
;
1191 // Crazyhouse-like variants
1192 piece
= move.appear
[0].p
;
1194 // Update king position + flags
1195 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1196 this.kingPos
[c
][0] = move.appear
[0].x
;
1197 this.kingPos
[c
][1] = move.appear
[0].y
;
1199 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1206 if (V
.HasEnpassant
) this.epSquares
.pop();
1207 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1208 V
.UndoOnBoard(this.board
, move);
1209 this.turn
= V
.GetOppCol(this.turn
);
1211 this.postUndo(move);
1214 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1215 // if (stateFen != this.states[this.states.length-1]) debugger;
1216 // this.states.pop();
1219 // After move is undo-ed *and flags resetted*, un-update other variables
1220 // TODO: more symmetry, by storing flags increment in move (?!)
1222 // (Potentially) Reset king position
1223 const c
= this.getColor(move.start
.x
, move.start
.y
);
1224 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1225 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1231 // What is the score ? (Interesting if game is over)
1233 if (this.atLeastOneMove()) return "*";
1235 const color
= this.turn
;
1236 // No valid move: stalemate or checkmate?
1237 if (!this.underCheck(color
)) return "1/2";
1239 return (color
== "w" ? "0-1" : "1-0");
1246 static get VALUES() {
1257 // "Checkmate" (unreachable eval)
1258 static get INFINITY() {
1262 // At this value or above, the game is over
1263 static get THRESHOLD_MATE() {
1267 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1268 static get SEARCH_DEPTH() {
1272 // 'movesList' arg for some variants to provide a custom list
1273 getComputerMove(movesList
) {
1274 const maxeval
= V
.INFINITY
;
1275 const color
= this.turn
;
1276 let moves1
= movesList
|| this.getAllValidMoves();
1278 if (moves1
.length
== 0)
1279 // TODO: this situation should not happen
1282 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1283 for (let i
= 0; i
< moves1
.length
; i
++) {
1284 this.play(moves1
[i
]);
1285 const score1
= this.getCurrentScore();
1286 if (score1
!= "*") {
1290 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1292 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1293 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1294 this.undo(moves1
[i
]);
1297 // Initial self evaluation is very low: "I'm checkmated"
1298 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1299 // Initial enemy evaluation is very low too, for him
1300 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1301 // Second half-move:
1302 let moves2
= this.getAllValidMoves();
1303 for (let j
= 0; j
< moves2
.length
; j
++) {
1304 this.play(moves2
[j
]);
1305 const score2
= this.getCurrentScore();
1306 let evalPos
= 0; //1/2 value
1309 evalPos
= this.evalPosition();
1319 (color
== "w" && evalPos
< eval2
) ||
1320 (color
== "b" && evalPos
> eval2
)
1324 this.undo(moves2
[j
]);
1327 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1328 (color
== "b" && eval2
< moves1
[i
].eval
)
1330 moves1
[i
].eval
= eval2
;
1332 this.undo(moves1
[i
]);
1334 moves1
.sort((a
, b
) => {
1335 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1337 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1339 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1340 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1341 for (let i
= 0; i
< moves1
.length
; i
++) {
1342 this.play(moves1
[i
]);
1343 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1345 0.1 * moves1
[i
].eval
+
1346 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1347 this.undo(moves1
[i
]);
1349 moves1
.sort((a
, b
) => {
1350 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1354 let candidates
= [0];
1355 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1357 return moves1
[candidates
[randInt(candidates
.length
)]];
1360 alphabeta(depth
, alpha
, beta
) {
1361 const maxeval
= V
.INFINITY
;
1362 const color
= this.turn
;
1363 const score
= this.getCurrentScore();
1365 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1366 if (depth
== 0) return this.evalPosition();
1367 const moves
= this.getAllValidMoves();
1368 let v
= color
== "w" ? -maxeval : maxeval
;
1370 for (let i
= 0; i
< moves
.length
; i
++) {
1371 this.play(moves
[i
]);
1372 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1373 this.undo(moves
[i
]);
1374 alpha
= Math
.max(alpha
, v
);
1375 if (alpha
>= beta
) break; //beta cutoff
1380 for (let i
= 0; i
< moves
.length
; i
++) {
1381 this.play(moves
[i
]);
1382 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1383 this.undo(moves
[i
]);
1384 beta
= Math
.min(beta
, v
);
1385 if (alpha
>= beta
) break; //alpha cutoff
1393 // Just count material for now
1394 for (let i
= 0; i
< V
.size
.x
; i
++) {
1395 for (let j
= 0; j
< V
.size
.y
; j
++) {
1396 if (this.board
[i
][j
] != V
.EMPTY
) {
1397 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1398 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1405 /////////////////////////
1406 // MOVES + GAME NOTATION
1407 /////////////////////////
1409 // Context: just before move is played, turn hasn't changed
1410 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1412 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1414 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1416 // Translate final square
1417 const finalSquare
= V
.CoordsToSquare(move.end
);
1419 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1420 if (piece
== V
.PAWN
) {
1423 if (move.vanish
.length
> move.appear
.length
) {
1425 const startColumn
= V
.CoordToColumn(move.start
.y
);
1426 notation
= startColumn
+ "x" + finalSquare
;
1428 else notation
= finalSquare
;
1429 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1431 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1436 piece
.toUpperCase() +
1437 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1442 static GetUnambiguousNotation(move) {
1443 // Machine-readable format with all the informations about the move
1445 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1446 ? V
.CoordsToSquare(move.start
)
1449 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1450 ? V
.CoordsToSquare(move.end
)
1453 (!!move.appear
&& move.appear
.length
> 0
1454 ? move.appear
.map(a
=>
1455 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1458 (!!move.vanish
&& move.vanish
.length
> 0
1459 ? move.vanish
.map(a
=>
1460 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")