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
) {
241 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
242 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
249 // Setup the initial random (asymmetric) position
250 static GenRandInitFen(randomness
) {
253 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
255 let pieces
= { w: new Array(8), b: new Array(8) };
257 // Shuffle pieces on first (and last rank if randomness == 2)
258 for (let c
of ["w", "b"]) {
259 if (c
== 'b' && randomness
== 1) {
260 pieces
['b'] = pieces
['w'];
265 let positions
= ArrayFun
.range(8);
267 // Get random squares for bishops
268 let randIndex
= 2 * randInt(4);
269 const bishop1Pos
= positions
[randIndex
];
270 // The second bishop must be on a square of different color
271 let randIndex_tmp
= 2 * randInt(4) + 1;
272 const bishop2Pos
= positions
[randIndex_tmp
];
273 // Remove chosen squares
274 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
275 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
277 // Get random squares for knights
278 randIndex
= randInt(6);
279 const knight1Pos
= positions
[randIndex
];
280 positions
.splice(randIndex
, 1);
281 randIndex
= randInt(5);
282 const knight2Pos
= positions
[randIndex
];
283 positions
.splice(randIndex
, 1);
285 // Get random square for queen
286 randIndex
= randInt(4);
287 const queenPos
= positions
[randIndex
];
288 positions
.splice(randIndex
, 1);
290 // Rooks and king positions are now fixed,
291 // because of the ordering rook-king-rook
292 const rook1Pos
= positions
[0];
293 const kingPos
= positions
[1];
294 const rook2Pos
= positions
[2];
296 // Finally put the shuffled pieces in the board array
297 pieces
[c
][rook1Pos
] = "r";
298 pieces
[c
][knight1Pos
] = "n";
299 pieces
[c
][bishop1Pos
] = "b";
300 pieces
[c
][queenPos
] = "q";
301 pieces
[c
][kingPos
] = "k";
302 pieces
[c
][bishop2Pos
] = "b";
303 pieces
[c
][knight2Pos
] = "n";
304 pieces
[c
][rook2Pos
] = "r";
305 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
307 // Add turn + flags + enpassant
309 pieces
["b"].join("") +
310 "/pppppppp/8/8/8/8/PPPPPPPP/" +
311 pieces
["w"].join("").toUpperCase() +
312 " w 0 " + flags
+ " -"
316 // "Parse" FEN: just return untransformed string data
317 static ParseFen(fen
) {
318 const fenParts
= fen
.split(" ");
320 position: fenParts
[0],
322 movesCount: fenParts
[2]
325 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
326 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
330 // Return current fen (game state)
333 this.getBaseFen() + " " +
334 this.getTurnFen() + " " +
336 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
337 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
342 // Omit movesCount, only variable allowed to differ
344 this.getBaseFen() + "_" +
346 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
347 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
351 // Position part of the FEN string
354 for (let i
= 0; i
< V
.size
.x
; i
++) {
356 for (let j
= 0; j
< V
.size
.y
; j
++) {
357 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
359 if (emptyCount
> 0) {
360 // Add empty squares in-between
361 position
+= emptyCount
;
364 position
+= V
.board2fen(this.board
[i
][j
]);
367 if (emptyCount
> 0) {
369 position
+= emptyCount
;
371 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
380 // Flags part of the FEN string
384 for (let c
of ["w", "b"])
385 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
389 // Enpassant part of the FEN string
391 const L
= this.epSquares
.length
;
392 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
393 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
396 // Turn position fen into double array ["wb","wp","bk",...]
397 static GetBoard(position
) {
398 const rows
= position
.split("/");
399 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
400 for (let i
= 0; i
< rows
.length
; i
++) {
402 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
403 const character
= rows
[i
][indexInRow
];
404 const num
= parseInt(character
);
405 // If num is a number, just shift j:
406 if (!isNaN(num
)) j
+= num
;
407 // Else: something at position i,j
408 else board
[i
][j
++] = V
.fen2board(character
);
414 // Extract (relevant) flags from fen
416 // white a-castle, h-castle, black a-castle, h-castle
417 this.castleFlags
= { w: [true, true], b: [true, true] };
418 for (let i
= 0; i
< 4; i
++) {
419 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
420 V
.ColumnToCoord(fenflags
.charAt(i
));
427 // Fen string fully describes the game state
430 // In printDiagram() fen isn't supply because only getPpath() is used
431 // TODO: find a better solution!
433 const fenParsed
= V
.ParseFen(fen
);
434 this.board
= V
.GetBoard(fenParsed
.position
);
435 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
436 this.movesCount
= parseInt(fenParsed
.movesCount
);
437 this.setOtherVariables(fen
);
440 // Scan board for kings positions
442 this.INIT_COL_KING
= { w: -1, b: -1 };
443 this.kingPos
= { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
444 const fenRows
= V
.ParseFen(fen
).position
.split("/");
445 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
446 for (let i
= 0; i
< fenRows
.length
; i
++) {
447 let k
= 0; //column index on board
448 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
449 switch (fenRows
[i
].charAt(j
)) {
451 this.kingPos
["b"] = [i
, k
];
452 this.INIT_COL_KING
["b"] = k
;
455 this.kingPos
["w"] = [i
, k
];
456 this.INIT_COL_KING
["w"] = k
;
459 const num
= parseInt(fenRows
[i
].charAt(j
));
460 if (!isNaN(num
)) k
+= num
- 1;
468 // Some additional variables from FEN (variant dependant)
469 setOtherVariables(fen
) {
470 // Set flags and enpassant:
471 const parsedFen
= V
.ParseFen(fen
);
472 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
473 if (V
.HasEnpassant
) {
475 parsedFen
.enpassant
!= "-"
476 ? this.getEpSquare(parsedFen
.enpassant
)
478 this.epSquares
= [epSq
];
480 // Search for kings positions:
484 /////////////////////
488 return { x: 8, y: 8 };
491 // Color of thing on square (i,j). 'undefined' if square is empty
493 return this.board
[i
][j
].charAt(0);
496 // Piece type on square (i,j). 'undefined' if square is empty
498 return this.board
[i
][j
].charAt(1);
501 // Get opponent color
502 static GetOppCol(color
) {
503 return color
== "w" ? "b" : "w";
506 // Pieces codes (for a clearer code)
513 static get KNIGHT() {
516 static get BISHOP() {
527 static get PIECES() {
528 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
536 // Some pieces movements
567 // All possible moves from selected square
568 getPotentialMovesFrom([x
, y
]) {
569 switch (this.getPiece(x
, y
)) {
571 return this.getPotentialPawnMoves([x
, y
]);
573 return this.getPotentialRookMoves([x
, y
]);
575 return this.getPotentialKnightMoves([x
, y
]);
577 return this.getPotentialBishopMoves([x
, y
]);
579 return this.getPotentialQueenMoves([x
, y
]);
581 return this.getPotentialKingMoves([x
, y
]);
583 return []; //never reached
586 // Build a regular move from its initial and destination squares.
587 // tr: transformation
588 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
594 c: tr
? tr
.c : this.getColor(sx
, sy
),
595 p: tr
? tr
.p : this.getPiece(sx
, sy
)
602 c: this.getColor(sx
, sy
),
603 p: this.getPiece(sx
, sy
)
608 // The opponent piece disappears if we take it
609 if (this.board
[ex
][ey
] != V
.EMPTY
) {
614 c: this.getColor(ex
, ey
),
615 p: this.getPiece(ex
, ey
)
623 // Generic method to find possible moves of non-pawn pieces:
624 // "sliding or jumping"
625 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
627 outerLoop: for (let step
of steps
) {
630 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
631 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
632 if (oneStep
) continue outerLoop
;
636 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
637 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
642 // What are the pawn moves from square x,y ?
643 getPotentialPawnMoves([x
, y
]) {
644 const color
= this.turn
;
646 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
647 const shiftX
= color
== "w" ? -1 : 1;
648 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
649 const startRank
= color
== "w" ? sizeX
- 2 : 1;
650 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
652 // NOTE: next condition is generally true (no pawn on last rank)
653 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
655 x
+ shiftX
== lastRank
656 ? [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
]
658 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
659 // One square forward
660 for (let piece
of finalPieces
) {
662 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
668 // Next condition because pawns on 1st rank can generally jump
670 [startRank
, firstRank
].includes(x
) &&
671 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
674 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
678 for (let shiftY
of [-1, 1]) {
681 y
+ shiftY
< sizeY
&&
682 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
683 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
685 for (let piece
of finalPieces
) {
687 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
697 if (V
.HasEnpassant
) {
699 const Lep
= this.epSquares
.length
;
700 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
703 epSquare
.x
== x
+ shiftX
&&
704 Math
.abs(epSquare
.y
- y
) == 1
706 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
707 enpassantMove
.vanish
.push({
711 c: this.getColor(x
, epSquare
.y
)
713 moves
.push(enpassantMove
);
720 // What are the rook moves from square x,y ?
721 getPotentialRookMoves(sq
) {
722 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
725 // What are the knight moves from square x,y ?
726 getPotentialKnightMoves(sq
) {
727 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
730 // What are the bishop moves from square x,y ?
731 getPotentialBishopMoves(sq
) {
732 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
735 // What are the queen moves from square x,y ?
736 getPotentialQueenMoves(sq
) {
737 return this.getSlideNJumpMoves(
739 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
743 // What are the king moves from square x,y ?
744 getPotentialKingMoves(sq
) {
745 // Initialize with normal moves
746 const moves
= this.getSlideNJumpMoves(
748 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
751 return moves
.concat(this.getCastleMoves(sq
));
754 getCastleMoves([x
, y
]) {
755 const c
= this.getColor(x
, y
);
756 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
757 return []; //x isn't first rank, or king has moved (shortcut)
760 const oppCol
= V
.GetOppCol(c
);
764 const finalSquares
= [
766 [V
.size
.y
- 2, V
.size
.y
- 3]
771 castleSide
++ //large, then small
773 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
774 // If this code is reached, rooks and king are on initial position
776 // Nothing on the path of the king ? (and no checks)
777 const finDist
= finalSquares
[castleSide
][0] - y
;
778 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
782 this.isAttacked([x
, i
], [oppCol
]) ||
783 (this.board
[x
][i
] != V
.EMPTY
&&
784 // NOTE: next check is enough, because of chessboard constraints
785 (this.getColor(x
, i
) != c
||
786 ![V
.KING
, V
.ROOK
].includes(this.getPiece(x
, i
))))
788 continue castlingCheck
;
791 } while (i
!= finalSquares
[castleSide
][0]);
793 // Nothing on the path to the rook?
794 step
= castleSide
== 0 ? -1 : 1;
795 const rookPos
= this.castleFlags
[c
][castleSide
];
796 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
797 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
800 // Nothing on final squares, except maybe king and castling rook?
801 for (i
= 0; i
< 2; i
++) {
803 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
804 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
805 finalSquares
[castleSide
][i
] != rookPos
807 continue castlingCheck
;
811 // If this code is reached, castle is valid
815 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
816 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: V
.ROOK
, c: c
})
819 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
820 new PiPo({ x: x
, y: rookPos
, p: V
.ROOK
, c: c
})
823 Math
.abs(y
- rookPos
) <= 2
824 ? { x: x
, y: rookPos
}
825 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
836 // For the interface: possible moves for the current turn from square sq
837 getPossibleMovesFrom(sq
) {
838 return this.filterValid(this.getPotentialMovesFrom(sq
));
841 // TODO: promotions (into R,B,N,Q) should be filtered only once
843 if (moves
.length
== 0) return [];
844 const color
= this.turn
;
845 return moves
.filter(m
=> {
847 const res
= !this.underCheck(color
);
853 // Search for all valid moves considering current turn
854 // (for engine and game end)
856 const color
= this.turn
;
857 let potentialMoves
= [];
858 for (let i
= 0; i
< V
.size
.x
; i
++) {
859 for (let j
= 0; j
< V
.size
.y
; j
++) {
860 if (this.getColor(i
, j
) == color
) {
861 Array
.prototype.push
.apply(
863 this.getPotentialMovesFrom([i
, j
])
868 return this.filterValid(potentialMoves
);
871 // Stop at the first move found
873 const color
= this.turn
;
874 for (let i
= 0; i
< V
.size
.x
; i
++) {
875 for (let j
= 0; j
< V
.size
.y
; j
++) {
876 if (this.getColor(i
, j
) == color
) {
877 const moves
= this.getPotentialMovesFrom([i
, j
]);
878 if (moves
.length
> 0) {
879 for (let k
= 0; k
< moves
.length
; k
++) {
880 if (this.filterValid([moves
[k
]]).length
> 0) return true;
889 // Check if pieces of color in 'colors' are attacking (king) on square x,y
890 isAttacked(sq
, colors
) {
892 this.isAttackedByPawn(sq
, colors
) ||
893 this.isAttackedByRook(sq
, colors
) ||
894 this.isAttackedByKnight(sq
, colors
) ||
895 this.isAttackedByBishop(sq
, colors
) ||
896 this.isAttackedByQueen(sq
, colors
) ||
897 this.isAttackedByKing(sq
, colors
)
901 // Generic method for non-pawn pieces ("sliding or jumping"):
902 // is x,y attacked by a piece of color in array 'colors' ?
903 isAttackedBySlideNJump([x
, y
], colors
, piece
, steps
, oneStep
) {
904 for (let step
of steps
) {
905 let rx
= x
+ step
[0],
907 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
913 this.getPiece(rx
, ry
) === piece
&&
914 colors
.includes(this.getColor(rx
, ry
))
922 // Is square x,y attacked by 'colors' pawns ?
923 isAttackedByPawn([x
, y
], colors
) {
924 for (let c
of colors
) {
925 const pawnShift
= c
== "w" ? 1 : -1;
926 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
927 for (let i
of [-1, 1]) {
931 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
932 this.getColor(x
+ pawnShift
, y
+ i
) == c
942 // Is square x,y attacked by 'colors' rooks ?
943 isAttackedByRook(sq
, colors
) {
944 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
947 // Is square x,y attacked by 'colors' knights ?
948 isAttackedByKnight(sq
, colors
) {
949 return this.isAttackedBySlideNJump(
958 // Is square x,y attacked by 'colors' bishops ?
959 isAttackedByBishop(sq
, colors
) {
960 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
963 // Is square x,y attacked by 'colors' queens ?
964 isAttackedByQueen(sq
, colors
) {
965 return this.isAttackedBySlideNJump(
969 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
973 // Is square x,y attacked by 'colors' king(s) ?
974 isAttackedByKing(sq
, colors
) {
975 return this.isAttackedBySlideNJump(
979 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
984 // Is color under check after his move ?
986 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
992 // Apply a move on board
993 static PlayOnBoard(board
, move) {
994 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
995 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
997 // Un-apply the played move
998 static UndoOnBoard(board
, move) {
999 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1000 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1007 // if (!this.states) this.states = [];
1008 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1009 // this.states.push(stateFen);
1012 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1013 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1014 V
.PlayOnBoard(this.board
, move);
1015 this.turn
= V
.GetOppCol(this.turn
);
1017 this.postPlay(move);
1020 // After move is played, update variables + flags
1022 const c
= V
.GetOppCol(this.turn
);
1023 let piece
= undefined;
1024 if (move.vanish
.length
>= 1)
1025 // Usual case, something is moved
1026 piece
= move.vanish
[0].p
;
1028 // Crazyhouse-like variants
1029 piece
= move.appear
[0].p
;
1030 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1032 // Update king position + flags
1033 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1034 this.kingPos
[c
][0] = move.appear
[0].x
;
1035 this.kingPos
[c
][1] = move.appear
[0].y
;
1036 if (V
.HasCastle
) this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1040 // Update castling flags if rooks are moved
1041 const oppCol
= V
.GetOppCol(c
);
1042 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1044 move.start
.x
== firstRank
&& //our rook moves?
1045 this.castleFlags
[c
].includes(move.start
.y
)
1047 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1048 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1050 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1051 this.castleFlags
[oppCol
].includes(move.end
.y
)
1053 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1054 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1063 if (V
.HasEnpassant
) this.epSquares
.pop();
1064 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1065 V
.UndoOnBoard(this.board
, move);
1066 this.turn
= V
.GetOppCol(this.turn
);
1068 this.postUndo(move);
1071 // const stateFen = this.getBaseFen() + this.getTurnFen();// + this.getFlagsFen();
1072 // if (stateFen != this.states[this.states.length-1]) debugger;
1073 // this.states.pop();
1076 // After move is undo-ed *and flags resetted*, un-update other variables
1077 // TODO: more symmetry, by storing flags increment in move (?!)
1079 // (Potentially) Reset king position
1080 const c
= this.getColor(move.start
.x
, move.start
.y
);
1081 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1082 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1088 // What is the score ? (Interesting if game is over)
1090 if (this.atLeastOneMove())
1094 const color
= this.turn
;
1095 // No valid move: stalemate or checkmate?
1096 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1099 return color
== "w" ? "0-1" : "1-0";
1106 static get VALUES() {
1117 // "Checkmate" (unreachable eval)
1118 static get INFINITY() {
1122 // At this value or above, the game is over
1123 static get THRESHOLD_MATE() {
1127 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1128 static get SEARCH_DEPTH() {
1133 const maxeval
= V
.INFINITY
;
1134 const color
= this.turn
;
1135 let moves1
= this.getAllValidMoves();
1137 if (moves1
.length
== 0)
1138 // TODO: this situation should not happen
1141 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1142 for (let i
= 0; i
< moves1
.length
; i
++) {
1143 this.play(moves1
[i
]);
1144 const score1
= this.getCurrentScore();
1145 if (score1
!= "*") {
1149 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1151 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1152 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1153 this.undo(moves1
[i
]);
1156 // Initial self evaluation is very low: "I'm checkmated"
1157 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1158 // Initial enemy evaluation is very low too, for him
1159 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1160 // Second half-move:
1161 let moves2
= this.getAllValidMoves();
1162 for (let j
= 0; j
< moves2
.length
; j
++) {
1163 this.play(moves2
[j
]);
1164 const score2
= this.getCurrentScore();
1165 let evalPos
= 0; //1/2 value
1168 evalPos
= this.evalPosition();
1178 (color
== "w" && evalPos
< eval2
) ||
1179 (color
== "b" && evalPos
> eval2
)
1183 this.undo(moves2
[j
]);
1186 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1187 (color
== "b" && eval2
< moves1
[i
].eval
)
1189 moves1
[i
].eval
= eval2
;
1191 this.undo(moves1
[i
]);
1193 moves1
.sort((a
, b
) => {
1194 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1196 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1198 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1199 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1200 for (let i
= 0; i
< moves1
.length
; i
++) {
1201 this.play(moves1
[i
]);
1202 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1204 0.1 * moves1
[i
].eval
+
1205 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1206 this.undo(moves1
[i
]);
1208 moves1
.sort((a
, b
) => {
1209 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1213 let candidates
= [0];
1214 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1216 return moves1
[candidates
[randInt(candidates
.length
)]];
1219 alphabeta(depth
, alpha
, beta
) {
1220 const maxeval
= V
.INFINITY
;
1221 const color
= this.turn
;
1222 const score
= this.getCurrentScore();
1224 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1225 if (depth
== 0) return this.evalPosition();
1226 const moves
= this.getAllValidMoves();
1227 let v
= color
== "w" ? -maxeval : maxeval
;
1229 for (let i
= 0; i
< moves
.length
; i
++) {
1230 this.play(moves
[i
]);
1231 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1232 this.undo(moves
[i
]);
1233 alpha
= Math
.max(alpha
, v
);
1234 if (alpha
>= beta
) break; //beta cutoff
1239 for (let i
= 0; i
< moves
.length
; i
++) {
1240 this.play(moves
[i
]);
1241 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1242 this.undo(moves
[i
]);
1243 beta
= Math
.min(beta
, v
);
1244 if (alpha
>= beta
) break; //alpha cutoff
1252 // Just count material for now
1253 for (let i
= 0; i
< V
.size
.x
; i
++) {
1254 for (let j
= 0; j
< V
.size
.y
; j
++) {
1255 if (this.board
[i
][j
] != V
.EMPTY
) {
1256 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1257 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1264 /////////////////////////
1265 // MOVES + GAME NOTATION
1266 /////////////////////////
1268 // Context: just before move is played, turn hasn't changed
1269 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1271 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1273 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1275 // Translate final square
1276 const finalSquare
= V
.CoordsToSquare(move.end
);
1278 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1279 if (piece
== V
.PAWN
) {
1282 if (move.vanish
.length
> move.appear
.length
) {
1284 const startColumn
= V
.CoordToColumn(move.start
.y
);
1285 notation
= startColumn
+ "x" + finalSquare
;
1287 else notation
= finalSquare
;
1288 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1290 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1295 piece
.toUpperCase() +
1296 (move.vanish
.length
> move.appear
.length
? "x" : "") +