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 // Turn "wb" into "B" (for FEN)
78 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
81 // Turn "p" into "bp" (for board)
83 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
86 // Check if FEN describe a board situation correctly
87 static IsGoodFen(fen
) {
88 const fenParsed
= V
.ParseFen(fen
);
90 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
92 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
93 // 3) Check moves count
94 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
97 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
102 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
109 // Is position part of the FEN a priori correct?
110 static IsGoodPosition(position
) {
111 if (position
.length
== 0) return false;
112 const rows
= position
.split("/");
113 if (rows
.length
!= V
.size
.x
) return false;
115 for (let row
of rows
) {
117 for (let i
= 0; i
< row
.length
; i
++) {
118 if (['K','k'].includes(row
[i
]))
119 kings
[row
[i
]] = true;
120 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
122 const num
= parseInt(row
[i
]);
123 if (isNaN(num
)) return false;
127 if (sumElts
!= V
.size
.y
) return false;
129 // Both kings should be on board:
130 if (Object
.keys(kings
).length
!= 2)
136 static IsGoodTurn(turn
) {
137 return ["w", "b"].includes(turn
);
141 static IsGoodFlags(flags
) {
142 // NOTE: a little too permissive to work with more variants
143 return !!flags
.match(/^[a-z]{4,4}$/);
146 static IsGoodEnpassant(enpassant
) {
147 if (enpassant
!= "-") {
148 const ep
= V
.SquareToCoords(enpassant
);
149 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
154 // 3 --> d (column number to letter)
155 static CoordToColumn(colnum
) {
156 return String
.fromCharCode(97 + colnum
);
159 // d --> 3 (column letter to number)
160 static ColumnToCoord(column
) {
161 return column
.charCodeAt(0) - 97;
165 static SquareToCoords(sq
) {
167 // NOTE: column is always one char => max 26 columns
168 // row is counted from black side => subtraction
169 x: V
.size
.x
- parseInt(sq
.substr(1)),
170 y: sq
[0].charCodeAt() - 97
175 static CoordsToSquare(coords
) {
176 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
181 return b
; //usual pieces in pieces/ folder
184 // Path to promotion pieces (usually the same)
186 return this.getPpath(b
);
189 // Aggregates flags into one object
191 return this.castleFlags
;
195 disaggregateFlags(flags
) {
196 this.castleFlags
= flags
;
199 // En-passant square, if any
200 getEpSquare(moveOrSquare
) {
201 if (!moveOrSquare
) return undefined;
202 if (typeof moveOrSquare
=== "string") {
203 const square
= moveOrSquare
;
204 if (square
== "-") return undefined;
205 return V
.SquareToCoords(square
);
207 // Argument is a move:
208 const move = moveOrSquare
;
209 const s
= move.start
,
212 Math
.abs(s
.x
- e
.x
) == 2 &&
214 move.appear
[0].p
== V
.PAWN
221 return undefined; //default
224 // Can thing on square1 take thing on square2
225 canTake([x1
, y1
], [x2
, y2
]) {
226 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
229 // Is (x,y) on the chessboard?
230 static OnBoard(x
, y
) {
231 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
234 // Used in interface: 'side' arg == player color
235 canIplay(side
, [x
, y
]) {
236 return this.turn
== side
&& this.getColor(x
, y
) == side
;
239 // On which squares is color under check ? (for interface)
240 getCheckSquares(color
) {
242 this.underCheck(color
)
243 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
251 // Setup the initial random (asymmetric) position
252 static GenRandInitFen(randomness
) {
255 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
257 let pieces
= { w: new Array(8), b: new Array(8) };
259 // Shuffle pieces on first (and last rank if randomness == 2)
260 for (let c
of ["w", "b"]) {
261 if (c
== 'b' && randomness
== 1) {
262 pieces
['b'] = pieces
['w'];
267 let positions
= ArrayFun
.range(8);
269 // Get random squares for bishops
270 let randIndex
= 2 * randInt(4);
271 const bishop1Pos
= positions
[randIndex
];
272 // The second bishop must be on a square of different color
273 let randIndex_tmp
= 2 * randInt(4) + 1;
274 const bishop2Pos
= positions
[randIndex_tmp
];
275 // Remove chosen squares
276 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
277 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
279 // Get random squares for knights
280 randIndex
= randInt(6);
281 const knight1Pos
= positions
[randIndex
];
282 positions
.splice(randIndex
, 1);
283 randIndex
= randInt(5);
284 const knight2Pos
= positions
[randIndex
];
285 positions
.splice(randIndex
, 1);
287 // Get random square for queen
288 randIndex
= randInt(4);
289 const queenPos
= positions
[randIndex
];
290 positions
.splice(randIndex
, 1);
292 // Rooks and king positions are now fixed,
293 // because of the ordering rook-king-rook
294 const rook1Pos
= positions
[0];
295 const kingPos
= positions
[1];
296 const rook2Pos
= positions
[2];
298 // Finally put the shuffled pieces in the board array
299 pieces
[c
][rook1Pos
] = "r";
300 pieces
[c
][knight1Pos
] = "n";
301 pieces
[c
][bishop1Pos
] = "b";
302 pieces
[c
][queenPos
] = "q";
303 pieces
[c
][kingPos
] = "k";
304 pieces
[c
][bishop2Pos
] = "b";
305 pieces
[c
][knight2Pos
] = "n";
306 pieces
[c
][rook2Pos
] = "r";
307 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
309 // Add turn + flags + enpassant
311 pieces
["b"].join("") +
312 "/pppppppp/8/8/8/8/PPPPPPPP/" +
313 pieces
["w"].join("").toUpperCase() +
314 " w 0 " + flags
+ " -"
318 // "Parse" FEN: just return untransformed string data
319 static ParseFen(fen
) {
320 const fenParts
= fen
.split(" ");
322 position: fenParts
[0],
324 movesCount: fenParts
[2]
327 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
328 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
332 // Return current fen (game state)
335 this.getBaseFen() + " " +
336 this.getTurnFen() + " " +
338 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
339 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
344 // Omit movesCount, only variable allowed to differ
346 this.getBaseFen() + "_" +
348 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
349 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
353 // Position part of the FEN string
356 for (let i
= 0; i
< V
.size
.x
; i
++) {
358 for (let j
= 0; j
< V
.size
.y
; j
++) {
359 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
361 if (emptyCount
> 0) {
362 // Add empty squares in-between
363 position
+= emptyCount
;
366 position
+= V
.board2fen(this.board
[i
][j
]);
369 if (emptyCount
> 0) {
371 position
+= emptyCount
;
373 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
382 // Flags part of the FEN string
386 for (let c
of ["w", "b"])
387 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
391 // Enpassant part of the FEN string
393 const L
= this.epSquares
.length
;
394 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
395 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
398 // Turn position fen into double array ["wb","wp","bk",...]
399 static GetBoard(position
) {
400 const rows
= position
.split("/");
401 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
402 for (let i
= 0; i
< rows
.length
; i
++) {
404 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
405 const character
= rows
[i
][indexInRow
];
406 const num
= parseInt(character
);
407 // If num is a number, just shift j:
408 if (!isNaN(num
)) j
+= num
;
409 // Else: something at position i,j
410 else board
[i
][j
++] = V
.fen2board(character
);
416 // Extract (relevant) flags from fen
418 // white a-castle, h-castle, black a-castle, h-castle
419 this.castleFlags
= { w: [true, true], b: [true, true] };
420 for (let i
= 0; i
< 4; i
++) {
421 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
422 V
.ColumnToCoord(fenflags
.charAt(i
));
429 // Fen string fully describes the game state
432 // In printDiagram() fen isn't supply because only getPpath() is used
433 // TODO: find a better solution!
435 const fenParsed
= V
.ParseFen(fen
);
436 this.board
= V
.GetBoard(fenParsed
.position
);
437 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
438 this.movesCount
= parseInt(fenParsed
.movesCount
);
439 this.setOtherVariables(fen
);
442 // Scan board for kings positions
444 this.INIT_COL_KING
= { w: -1, b: -1 };
445 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
446 const fenRows
= V
.ParseFen(fen
).position
.split("/");
447 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
448 for (let i
= 0; i
< fenRows
.length
; i
++) {
449 let k
= 0; //column index on board
450 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
451 switch (fenRows
[i
].charAt(j
)) {
453 this.kingPos
["b"] = [i
, k
];
454 this.INIT_COL_KING
["b"] = k
;
457 this.kingPos
["w"] = [i
, k
];
458 this.INIT_COL_KING
["w"] = k
;
461 const num
= parseInt(fenRows
[i
].charAt(j
));
462 if (!isNaN(num
)) k
+= num
- 1;
470 // Some additional variables from FEN (variant dependant)
471 setOtherVariables(fen
) {
472 // Set flags and enpassant:
473 const parsedFen
= V
.ParseFen(fen
);
474 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
475 if (V
.HasEnpassant
) {
477 parsedFen
.enpassant
!= "-"
478 ? this.getEpSquare(parsedFen
.enpassant
)
480 this.epSquares
= [epSq
];
482 // Search for kings positions:
486 /////////////////////
490 return { x: 8, y: 8 };
493 // Color of thing on square (i,j). 'undefined' if square is empty
495 return this.board
[i
][j
].charAt(0);
498 // Piece type on square (i,j). 'undefined' if square is empty
500 return this.board
[i
][j
].charAt(1);
503 // Get opponent color
504 static GetOppCol(color
) {
505 return color
== "w" ? "b" : "w";
508 // Pieces codes (for a clearer code)
515 static get KNIGHT() {
518 static get BISHOP() {
529 static get PIECES() {
530 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
538 // Some pieces movements
569 // All possible moves from selected square
570 getPotentialMovesFrom([x
, y
]) {
571 switch (this.getPiece(x
, y
)) {
573 return this.getPotentialPawnMoves([x
, y
]);
575 return this.getPotentialRookMoves([x
, y
]);
577 return this.getPotentialKnightMoves([x
, y
]);
579 return this.getPotentialBishopMoves([x
, y
]);
581 return this.getPotentialQueenMoves([x
, y
]);
583 return this.getPotentialKingMoves([x
, y
]);
585 return []; //never reached
588 // Build a regular move from its initial and destination squares.
589 // tr: transformation
590 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
596 c: tr
? tr
.c : this.getColor(sx
, sy
),
597 p: tr
? tr
.p : this.getPiece(sx
, sy
)
604 c: this.getColor(sx
, sy
),
605 p: this.getPiece(sx
, sy
)
610 // The opponent piece disappears if we take it
611 if (this.board
[ex
][ey
] != V
.EMPTY
) {
616 c: this.getColor(ex
, ey
),
617 p: this.getPiece(ex
, ey
)
625 // Generic method to find possible moves of non-pawn pieces:
626 // "sliding or jumping"
627 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
629 outerLoop: for (let step
of steps
) {
632 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
633 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
634 if (oneStep
) continue outerLoop
;
638 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
639 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
644 // What are the pawn moves from square x,y ?
645 getPotentialPawnMoves([x
, y
]) {
646 const color
= this.turn
;
648 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
649 const shiftX
= color
== "w" ? -1 : 1;
650 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
651 const startRank
= color
== "w" ? sizeX
- 2 : 1;
652 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
654 // NOTE: next condition is generally true (no pawn on last rank)
655 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
657 x
+ shiftX
== lastRank
658 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
660 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
661 // One square forward
662 for (let piece
of finalPieces
) {
664 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
670 // Next condition because pawns on 1st rank can generally jump
672 [startRank
, firstRank
].includes(x
) &&
673 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
676 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
680 for (let shiftY
of [-1, 1]) {
683 y
+ shiftY
< sizeY
&&
684 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
685 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
687 for (let piece
of finalPieces
) {
689 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
699 if (V
.HasEnpassant
) {
701 const Lep
= this.epSquares
.length
;
702 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
705 epSquare
.x
== x
+ shiftX
&&
706 Math
.abs(epSquare
.y
- y
) == 1
708 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
709 enpassantMove
.vanish
.push({
713 c: this.getColor(x
, epSquare
.y
)
715 moves
.push(enpassantMove
);
722 // What are the rook moves from square x,y ?
723 getPotentialRookMoves(sq
) {
724 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
727 // What are the knight moves from square x,y ?
728 getPotentialKnightMoves(sq
) {
729 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
732 // What are the bishop moves from square x,y ?
733 getPotentialBishopMoves(sq
) {
734 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
737 // What are the queen moves from square x,y ?
738 getPotentialQueenMoves(sq
) {
739 return this.getSlideNJumpMoves(
741 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
745 // What are the king moves from square x,y ?
746 getPotentialKingMoves(sq
) {
747 // Initialize with normal moves
748 const moves
= this.getSlideNJumpMoves(
750 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
753 return moves
.concat(this.getCastleMoves(sq
));
756 getCastleMoves([x
, y
]) {
757 const c
= this.getColor(x
, y
);
758 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
759 return []; //x isn't first rank, or king has moved (shortcut)
762 const oppCol
= V
.GetOppCol(c
);
766 const finalSquares
= [
768 [V
.size
.y
- 2, V
.size
.y
- 3]
773 castleSide
++ //large, then small
775 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
776 // If this code is reached, rooks and king are on initial position
778 // Nothing on the path of the king ? (and no checks)
779 const finDist
= finalSquares
[castleSide
][0] - y
;
780 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
784 this.isAttacked([x
, i
], [oppCol
]) ||
785 (this.board
[x
][i
] != V
.EMPTY
&&
786 // NOTE: next check is enough, because of chessboard constraints
787 (this.getColor(x
, i
) != c
||
788 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
790 continue castlingCheck
;
793 } while (i
!= finalSquares
[castleSide
][0]);
795 // Nothing on the path to the rook?
796 step
= castleSide
== 0 ? -1 : 1;
797 const rookPos
= this.castleFlags
[c
][castleSide
];
798 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
799 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
802 // Nothing on final squares, except maybe king and castling rook?
803 for (i
= 0; i
< 2; i
++) {
805 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
806 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
807 finalSquares
[castleSide
][i
] != rookPos
809 continue castlingCheck
;
813 // If this code is reached, castle is valid
817 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
818 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
821 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
822 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
825 Math
.abs(y
- rookPos
) <= 2
826 ? { x: x
, y: rookPos
}
827 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
838 // For the interface: possible moves for the current turn from square sq
839 getPossibleMovesFrom(sq
) {
840 return this.filterValid(this.getPotentialMovesFrom(sq
));
843 // TODO: promotions (into R,B,N,Q) should be filtered only once
845 if (moves
.length
== 0) return [];
846 const color
= this.turn
;
847 return moves
.filter(m
=> {
849 const res
= !this.underCheck(color
);
855 // Search for all valid moves considering current turn
856 // (for engine and game end)
858 const color
= this.turn
;
859 let potentialMoves
= [];
860 for (let i
= 0; i
< V
.size
.x
; i
++) {
861 for (let j
= 0; j
< V
.size
.y
; j
++) {
862 if (this.getColor(i
, j
) == color
) {
863 Array
.prototype.push
.apply(
865 this.getPotentialMovesFrom([i
, j
])
870 return this.filterValid(potentialMoves
);
873 // Stop at the first move found
875 const color
= this.turn
;
876 for (let i
= 0; i
< V
.size
.x
; i
++) {
877 for (let j
= 0; j
< V
.size
.y
; j
++) {
878 if (this.getColor(i
, j
) == color
) {
879 const moves
= this.getPotentialMovesFrom([i
, j
]);
880 if (moves
.length
> 0) {
881 for (let k
= 0; k
< moves
.length
; k
++) {
882 if (this.filterValid([moves
[k
]]).length
> 0) return true;
891 // Check if pieces of color in 'colors' are attacking (king) on square x,y
892 isAttacked(sq
, colors
) {
894 this.isAttackedByPawn(sq
, colors
) ||
895 this.isAttackedByRook(sq
, colors
) ||
896 this.isAttackedByKnight(sq
, colors
) ||
897 this.isAttackedByBishop(sq
, colors
) ||
898 this.isAttackedByQueen(sq
, colors
) ||
899 this.isAttackedByKing(sq
, colors
)
903 // Generic method for non-pawn pieces ("sliding or jumping"):
904 // is x,y attacked by a piece of color in array 'colors' ?
905 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
906 for (let step
of steps
) {
907 let rx
= x
+ step
[0],
909 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
915 this.getPiece(rx
, ry
) === piece
&&
916 colors
.includes(this.getColor(rx
, ry
))
924 // Is square x,y attacked by 'colors' pawns ?
925 isAttackedByPawn([x
, y
], colors
) {
926 for (let c
of colors
) {
927 const pawnShift
= c
== "w" ? 1 : -1;
928 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
929 for (let i
of [-1, 1]) {
933 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
934 this.getColor(x
+ pawnShift
, y
+ i
) == c
944 // Is square x,y attacked by 'colors' rooks ?
945 isAttackedByRook(sq
, colors
) {
946 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
949 // Is square x,y attacked by 'colors' knights ?
950 isAttackedByKnight(sq
, colors
) {
951 return this.isAttackedBySlideNJump(
960 // Is square x,y attacked by 'colors' bishops ?
961 isAttackedByBishop(sq
, colors
) {
962 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
965 // Is square x,y attacked by 'colors' queens ?
966 isAttackedByQueen(sq
, colors
) {
967 return this.isAttackedBySlideNJump(
971 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
975 // Is square x,y attacked by 'colors' king(s) ?
976 isAttackedByKing(sq
, colors
) {
977 return this.isAttackedBySlideNJump(
981 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
986 // Is color under check after his move ?
988 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
994 // Apply a move on board
995 static PlayOnBoard(board
, move) {
996 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
997 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
999 // Un-apply the played move
1000 static UndoOnBoard(board
, move) {
1001 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1002 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1009 // if (!this.states) this.states = [];
1010 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1011 // this.states.push(stateFen);
1014 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1015 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1016 V
.PlayOnBoard(this.board
, move);
1017 this.turn
= V
.GetOppCol(this.turn
);
1019 this.postPlay(move);
1022 // After move is played, update variables + flags
1024 const c
= V
.GetOppCol(this.turn
);
1025 let piece
= undefined;
1026 if (move.vanish
.length
>= 1)
1027 // Usual case, something is moved
1028 piece
= move.vanish
[0].p
;
1030 // Crazyhouse-like variants
1031 piece
= move.appear
[0].p
;
1032 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1034 // Update king position + flags
1035 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1036 this.kingPos
[c
][0] = move.appear
[0].x
;
1037 this.kingPos
[c
][1] = move.appear
[0].y
;
1038 if (V
.HasCastle
) this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1042 // Update castling flags if rooks are moved
1043 const oppCol
= V
.GetOppCol(c
);
1044 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1046 move.start
.x
== firstRank
&& //our rook moves?
1047 this.castleFlags
[c
].includes(move.start
.y
)
1049 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1050 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1052 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1053 this.castleFlags
[oppCol
].includes(move.end
.y
)
1055 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1056 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1065 if (V
.HasEnpassant
) this.epSquares
.pop();
1066 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1067 V
.UndoOnBoard(this.board
, move);
1068 this.turn
= V
.GetOppCol(this.turn
);
1070 this.postUndo(move);
1073 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1074 // if (stateFen != this.states[this.states.length-1]) debugger;
1075 // this.states.pop();
1078 // After move is undo-ed *and flags resetted*, un-update other variables
1079 // TODO: more symmetry, by storing flags increment in move (?!)
1081 // (Potentially) Reset king position
1082 const c
= this.getColor(move.start
.x
, move.start
.y
);
1083 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1084 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1090 // What is the score ? (Interesting if game is over)
1092 if (this.atLeastOneMove())
1096 const color
= this.turn
;
1097 // No valid move: stalemate or checkmate?
1098 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1101 return color
== "w" ? "0-1" : "1-0";
1108 static get VALUES() {
1119 // "Checkmate" (unreachable eval)
1120 static get INFINITY() {
1124 // At this value or above, the game is over
1125 static get THRESHOLD_MATE() {
1129 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1130 static get SEARCH_DEPTH() {
1135 const maxeval
= V
.INFINITY
;
1136 const color
= this.turn
;
1137 let moves1
= this.getAllValidMoves();
1139 if (moves1
.length
== 0)
1140 // TODO: this situation should not happen
1143 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1144 for (let i
= 0; i
< moves1
.length
; i
++) {
1145 this.play(moves1
[i
]);
1146 const score1
= this.getCurrentScore();
1147 if (score1
!= "*") {
1151 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1153 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1154 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1155 this.undo(moves1
[i
]);
1158 // Initial self evaluation is very low: "I'm checkmated"
1159 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1160 // Initial enemy evaluation is very low too, for him
1161 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1162 // Second half-move:
1163 let moves2
= this.getAllValidMoves();
1164 for (let j
= 0; j
< moves2
.length
; j
++) {
1165 this.play(moves2
[j
]);
1166 const score2
= this.getCurrentScore();
1167 let evalPos
= 0; //1/2 value
1170 evalPos
= this.evalPosition();
1180 (color
== "w" && evalPos
< eval2
) ||
1181 (color
== "b" && evalPos
> eval2
)
1185 this.undo(moves2
[j
]);
1188 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1189 (color
== "b" && eval2
< moves1
[i
].eval
)
1191 moves1
[i
].eval
= eval2
;
1193 this.undo(moves1
[i
]);
1195 moves1
.sort((a
, b
) => {
1196 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1198 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1200 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1201 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1202 for (let i
= 0; i
< moves1
.length
; i
++) {
1203 this.play(moves1
[i
]);
1204 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1206 0.1 * moves1
[i
].eval
+
1207 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1208 this.undo(moves1
[i
]);
1210 moves1
.sort((a
, b
) => {
1211 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1215 let candidates
= [0];
1216 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1218 return moves1
[candidates
[randInt(candidates
.length
)]];
1221 alphabeta(depth
, alpha
, beta
) {
1222 const maxeval
= V
.INFINITY
;
1223 const color
= this.turn
;
1224 const score
= this.getCurrentScore();
1226 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1227 if (depth
== 0) return this.evalPosition();
1228 const moves
= this.getAllValidMoves();
1229 let v
= color
== "w" ? -maxeval : maxeval
;
1231 for (let i
= 0; i
< moves
.length
; i
++) {
1232 this.play(moves
[i
]);
1233 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1234 this.undo(moves
[i
]);
1235 alpha
= Math
.max(alpha
, v
);
1236 if (alpha
>= beta
) break; //beta cutoff
1241 for (let i
= 0; i
< moves
.length
; i
++) {
1242 this.play(moves
[i
]);
1243 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1244 this.undo(moves
[i
]);
1245 beta
= Math
.min(beta
, v
);
1246 if (alpha
>= beta
) break; //alpha cutoff
1254 // Just count material for now
1255 for (let i
= 0; i
< V
.size
.x
; i
++) {
1256 for (let j
= 0; j
< V
.size
.y
; j
++) {
1257 if (this.board
[i
][j
] != V
.EMPTY
) {
1258 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1259 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1266 /////////////////////////
1267 // MOVES + GAME NOTATION
1268 /////////////////////////
1270 // Context: just before move is played, turn hasn't changed
1271 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1273 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1275 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1277 // Translate final square
1278 const finalSquare
= V
.CoordsToSquare(move.end
);
1280 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1281 if (piece
== V
.PAWN
) {
1284 if (move.vanish
.length
> move.appear
.length
) {
1286 const startColumn
= V
.CoordToColumn(move.start
.y
);
1287 notation
= startColumn
+ "x" + finalSquare
;
1289 else notation
= finalSquare
;
1290 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1292 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1297 piece
.toUpperCase() +
1298 (move.vanish
.length
> move.appear
.length
? "x" : "") +