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 // Some variants don't have en-passant
46 static get HasEnpassant() {
50 // Some variants cannot have analyse mode
51 static get CanAnalyze() {
54 // Patch: issues with javascript OOP, objects can't access static fields.
59 // Some variants show incomplete information,
60 // and thus show only a partial moves list or no list at all.
61 static get ShowMoves() {
68 // Some variants always show the same orientation
69 static get CanFlip() {
76 static get IMAGE_EXTENSION() {
77 // All pieces should be in the SVG format
81 // Turn "wb" into "B" (for FEN)
83 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
86 // Turn "p" into "bp" (for board)
88 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
91 // Check if FEN describe a board situation correctly
92 static IsGoodFen(fen
) {
93 const fenParsed
= V
.ParseFen(fen
);
95 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
97 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
98 // 3) Check moves count
99 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
102 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
104 // 5) Check enpassant
107 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
114 // Is position part of the FEN a priori correct?
115 static IsGoodPosition(position
) {
116 if (position
.length
== 0) return false;
117 const rows
= position
.split("/");
118 if (rows
.length
!= V
.size
.x
) return false;
120 for (let row
of rows
) {
122 for (let i
= 0; i
< row
.length
; i
++) {
123 if (['K','k'].includes(row
[i
]))
124 kings
[row
[i
]] = true;
125 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
127 const num
= parseInt(row
[i
]);
128 if (isNaN(num
)) return false;
132 if (sumElts
!= V
.size
.y
) return false;
134 // Both kings should be on board:
135 if (Object
.keys(kings
).length
!= 2)
141 static IsGoodTurn(turn
) {
142 return ["w", "b"].includes(turn
);
146 static IsGoodFlags(flags
) {
147 // NOTE: a little too permissive to work with more variants
148 return !!flags
.match(/^[a-z]{4,4}$/);
151 static IsGoodEnpassant(enpassant
) {
152 if (enpassant
!= "-") {
153 const ep
= V
.SquareToCoords(enpassant
);
154 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
159 // 3 --> d (column number to letter)
160 static CoordToColumn(colnum
) {
161 return String
.fromCharCode(97 + colnum
);
164 // d --> 3 (column letter to number)
165 static ColumnToCoord(column
) {
166 return column
.charCodeAt(0) - 97;
170 static SquareToCoords(sq
) {
172 // NOTE: column is always one char => max 26 columns
173 // row is counted from black side => subtraction
174 x: V
.size
.x
- parseInt(sq
.substr(1)),
175 y: sq
[0].charCodeAt() - 97
180 static CoordsToSquare(coords
) {
181 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
186 return b
; //usual pieces in pieces/ folder
189 // Path to promotion pieces (usually the same)
191 return this.getPpath(b
);
194 // Aggregates flags into one object
196 return this.castleFlags
;
200 disaggregateFlags(flags
) {
201 this.castleFlags
= flags
;
204 // En-passant square, if any
205 getEpSquare(moveOrSquare
) {
206 if (!moveOrSquare
) return undefined;
207 if (typeof moveOrSquare
=== "string") {
208 const square
= moveOrSquare
;
209 if (square
== "-") return undefined;
210 return V
.SquareToCoords(square
);
212 // Argument is a move:
213 const move = moveOrSquare
;
214 const s
= move.start
,
217 Math
.abs(s
.x
- e
.x
) == 2 &&
219 move.appear
[0].p
== V
.PAWN
226 return undefined; //default
229 // Can thing on square1 take thing on square2
230 canTake([x1
, y1
], [x2
, y2
]) {
231 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
234 // Is (x,y) on the chessboard?
235 static OnBoard(x
, y
) {
236 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
239 // Used in interface: 'side' arg == player color
240 canIplay(side
, [x
, y
]) {
241 return this.turn
== side
&& this.getColor(x
, y
) == side
;
244 // On which squares is color under check ? (for interface)
245 getCheckSquares(color
) {
247 this.underCheck(color
)
248 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
256 // Setup the initial random (asymmetric) position
257 static GenRandInitFen(randomness
) {
260 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
262 let pieces
= { w: new Array(8), b: new Array(8) };
264 // Shuffle pieces on first (and last rank if randomness == 2)
265 for (let c
of ["w", "b"]) {
266 if (c
== 'b' && randomness
== 1) {
267 pieces
['b'] = pieces
['w'];
272 let positions
= ArrayFun
.range(8);
274 // Get random squares for bishops
275 let randIndex
= 2 * randInt(4);
276 const bishop1Pos
= positions
[randIndex
];
277 // The second bishop must be on a square of different color
278 let randIndex_tmp
= 2 * randInt(4) + 1;
279 const bishop2Pos
= positions
[randIndex_tmp
];
280 // Remove chosen squares
281 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
282 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
284 // Get random squares for knights
285 randIndex
= randInt(6);
286 const knight1Pos
= positions
[randIndex
];
287 positions
.splice(randIndex
, 1);
288 randIndex
= randInt(5);
289 const knight2Pos
= positions
[randIndex
];
290 positions
.splice(randIndex
, 1);
292 // Get random square for queen
293 randIndex
= randInt(4);
294 const queenPos
= positions
[randIndex
];
295 positions
.splice(randIndex
, 1);
297 // Rooks and king positions are now fixed,
298 // because of the ordering rook-king-rook
299 const rook1Pos
= positions
[0];
300 const kingPos
= positions
[1];
301 const rook2Pos
= positions
[2];
303 // Finally put the shuffled pieces in the board array
304 pieces
[c
][rook1Pos
] = "r";
305 pieces
[c
][knight1Pos
] = "n";
306 pieces
[c
][bishop1Pos
] = "b";
307 pieces
[c
][queenPos
] = "q";
308 pieces
[c
][kingPos
] = "k";
309 pieces
[c
][bishop2Pos
] = "b";
310 pieces
[c
][knight2Pos
] = "n";
311 pieces
[c
][rook2Pos
] = "r";
312 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
314 // Add turn + flags + enpassant
316 pieces
["b"].join("") +
317 "/pppppppp/8/8/8/8/PPPPPPPP/" +
318 pieces
["w"].join("").toUpperCase() +
319 " w 0 " + flags
+ " -"
323 // "Parse" FEN: just return untransformed string data
324 static ParseFen(fen
) {
325 const fenParts
= fen
.split(" ");
327 position: fenParts
[0],
329 movesCount: fenParts
[2]
332 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
333 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
337 // Return current fen (game state)
340 this.getBaseFen() + " " +
341 this.getTurnFen() + " " +
343 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
344 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
349 // Omit movesCount, only variable allowed to differ
351 this.getBaseFen() + "_" +
353 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
354 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
358 // Position part of the FEN string
361 for (let i
= 0; i
< V
.size
.x
; i
++) {
363 for (let j
= 0; j
< V
.size
.y
; j
++) {
364 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
366 if (emptyCount
> 0) {
367 // Add empty squares in-between
368 position
+= emptyCount
;
371 position
+= V
.board2fen(this.board
[i
][j
]);
374 if (emptyCount
> 0) {
376 position
+= emptyCount
;
378 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
387 // Flags part of the FEN string
391 for (let c
of ["w", "b"])
392 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
396 // Enpassant part of the FEN string
398 const L
= this.epSquares
.length
;
399 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
400 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
403 // Turn position fen into double array ["wb","wp","bk",...]
404 static GetBoard(position
) {
405 const rows
= position
.split("/");
406 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
407 for (let i
= 0; i
< rows
.length
; i
++) {
409 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
410 const character
= rows
[i
][indexInRow
];
411 const num
= parseInt(character
);
412 // If num is a number, just shift j:
413 if (!isNaN(num
)) j
+= num
;
414 // Else: something at position i,j
415 else board
[i
][j
++] = V
.fen2board(character
);
421 // Extract (relevant) flags from fen
423 // white a-castle, h-castle, black a-castle, h-castle
424 this.castleFlags
= { w: [true, true], b: [true, true] };
425 for (let i
= 0; i
< 4; i
++) {
426 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
427 V
.ColumnToCoord(fenflags
.charAt(i
));
434 // Fen string fully describes the game state
437 // In printDiagram() fen isn't supply because only getPpath() is used
438 // TODO: find a better solution!
440 const fenParsed
= V
.ParseFen(fen
);
441 this.board
= V
.GetBoard(fenParsed
.position
);
442 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
443 this.movesCount
= parseInt(fenParsed
.movesCount
);
444 this.setOtherVariables(fen
);
447 // Scan board for kings positions
449 this.INIT_COL_KING
= { w: -1, b: -1 };
450 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
451 const fenRows
= V
.ParseFen(fen
).position
.split("/");
452 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
453 for (let i
= 0; i
< fenRows
.length
; i
++) {
454 let k
= 0; //column index on board
455 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
456 switch (fenRows
[i
].charAt(j
)) {
458 this.kingPos
["b"] = [i
, k
];
459 this.INIT_COL_KING
["b"] = k
;
462 this.kingPos
["w"] = [i
, k
];
463 this.INIT_COL_KING
["w"] = k
;
466 const num
= parseInt(fenRows
[i
].charAt(j
));
467 if (!isNaN(num
)) k
+= num
- 1;
475 // Some additional variables from FEN (variant dependant)
476 setOtherVariables(fen
) {
477 // Set flags and enpassant:
478 const parsedFen
= V
.ParseFen(fen
);
479 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
480 if (V
.HasEnpassant
) {
482 parsedFen
.enpassant
!= "-"
483 ? this.getEpSquare(parsedFen
.enpassant
)
485 this.epSquares
= [epSq
];
487 // Search for kings positions:
491 /////////////////////
495 return { x: 8, y: 8 };
498 // Color of thing on square (i,j). 'undefined' if square is empty
500 return this.board
[i
][j
].charAt(0);
503 // Piece type on square (i,j). 'undefined' if square is empty
505 return this.board
[i
][j
].charAt(1);
508 // Get opponent color
509 static GetOppCol(color
) {
510 return color
== "w" ? "b" : "w";
513 // Pieces codes (for a clearer code)
520 static get KNIGHT() {
523 static get BISHOP() {
534 static get PIECES() {
535 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
543 // Some pieces movements
574 // All possible moves from selected square
575 getPotentialMovesFrom([x
, y
]) {
576 switch (this.getPiece(x
, y
)) {
578 return this.getPotentialPawnMoves([x
, y
]);
580 return this.getPotentialRookMoves([x
, y
]);
582 return this.getPotentialKnightMoves([x
, y
]);
584 return this.getPotentialBishopMoves([x
, y
]);
586 return this.getPotentialQueenMoves([x
, y
]);
588 return this.getPotentialKingMoves([x
, y
]);
590 return []; //never reached
593 // Build a regular move from its initial and destination squares.
594 // tr: transformation
595 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
601 c: tr
? tr
.c : this.getColor(sx
, sy
),
602 p: tr
? tr
.p : this.getPiece(sx
, sy
)
609 c: this.getColor(sx
, sy
),
610 p: this.getPiece(sx
, sy
)
615 // The opponent piece disappears if we take it
616 if (this.board
[ex
][ey
] != V
.EMPTY
) {
621 c: this.getColor(ex
, ey
),
622 p: this.getPiece(ex
, ey
)
630 // Generic method to find possible moves of non-pawn pieces:
631 // "sliding or jumping"
632 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
634 outerLoop: for (let step
of steps
) {
637 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
638 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
639 if (oneStep
) continue outerLoop
;
643 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
644 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
649 // What are the pawn moves from square x,y ?
650 getPotentialPawnMoves([x
, y
]) {
651 const color
= this.turn
;
653 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
654 const shiftX
= color
== "w" ? -1 : 1;
655 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
656 const startRank
= color
== "w" ? sizeX
- 2 : 1;
657 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
659 // NOTE: next condition is generally true (no pawn on last rank)
660 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
662 x
+ shiftX
== lastRank
663 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
665 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
666 // One square forward
667 for (let piece
of finalPieces
) {
669 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
675 // Next condition because pawns on 1st rank can generally jump
677 [startRank
, firstRank
].includes(x
) &&
678 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
681 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
685 for (let shiftY
of [-1, 1]) {
688 y
+ shiftY
< sizeY
&&
689 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
690 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
692 for (let piece
of finalPieces
) {
694 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
704 if (V
.HasEnpassant
) {
706 const Lep
= this.epSquares
.length
;
707 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
710 epSquare
.x
== x
+ shiftX
&&
711 Math
.abs(epSquare
.y
- y
) == 1
713 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
714 enpassantMove
.vanish
.push({
718 c: this.getColor(x
, epSquare
.y
)
720 moves
.push(enpassantMove
);
727 // What are the rook moves from square x,y ?
728 getPotentialRookMoves(sq
) {
729 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
732 // What are the knight moves from square x,y ?
733 getPotentialKnightMoves(sq
) {
734 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
737 // What are the bishop moves from square x,y ?
738 getPotentialBishopMoves(sq
) {
739 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
742 // What are the queen moves from square x,y ?
743 getPotentialQueenMoves(sq
) {
744 return this.getSlideNJumpMoves(
746 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
750 // What are the king moves from square x,y ?
751 getPotentialKingMoves(sq
) {
752 // Initialize with normal moves
753 const moves
= this.getSlideNJumpMoves(
755 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
758 return moves
.concat(this.getCastleMoves(sq
));
761 getCastleMoves([x
, y
]) {
762 const c
= this.getColor(x
, y
);
763 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
764 return []; //x isn't first rank, or king has moved (shortcut)
767 const oppCol
= V
.GetOppCol(c
);
771 const finalSquares
= [
773 [V
.size
.y
- 2, V
.size
.y
- 3]
778 castleSide
++ //large, then small
780 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
781 // If this code is reached, rooks and king are on initial position
783 // Nothing on the path of the king ? (and no checks)
784 const finDist
= finalSquares
[castleSide
][0] - y
;
785 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
789 this.isAttacked([x
, i
], [oppCol
]) ||
790 (this.board
[x
][i
] != V
.EMPTY
&&
791 // NOTE: next check is enough, because of chessboard constraints
792 (this.getColor(x
, i
) != c
||
793 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
795 continue castlingCheck
;
798 } while (i
!= finalSquares
[castleSide
][0]);
800 // Nothing on the path to the rook?
801 step
= castleSide
== 0 ? -1 : 1;
802 const rookPos
= this.castleFlags
[c
][castleSide
];
803 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
804 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
807 // Nothing on final squares, except maybe king and castling rook?
808 for (i
= 0; i
< 2; i
++) {
810 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
811 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
812 finalSquares
[castleSide
][i
] != rookPos
814 continue castlingCheck
;
818 // If this code is reached, castle is valid
822 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
823 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
826 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
827 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
830 Math
.abs(y
- rookPos
) <= 2
831 ? { x: x
, y: rookPos
}
832 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
843 // For the interface: possible moves for the current turn from square sq
844 getPossibleMovesFrom(sq
) {
845 return this.filterValid(this.getPotentialMovesFrom(sq
));
848 // TODO: promotions (into R,B,N,Q) should be filtered only once
850 if (moves
.length
== 0) return [];
851 const color
= this.turn
;
852 return moves
.filter(m
=> {
854 const res
= !this.underCheck(color
);
860 // Search for all valid moves considering current turn
861 // (for engine and game end)
863 const color
= this.turn
;
864 let potentialMoves
= [];
865 for (let i
= 0; i
< V
.size
.x
; i
++) {
866 for (let j
= 0; j
< V
.size
.y
; j
++) {
867 if (this.getColor(i
, j
) == color
) {
868 Array
.prototype.push
.apply(
870 this.getPotentialMovesFrom([i
, j
])
875 return this.filterValid(potentialMoves
);
878 // Stop at the first move found
880 const color
= this.turn
;
881 for (let i
= 0; i
< V
.size
.x
; i
++) {
882 for (let j
= 0; j
< V
.size
.y
; j
++) {
883 if (this.getColor(i
, j
) == color
) {
884 const moves
= this.getPotentialMovesFrom([i
, j
]);
885 if (moves
.length
> 0) {
886 for (let k
= 0; k
< moves
.length
; k
++) {
887 if (this.filterValid([moves
[k
]]).length
> 0) return true;
896 // Check if pieces of color in 'colors' are attacking (king) on square x,y
897 isAttacked(sq
, colors
) {
899 this.isAttackedByPawn(sq
, colors
) ||
900 this.isAttackedByRook(sq
, colors
) ||
901 this.isAttackedByKnight(sq
, colors
) ||
902 this.isAttackedByBishop(sq
, colors
) ||
903 this.isAttackedByQueen(sq
, colors
) ||
904 this.isAttackedByKing(sq
, colors
)
908 // Generic method for non-pawn pieces ("sliding or jumping"):
909 // is x,y attacked by a piece of color in array 'colors' ?
910 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
911 for (let step
of steps
) {
912 let rx
= x
+ step
[0],
914 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
920 this.getPiece(rx
, ry
) === piece
&&
921 colors
.includes(this.getColor(rx
, ry
))
929 // Is square x,y attacked by 'colors' pawns ?
930 isAttackedByPawn([x
, y
], colors
) {
931 for (let c
of colors
) {
932 const pawnShift
= c
== "w" ? 1 : -1;
933 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
934 for (let i
of [-1, 1]) {
938 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
939 this.getColor(x
+ pawnShift
, y
+ i
) == c
949 // Is square x,y attacked by 'colors' rooks ?
950 isAttackedByRook(sq
, colors
) {
951 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
954 // Is square x,y attacked by 'colors' knights ?
955 isAttackedByKnight(sq
, colors
) {
956 return this.isAttackedBySlideNJump(
965 // Is square x,y attacked by 'colors' bishops ?
966 isAttackedByBishop(sq
, colors
) {
967 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
970 // Is square x,y attacked by 'colors' queens ?
971 isAttackedByQueen(sq
, colors
) {
972 return this.isAttackedBySlideNJump(
976 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
980 // Is square x,y attacked by 'colors' king(s) ?
981 isAttackedByKing(sq
, colors
) {
982 return this.isAttackedBySlideNJump(
986 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
991 // Is color under check after his move ?
993 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
999 // Apply a move on board
1000 static PlayOnBoard(board
, move) {
1001 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1002 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1004 // Un-apply the played move
1005 static UndoOnBoard(board
, move) {
1006 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1007 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1014 // if (!this.states) this.states = [];
1015 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1016 // this.states.push(stateFen);
1019 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1020 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1021 V
.PlayOnBoard(this.board
, move);
1022 this.turn
= V
.GetOppCol(this.turn
);
1024 this.postPlay(move);
1027 // After move is played, update variables + flags
1029 const c
= V
.GetOppCol(this.turn
);
1030 let piece
= undefined;
1031 if (move.vanish
.length
>= 1)
1032 // Usual case, something is moved
1033 piece
= move.vanish
[0].p
;
1035 // Crazyhouse-like variants
1036 piece
= move.appear
[0].p
;
1037 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1039 // Update king position + flags
1040 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1041 this.kingPos
[c
][0] = move.appear
[0].x
;
1042 this.kingPos
[c
][1] = move.appear
[0].y
;
1043 if (V
.HasCastle
) this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1047 // Update castling flags if rooks are moved
1048 const oppCol
= V
.GetOppCol(c
);
1049 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1051 move.start
.x
== firstRank
&& //our rook moves?
1052 this.castleFlags
[c
].includes(move.start
.y
)
1054 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1055 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1057 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1058 this.castleFlags
[oppCol
].includes(move.end
.y
)
1060 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1061 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1070 if (V
.HasEnpassant
) this.epSquares
.pop();
1071 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1072 V
.UndoOnBoard(this.board
, move);
1073 this.turn
= V
.GetOppCol(this.turn
);
1075 this.postUndo(move);
1078 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1079 // if (stateFen != this.states[this.states.length-1]) debugger;
1080 // this.states.pop();
1083 // After move is undo-ed *and flags resetted*, un-update other variables
1084 // TODO: more symmetry, by storing flags increment in move (?!)
1086 // (Potentially) Reset king position
1087 const c
= this.getColor(move.start
.x
, move.start
.y
);
1088 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1089 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1095 // What is the score ? (Interesting if game is over)
1097 if (this.atLeastOneMove())
1101 const color
= this.turn
;
1102 // No valid move: stalemate or checkmate?
1103 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1106 return color
== "w" ? "0-1" : "1-0";
1113 static get VALUES() {
1124 // "Checkmate" (unreachable eval)
1125 static get INFINITY() {
1129 // At this value or above, the game is over
1130 static get THRESHOLD_MATE() {
1134 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1135 static get SEARCH_DEPTH() {
1140 const maxeval
= V
.INFINITY
;
1141 const color
= this.turn
;
1142 let moves1
= this.getAllValidMoves();
1144 if (moves1
.length
== 0)
1145 // TODO: this situation should not happen
1148 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1149 for (let i
= 0; i
< moves1
.length
; i
++) {
1150 this.play(moves1
[i
]);
1151 const score1
= this.getCurrentScore();
1152 if (score1
!= "*") {
1156 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1158 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1159 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1160 this.undo(moves1
[i
]);
1163 // Initial self evaluation is very low: "I'm checkmated"
1164 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1165 // Initial enemy evaluation is very low too, for him
1166 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1167 // Second half-move:
1168 let moves2
= this.getAllValidMoves();
1169 for (let j
= 0; j
< moves2
.length
; j
++) {
1170 this.play(moves2
[j
]);
1171 const score2
= this.getCurrentScore();
1172 let evalPos
= 0; //1/2 value
1175 evalPos
= this.evalPosition();
1185 (color
== "w" && evalPos
< eval2
) ||
1186 (color
== "b" && evalPos
> eval2
)
1190 this.undo(moves2
[j
]);
1193 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1194 (color
== "b" && eval2
< moves1
[i
].eval
)
1196 moves1
[i
].eval
= eval2
;
1198 this.undo(moves1
[i
]);
1200 moves1
.sort((a
, b
) => {
1201 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1203 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1205 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1206 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1207 for (let i
= 0; i
< moves1
.length
; i
++) {
1208 this.play(moves1
[i
]);
1209 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1211 0.1 * moves1
[i
].eval
+
1212 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1213 this.undo(moves1
[i
]);
1215 moves1
.sort((a
, b
) => {
1216 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1220 let candidates
= [0];
1221 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1223 return moves1
[candidates
[randInt(candidates
.length
)]];
1226 alphabeta(depth
, alpha
, beta
) {
1227 const maxeval
= V
.INFINITY
;
1228 const color
= this.turn
;
1229 const score
= this.getCurrentScore();
1231 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1232 if (depth
== 0) return this.evalPosition();
1233 const moves
= this.getAllValidMoves();
1234 let v
= color
== "w" ? -maxeval : maxeval
;
1236 for (let i
= 0; i
< moves
.length
; i
++) {
1237 this.play(moves
[i
]);
1238 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1239 this.undo(moves
[i
]);
1240 alpha
= Math
.max(alpha
, v
);
1241 if (alpha
>= beta
) break; //beta cutoff
1246 for (let i
= 0; i
< moves
.length
; i
++) {
1247 this.play(moves
[i
]);
1248 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1249 this.undo(moves
[i
]);
1250 beta
= Math
.min(beta
, v
);
1251 if (alpha
>= beta
) break; //alpha cutoff
1259 // Just count material for now
1260 for (let i
= 0; i
< V
.size
.x
; i
++) {
1261 for (let j
= 0; j
< V
.size
.y
; j
++) {
1262 if (this.board
[i
][j
] != V
.EMPTY
) {
1263 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1264 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1271 /////////////////////////
1272 // MOVES + GAME NOTATION
1273 /////////////////////////
1275 // Context: just before move is played, turn hasn't changed
1276 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1278 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1280 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1282 // Translate final square
1283 const finalSquare
= V
.CoordsToSquare(move.end
);
1285 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1286 if (piece
== V
.PAWN
) {
1289 if (move.vanish
.length
> move.appear
.length
) {
1291 const startColumn
= V
.CoordToColumn(move.start
.y
);
1292 notation
= startColumn
+ "x" + finalSquare
;
1294 else notation
= finalSquare
;
1295 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1297 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1302 piece
.toUpperCase() +
1303 (move.vanish
.length
> move.appear
.length
? "x" : "") +