37e756e9d141f8018e29103b5ac3e9ffc98b6abe
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;
131 let kings
= { "k": 0, "K": 0 };
132 for (let row
of rows
) {
134 for (let i
= 0; i
< row
.length
; i
++) {
135 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
136 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
138 const num
= parseInt(row
[i
]);
139 if (isNaN(num
)) return false;
143 if (sumElts
!= V
.size
.y
) return false;
145 // Both kings should be on board. Exactly one per color.
146 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
151 static IsGoodTurn(turn
) {
152 return ["w", "b"].includes(turn
);
156 static IsGoodFlags(flags
) {
157 // NOTE: a little too permissive to work with more variants
158 return !!flags
.match(/^[a-z]{4,4}$/);
161 static IsGoodEnpassant(enpassant
) {
162 if (enpassant
!= "-") {
163 const ep
= V
.SquareToCoords(enpassant
);
164 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
169 // 3 --> d (column number to letter)
170 static CoordToColumn(colnum
) {
171 return String
.fromCharCode(97 + colnum
);
174 // d --> 3 (column letter to number)
175 static ColumnToCoord(column
) {
176 return column
.charCodeAt(0) - 97;
180 static SquareToCoords(sq
) {
182 // NOTE: column is always one char => max 26 columns
183 // row is counted from black side => subtraction
184 x: V
.size
.x
- parseInt(sq
.substr(1)),
185 y: sq
[0].charCodeAt() - 97
190 static CoordsToSquare(coords
) {
191 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
194 // Path to pieces (standard ones in pieces/ folder)
199 // Path to promotion pieces (usually the same)
201 return this.getPpath(b
);
204 // Aggregates flags into one object
206 return this.castleFlags
;
210 disaggregateFlags(flags
) {
211 this.castleFlags
= flags
;
214 // En-passant square, if any
215 getEpSquare(moveOrSquare
) {
216 if (!moveOrSquare
) return undefined;
217 if (typeof moveOrSquare
=== "string") {
218 const square
= moveOrSquare
;
219 if (square
== "-") return undefined;
220 return V
.SquareToCoords(square
);
222 // Argument is a move:
223 const move = moveOrSquare
;
224 const s
= move.start
,
228 Math
.abs(s
.x
- e
.x
) == 2 &&
229 // Next conditions for variants like Atomic or Rifle, Recycle...
230 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
231 (move.vanish
.length
> 0 && move.vanish
[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
372 const format
= (count
) => {
373 // if more than 9 consecutive free spaces, break the integer,
374 // otherwise FEN parsing will fail.
375 if (count
<= 9) return count
;
376 // Currently only boards of size up to 11 or 12:
377 return "9" + (count
- 9);
380 for (let i
= 0; i
< V
.size
.x
; i
++) {
382 for (let j
= 0; j
< V
.size
.y
; j
++) {
383 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
385 if (emptyCount
> 0) {
386 // Add empty squares in-between
387 position
+= format(emptyCount
);
390 position
+= V
.board2fen(this.board
[i
][j
]);
393 if (emptyCount
> 0) {
395 position
+= format(emptyCount
);
397 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
406 // Flags part of the FEN string
410 for (let c
of ["w", "b"])
411 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
415 // Enpassant part of the FEN string
417 const L
= this.epSquares
.length
;
418 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
419 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
422 // Turn position fen into double array ["wb","wp","bk",...]
423 static GetBoard(position
) {
424 const rows
= position
.split("/");
425 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
426 for (let i
= 0; i
< rows
.length
; i
++) {
428 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
429 const character
= rows
[i
][indexInRow
];
430 const num
= parseInt(character
);
431 // If num is a number, just shift j:
432 if (!isNaN(num
)) j
+= num
;
433 // Else: something at position i,j
434 else board
[i
][j
++] = V
.fen2board(character
);
440 // Extract (relevant) flags from fen
442 // white a-castle, h-castle, black a-castle, h-castle
443 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
444 for (let i
= 0; i
< 4; i
++) {
445 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
446 V
.ColumnToCoord(fenflags
.charAt(i
));
453 // Fen string fully describes the game state
456 // In printDiagram() fen isn't supply because only getPpath() is used
457 // TODO: find a better solution!
459 const fenParsed
= V
.ParseFen(fen
);
460 this.board
= V
.GetBoard(fenParsed
.position
);
461 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
462 this.movesCount
= parseInt(fenParsed
.movesCount
);
463 this.setOtherVariables(fen
);
466 // Scan board for kings positions
468 this.INIT_COL_KING
= { w: -1, b: -1 };
469 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
470 const fenRows
= V
.ParseFen(fen
).position
.split("/");
471 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
472 for (let i
= 0; i
< fenRows
.length
; i
++) {
473 let k
= 0; //column index on board
474 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
475 switch (fenRows
[i
].charAt(j
)) {
477 this.kingPos
["b"] = [i
, k
];
478 this.INIT_COL_KING
["b"] = k
;
481 this.kingPos
["w"] = [i
, k
];
482 this.INIT_COL_KING
["w"] = k
;
485 const num
= parseInt(fenRows
[i
].charAt(j
));
486 if (!isNaN(num
)) k
+= num
- 1;
494 // Some additional variables from FEN (variant dependant)
495 setOtherVariables(fen
) {
496 // Set flags and enpassant:
497 const parsedFen
= V
.ParseFen(fen
);
498 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
499 if (V
.HasEnpassant
) {
501 parsedFen
.enpassant
!= "-"
502 ? this.getEpSquare(parsedFen
.enpassant
)
504 this.epSquares
= [epSq
];
506 // Search for kings positions:
510 /////////////////////
514 return { x: 8, y: 8 };
517 // Color of thing on square (i,j). 'undefined' if square is empty
519 return this.board
[i
][j
].charAt(0);
522 // Piece type on square (i,j). 'undefined' if square is empty
524 return this.board
[i
][j
].charAt(1);
527 // Get opponent color
528 static GetOppCol(color
) {
529 return color
== "w" ? "b" : "w";
532 // Pieces codes (for a clearer code)
539 static get KNIGHT() {
542 static get BISHOP() {
553 static get PIECES() {
554 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
562 // Some pieces movements
593 // All possible moves from selected square
594 getPotentialMovesFrom([x
, y
]) {
595 switch (this.getPiece(x
, y
)) {
597 return this.getPotentialPawnMoves([x
, y
]);
599 return this.getPotentialRookMoves([x
, y
]);
601 return this.getPotentialKnightMoves([x
, y
]);
603 return this.getPotentialBishopMoves([x
, y
]);
605 return this.getPotentialQueenMoves([x
, y
]);
607 return this.getPotentialKingMoves([x
, y
]);
609 return []; //never reached
612 // Build a regular move from its initial and destination squares.
613 // tr: transformation
614 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
615 const initColor
= this.getColor(sx
, sy
);
616 const initPiece
= this.getPiece(sx
, sy
);
622 c: tr
? tr
.c : initColor
,
623 p: tr
? tr
.p : initPiece
636 // The opponent piece disappears if we take it
637 if (this.board
[ex
][ey
] != V
.EMPTY
) {
642 c: this.getColor(ex
, ey
),
643 p: this.getPiece(ex
, ey
)
651 // Generic method to find possible moves of non-pawn pieces:
652 // "sliding or jumping"
653 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
655 outerLoop: for (let step
of steps
) {
658 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
659 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
660 if (oneStep
) continue outerLoop
;
664 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
665 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
670 // Special case of en-passant captures: treated separately
671 getEnpassantCaptures([x
, y
], shiftX
) {
672 const Lep
= this.epSquares
.length
;
673 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
674 let enpassantMove
= null;
677 epSquare
.x
== x
+ shiftX
&&
678 Math
.abs(epSquare
.y
- y
) == 1
680 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
681 enpassantMove
.vanish
.push({
684 // Captured piece is usually a pawn, but next line seems harmless
685 p: this.getPiece(x
, epSquare
.y
),
686 c: this.getColor(x
, epSquare
.y
)
689 return !!enpassantMove
? [enpassantMove
] : [];
692 // Consider all potential promotions:
693 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
694 let finalPieces
= [V
.PAWN
];
695 const color
= this.turn
;
696 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
697 if (x2
== lastRank
) {
698 // promotions arg: special override for Hiddenqueen variant
699 if (!!promotions
) finalPieces
= promotions
;
700 else if (!!V
.PawnSpecs
.promotions
)
701 finalPieces
= V
.PawnSpecs
.promotions
;
704 for (let piece
of finalPieces
) {
705 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
706 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
710 // What are the pawn moves from square x,y ?
711 getPotentialPawnMoves([x
, y
], promotions
) {
712 const color
= this.turn
;
713 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
714 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
715 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
716 const startRank
= (color
== "w" ? sizeX
- 2 : 1);
718 // Pawn movements in shiftX direction:
719 const getPawnMoves
= (shiftX
) => {
721 // NOTE: next condition is generally true (no pawn on last rank)
722 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
723 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
724 // One square forward
725 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
726 // Next condition because pawns on 1st rank can generally jump
728 V
.PawnSpecs
.twoSquares
&&
729 [startRank
, firstRank
].includes(x
) &&
730 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
733 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
737 if (V
.PawnSpecs
.canCapture
) {
738 for (let shiftY
of [-1, 1]) {
744 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
745 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
748 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
753 V
.PawnSpecs
.captureBackward
&&
754 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
755 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
756 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
759 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
770 let pMoves
= getPawnMoves(pawnShiftX
);
771 if (V
.PawnSpecs
.bidirectional
)
772 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
774 if (V
.HasEnpassant
) {
775 // NOTE: backward en-passant captures are not considered
776 // because no rules define them (for now).
777 Array
.prototype.push
.apply(
779 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
786 // What are the rook moves from square x,y ?
787 getPotentialRookMoves(sq
) {
788 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
791 // What are the knight moves from square x,y ?
792 getPotentialKnightMoves(sq
) {
793 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
796 // What are the bishop moves from square x,y ?
797 getPotentialBishopMoves(sq
) {
798 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
801 // What are the queen moves from square x,y ?
802 getPotentialQueenMoves(sq
) {
803 return this.getSlideNJumpMoves(
805 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
809 // What are the king moves from square x,y ?
810 getPotentialKingMoves(sq
) {
811 // Initialize with normal moves
812 let moves
= this.getSlideNJumpMoves(
814 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
817 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
821 // "castleInCheck" arg to let some variants castle under check
822 getCastleMoves([x
, y
], castleInCheck
) {
823 const c
= this.getColor(x
, y
);
824 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
825 return []; //x isn't first rank, or king has moved (shortcut)
828 const oppCol
= V
.GetOppCol(c
);
832 const finalSquares
= [
834 [V
.size
.y
- 2, V
.size
.y
- 3]
839 castleSide
++ //large, then small
841 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
842 // If this code is reached, rook and king are on initial position
844 // NOTE: in some variants this is not a rook, but let's keep variable name
845 const rookPos
= this.castleFlags
[c
][castleSide
];
846 const castlingPiece
= this.getPiece(x
, rookPos
);
847 if (this.getColor(x
, rookPos
) != c
)
848 // Rook is here but changed color (see Benedict)
851 // Nothing on the path of the king ? (and no checks)
852 const finDist
= finalSquares
[castleSide
][0] - y
;
853 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
857 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
858 (this.board
[x
][i
] != V
.EMPTY
&&
859 // NOTE: next check is enough, because of chessboard constraints
860 (this.getColor(x
, i
) != c
||
861 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
863 continue castlingCheck
;
866 } while (i
!= finalSquares
[castleSide
][0]);
868 // Nothing on the path to the rook?
869 step
= castleSide
== 0 ? -1 : 1;
870 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
871 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
874 // Nothing on final squares, except maybe king and castling rook?
875 for (i
= 0; i
< 2; i
++) {
877 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
878 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
879 finalSquares
[castleSide
][i
] != rookPos
881 continue castlingCheck
;
885 // If this code is reached, castle is valid
889 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
890 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: castlingPiece
, c: c
})
893 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
894 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
897 Math
.abs(y
- rookPos
) <= 2
898 ? { x: x
, y: rookPos
}
899 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
910 // For the interface: possible moves for the current turn from square sq
911 getPossibleMovesFrom(sq
) {
912 return this.filterValid(this.getPotentialMovesFrom(sq
));
915 // TODO: promotions (into R,B,N,Q) should be filtered only once
917 if (moves
.length
== 0) return [];
918 const color
= this.turn
;
919 return moves
.filter(m
=> {
921 const res
= !this.underCheck(color
);
927 // Search for all valid moves considering current turn
928 // (for engine and game end)
930 const color
= this.turn
;
931 let potentialMoves
= [];
932 for (let i
= 0; i
< V
.size
.x
; i
++) {
933 for (let j
= 0; j
< V
.size
.y
; j
++) {
934 if (this.getColor(i
, j
) == color
) {
935 Array
.prototype.push
.apply(
937 this.getPotentialMovesFrom([i
, j
])
942 return this.filterValid(potentialMoves
);
945 // Stop at the first move found
946 // TODO: not really, it explores all moves from a square but one would suffice.
948 const color
= this.turn
;
949 for (let i
= 0; i
< V
.size
.x
; i
++) {
950 for (let j
= 0; j
< V
.size
.y
; j
++) {
951 if (this.getColor(i
, j
) == color
) {
952 const moves
= this.getPotentialMovesFrom([i
, j
]);
953 if (moves
.length
> 0) {
954 for (let k
= 0; k
< moves
.length
; k
++) {
955 if (this.filterValid([moves
[k
]]).length
> 0) return true;
964 // Check if pieces of given color are attacking (king) on square x,y
965 isAttacked(sq
, color
) {
967 this.isAttackedByPawn(sq
, color
) ||
968 this.isAttackedByRook(sq
, color
) ||
969 this.isAttackedByKnight(sq
, color
) ||
970 this.isAttackedByBishop(sq
, color
) ||
971 this.isAttackedByQueen(sq
, color
) ||
972 this.isAttackedByKing(sq
, color
)
976 // Generic method for non-pawn pieces ("sliding or jumping"):
977 // is x,y attacked by a piece of given color ?
978 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
979 for (let step
of steps
) {
980 let rx
= x
+ step
[0],
982 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
988 this.getPiece(rx
, ry
) == piece
&&
989 this.getColor(rx
, ry
) == color
997 // Is square x,y attacked by 'color' pawns ?
998 isAttackedByPawn([x
, y
], color
) {
999 const pawnShift
= (color
== "w" ? 1 : -1);
1000 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
1001 for (let i
of [-1, 1]) {
1005 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
1006 this.getColor(x
+ pawnShift
, y
+ i
) == color
1015 // Is square x,y attacked by 'color' rooks ?
1016 isAttackedByRook(sq
, color
) {
1017 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1020 // Is square x,y attacked by 'color' knights ?
1021 isAttackedByKnight(sq
, color
) {
1022 return this.isAttackedBySlideNJump(
1031 // Is square x,y attacked by 'color' bishops ?
1032 isAttackedByBishop(sq
, color
) {
1033 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1036 // Is square x,y attacked by 'color' queens ?
1037 isAttackedByQueen(sq
, color
) {
1038 return this.isAttackedBySlideNJump(
1042 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1046 // Is square x,y attacked by 'color' king(s) ?
1047 isAttackedByKing(sq
, color
) {
1048 return this.isAttackedBySlideNJump(
1052 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1057 // Is color under check after his move ?
1059 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1065 // Apply a move on board
1066 static PlayOnBoard(board
, move) {
1067 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1068 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1070 // Un-apply the played move
1071 static UndoOnBoard(board
, move) {
1072 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1073 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1080 // if (!this.states) this.states = [];
1081 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1082 // this.states.push(stateFen);
1085 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1086 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1087 V
.PlayOnBoard(this.board
, move);
1088 this.turn
= V
.GetOppCol(this.turn
);
1090 this.postPlay(move);
1093 updateCastleFlags(move, piece
) {
1094 const c
= V
.GetOppCol(this.turn
);
1095 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1096 // Update castling flags if rooks are moved
1097 const oppCol
= V
.GetOppCol(c
);
1098 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1099 if (piece
== V
.KING
&& move.appear
.length
> 0)
1100 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1102 move.start
.x
== firstRank
&& //our rook moves?
1103 this.castleFlags
[c
].includes(move.start
.y
)
1105 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1106 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1108 // NOTE: not "else if" because a rook could take an opposing rook
1110 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1111 this.castleFlags
[oppCol
].includes(move.end
.y
)
1113 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1114 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1118 // After move is played, update variables + flags
1120 const c
= V
.GetOppCol(this.turn
);
1121 let piece
= undefined;
1122 if (move.vanish
.length
>= 1)
1123 // Usual case, something is moved
1124 piece
= move.vanish
[0].p
;
1126 // Crazyhouse-like variants
1127 piece
= move.appear
[0].p
;
1129 // Update king position + flags
1130 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1131 this.kingPos
[c
][0] = move.appear
[0].x
;
1132 this.kingPos
[c
][1] = move.appear
[0].y
;
1135 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1142 if (V
.HasEnpassant
) this.epSquares
.pop();
1143 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1144 V
.UndoOnBoard(this.board
, move);
1145 this.turn
= V
.GetOppCol(this.turn
);
1147 this.postUndo(move);
1150 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1151 // if (stateFen != this.states[this.states.length-1]) debugger;
1152 // this.states.pop();
1155 // After move is undo-ed *and flags resetted*, un-update other variables
1156 // TODO: more symmetry, by storing flags increment in move (?!)
1158 // (Potentially) Reset king position
1159 const c
= this.getColor(move.start
.x
, move.start
.y
);
1160 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1161 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1167 // What is the score ? (Interesting if game is over)
1169 if (this.atLeastOneMove()) return "*";
1171 const color
= this.turn
;
1172 // No valid move: stalemate or checkmate?
1173 if (!this.underCheck(color
)) return "1/2";
1175 return (color
== "w" ? "0-1" : "1-0");
1182 static get VALUES() {
1193 // "Checkmate" (unreachable eval)
1194 static get INFINITY() {
1198 // At this value or above, the game is over
1199 static get THRESHOLD_MATE() {
1203 // Search depth: 1,2 for high branching factor, 4 for small (Loser chess, eg.)
1204 static get SEARCH_DEPTH() {
1209 const maxeval
= V
.INFINITY
;
1210 const color
= this.turn
;
1211 let moves1
= this.getAllValidMoves();
1213 if (moves1
.length
== 0)
1214 // TODO: this situation should not happen
1217 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1218 for (let i
= 0; i
< moves1
.length
; i
++) {
1219 this.play(moves1
[i
]);
1220 const score1
= this.getCurrentScore();
1221 if (score1
!= "*") {
1225 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1227 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1228 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1229 this.undo(moves1
[i
]);
1232 // Initial self evaluation is very low: "I'm checkmated"
1233 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1234 // Initial enemy evaluation is very low too, for him
1235 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1236 // Second half-move:
1237 let moves2
= this.getAllValidMoves();
1238 for (let j
= 0; j
< moves2
.length
; j
++) {
1239 this.play(moves2
[j
]);
1240 const score2
= this.getCurrentScore();
1241 let evalPos
= 0; //1/2 value
1244 evalPos
= this.evalPosition();
1254 (color
== "w" && evalPos
< eval2
) ||
1255 (color
== "b" && evalPos
> eval2
)
1259 this.undo(moves2
[j
]);
1262 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1263 (color
== "b" && eval2
< moves1
[i
].eval
)
1265 moves1
[i
].eval
= eval2
;
1267 this.undo(moves1
[i
]);
1269 moves1
.sort((a
, b
) => {
1270 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1272 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1274 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1275 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1276 for (let i
= 0; i
< moves1
.length
; i
++) {
1277 this.play(moves1
[i
]);
1278 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1280 0.1 * moves1
[i
].eval
+
1281 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1282 this.undo(moves1
[i
]);
1284 moves1
.sort((a
, b
) => {
1285 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1289 let candidates
= [0];
1290 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1292 return moves1
[candidates
[randInt(candidates
.length
)]];
1295 alphabeta(depth
, alpha
, beta
) {
1296 const maxeval
= V
.INFINITY
;
1297 const color
= this.turn
;
1298 const score
= this.getCurrentScore();
1300 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1301 if (depth
== 0) return this.evalPosition();
1302 const moves
= this.getAllValidMoves();
1303 let v
= color
== "w" ? -maxeval : maxeval
;
1305 for (let i
= 0; i
< moves
.length
; i
++) {
1306 this.play(moves
[i
]);
1307 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1308 this.undo(moves
[i
]);
1309 alpha
= Math
.max(alpha
, v
);
1310 if (alpha
>= beta
) break; //beta cutoff
1315 for (let i
= 0; i
< moves
.length
; i
++) {
1316 this.play(moves
[i
]);
1317 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1318 this.undo(moves
[i
]);
1319 beta
= Math
.min(beta
, v
);
1320 if (alpha
>= beta
) break; //alpha cutoff
1328 // Just count material for now
1329 for (let i
= 0; i
< V
.size
.x
; i
++) {
1330 for (let j
= 0; j
< V
.size
.y
; j
++) {
1331 if (this.board
[i
][j
] != V
.EMPTY
) {
1332 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1333 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1340 /////////////////////////
1341 // MOVES + GAME NOTATION
1342 /////////////////////////
1344 // Context: just before move is played, turn hasn't changed
1345 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1347 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1349 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1351 // Translate final square
1352 const finalSquare
= V
.CoordsToSquare(move.end
);
1354 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1355 if (piece
== V
.PAWN
) {
1358 if (move.vanish
.length
> move.appear
.length
) {
1360 const startColumn
= V
.CoordToColumn(move.start
.y
);
1361 notation
= startColumn
+ "x" + finalSquare
;
1363 else notation
= finalSquare
;
1364 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1366 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1371 piece
.toUpperCase() +
1372 (move.vanish
.length
> move.appear
.length
? "x" : "") +