99de62658f9f3df3df795d50840bde55f1e4483a
1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
4 import { ArrayFun
} from "@/utils/array";
5 import { randInt
, shuffle
} from "@/utils/alea";
7 // class "PiPo": Piece + Position
8 export const PiPo
= class PiPo
{
9 // o: {piece[p], color[c], posX[x], posY[y]}
18 export const Move
= class Move
{
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
23 this.appear
= o
.appear
;
24 this.vanish
= o
.vanish
;
25 this.start
= o
.start
? o
.start : { x: o
.vanish
[0].x
, y: o
.vanish
[0].y
};
26 this.end
= o
.end
? o
.end : { x: o
.appear
[0].x
, y: o
.appear
[0].y
};
30 // NOTE: x coords = top to bottom; y = left to right
31 // (from white player perspective)
32 export const ChessRules
= class ChessRules
{
36 // Some variants don't have flags:
37 static get HasFlags() {
42 static get HasCastle() {
46 // Pawns specifications
47 static get PawnSpecs() {
49 directions: { 'w': -1, 'b': 1 },
50 initShift: { w: 1, b: 1 },
53 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
55 captureBackward: false,
60 // En-passant captures need a stack of squares:
61 static get HasEnpassant() {
65 // Some variants cannot have analyse mode
66 static get CanAnalyze() {
69 // Patch: issues with javascript OOP, objects can't access static fields.
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
83 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
88 // Some variants always show the same orientation
89 static get CanFlip() {
96 // For (generally old) variants without checkered board
97 static get Monochrome() {
101 // Some variants require lines drawing
105 // Draw all inter-squares lines
106 for (let i
= 0; i
<= V
.size
.x
; i
++)
107 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
108 for (let j
= 0; j
<= V
.size
.y
; j
++)
109 lines
.push([[0, j
], [V
.size
.x
, j
]]);
115 // Some variants use click infos:
120 static get IMAGE_EXTENSION() {
121 // All pieces should be in the SVG format
125 // Turn "wb" into "B" (for FEN)
126 static board2fen(b
) {
127 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
130 // Turn "p" into "bp" (for board)
131 static fen2board(f
) {
132 return f
.charCodeAt() <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
135 // Check if FEN describes a board situation correctly
136 static IsGoodFen(fen
) {
137 const fenParsed
= V
.ParseFen(fen
);
139 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
141 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
142 // 3) Check moves count
143 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
146 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
148 // 5) Check enpassant
151 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
158 // Is position part of the FEN a priori correct?
159 static IsGoodPosition(position
) {
160 if (position
.length
== 0) return false;
161 const rows
= position
.split("/");
162 if (rows
.length
!= V
.size
.x
) return false;
163 let kings
= { "k": 0, "K": 0 };
164 for (let row
of rows
) {
166 for (let i
= 0; i
< row
.length
; i
++) {
167 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
168 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
170 const num
= parseInt(row
[i
]);
171 if (isNaN(num
)) return false;
175 if (sumElts
!= V
.size
.y
) return false;
177 // Both kings should be on board. Exactly one per color.
178 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
183 static IsGoodTurn(turn
) {
184 return ["w", "b"].includes(turn
);
188 static IsGoodFlags(flags
) {
189 // NOTE: a little too permissive to work with more variants
190 return !!flags
.match(/^[a-z]{4,4}$/);
193 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
194 static IsGoodEnpassant(enpassant
) {
195 if (enpassant
!= "-") {
196 const ep
= V
.SquareToCoords(enpassant
);
197 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
202 // 3 --> d (column number to letter)
203 static CoordToColumn(colnum
) {
204 return String
.fromCharCode(97 + colnum
);
207 // d --> 3 (column letter to number)
208 static ColumnToCoord(column
) {
209 return column
.charCodeAt(0) - 97;
213 static SquareToCoords(sq
) {
215 // NOTE: column is always one char => max 26 columns
216 // row is counted from black side => subtraction
217 x: V
.size
.x
- parseInt(sq
.substr(1)),
218 y: sq
[0].charCodeAt() - 97
223 static CoordsToSquare(coords
) {
224 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
227 // Path to pieces (standard ones in pieces/ folder)
232 // Path to promotion pieces (usually the same)
234 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
237 // Aggregates flags into one object
239 return this.castleFlags
;
243 disaggregateFlags(flags
) {
244 this.castleFlags
= flags
;
247 // En-passant square, if any
248 getEpSquare(moveOrSquare
) {
249 if (!moveOrSquare
) return undefined;
250 if (typeof moveOrSquare
=== "string") {
251 const square
= moveOrSquare
;
252 if (square
== "-") return undefined;
253 return V
.SquareToCoords(square
);
255 // Argument is a move:
256 const move = moveOrSquare
;
257 const s
= move.start
,
261 Math
.abs(s
.x
- e
.x
) == 2 &&
262 // Next conditions for variants like Atomic or Rifle, Recycle...
263 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
264 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
271 return undefined; //default
274 // Can thing on square1 take thing on square2
275 canTake([x1
, y1
], [x2
, y2
]) {
276 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
279 // Is (x,y) on the chessboard?
280 static OnBoard(x
, y
) {
281 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
284 // Used in interface: 'side' arg == player color
285 canIplay(side
, [x
, y
]) {
286 return this.turn
== side
&& this.getColor(x
, y
) == side
;
289 // On which squares is color under check ? (for interface)
291 const color
= this.turn
;
293 this.underCheck(color
)
294 // kingPos must be duplicated, because it may change:
295 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
303 // Setup the initial random (asymmetric) position
304 static GenRandInitFen(randomness
) {
307 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
309 let pieces
= { w: new Array(8), b: new Array(8) };
311 // Shuffle pieces on first (and last rank if randomness == 2)
312 for (let c
of ["w", "b"]) {
313 if (c
== 'b' && randomness
== 1) {
314 pieces
['b'] = pieces
['w'];
319 let positions
= ArrayFun
.range(8);
321 // Get random squares for bishops
322 let randIndex
= 2 * randInt(4);
323 const bishop1Pos
= positions
[randIndex
];
324 // The second bishop must be on a square of different color
325 let randIndex_tmp
= 2 * randInt(4) + 1;
326 const bishop2Pos
= positions
[randIndex_tmp
];
327 // Remove chosen squares
328 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
329 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
331 // Get random squares for knights
332 randIndex
= randInt(6);
333 const knight1Pos
= positions
[randIndex
];
334 positions
.splice(randIndex
, 1);
335 randIndex
= randInt(5);
336 const knight2Pos
= positions
[randIndex
];
337 positions
.splice(randIndex
, 1);
339 // Get random square for queen
340 randIndex
= randInt(4);
341 const queenPos
= positions
[randIndex
];
342 positions
.splice(randIndex
, 1);
344 // Rooks and king positions are now fixed,
345 // because of the ordering rook-king-rook
346 const rook1Pos
= positions
[0];
347 const kingPos
= positions
[1];
348 const rook2Pos
= positions
[2];
350 // Finally put the shuffled pieces in the board array
351 pieces
[c
][rook1Pos
] = "r";
352 pieces
[c
][knight1Pos
] = "n";
353 pieces
[c
][bishop1Pos
] = "b";
354 pieces
[c
][queenPos
] = "q";
355 pieces
[c
][kingPos
] = "k";
356 pieces
[c
][bishop2Pos
] = "b";
357 pieces
[c
][knight2Pos
] = "n";
358 pieces
[c
][rook2Pos
] = "r";
359 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
361 // Add turn + flags + enpassant
363 pieces
["b"].join("") +
364 "/pppppppp/8/8/8/8/PPPPPPPP/" +
365 pieces
["w"].join("").toUpperCase() +
366 " w 0 " + flags
+ " -"
370 // "Parse" FEN: just return untransformed string data
371 static ParseFen(fen
) {
372 const fenParts
= fen
.split(" ");
374 position: fenParts
[0],
376 movesCount: fenParts
[2]
379 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
380 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
384 // Return current fen (game state)
387 this.getBaseFen() + " " +
388 this.getTurnFen() + " " +
390 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
391 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
396 // Omit movesCount, only variable allowed to differ
398 this.getBaseFen() + "_" +
400 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
401 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
405 // Position part of the FEN string
407 const format
= (count
) => {
408 // if more than 9 consecutive free spaces, break the integer,
409 // otherwise FEN parsing will fail.
410 if (count
<= 9) return count
;
411 // Currently only boards of size up to 11 or 12:
412 return "9" + (count
- 9);
415 for (let i
= 0; i
< V
.size
.x
; i
++) {
417 for (let j
= 0; j
< V
.size
.y
; j
++) {
418 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
420 if (emptyCount
> 0) {
421 // Add empty squares in-between
422 position
+= format(emptyCount
);
425 position
+= V
.board2fen(this.board
[i
][j
]);
428 if (emptyCount
> 0) {
430 position
+= format(emptyCount
);
432 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
441 // Flags part of the FEN string
445 for (let c
of ["w", "b"])
446 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
450 // Enpassant part of the FEN string
452 const L
= this.epSquares
.length
;
453 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
454 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
457 // Turn position fen into double array ["wb","wp","bk",...]
458 static GetBoard(position
) {
459 const rows
= position
.split("/");
460 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
461 for (let i
= 0; i
< rows
.length
; i
++) {
463 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
464 const character
= rows
[i
][indexInRow
];
465 const num
= parseInt(character
);
466 // If num is a number, just shift j:
467 if (!isNaN(num
)) j
+= num
;
468 // Else: something at position i,j
469 else board
[i
][j
++] = V
.fen2board(character
);
475 // Extract (relevant) flags from fen
477 // white a-castle, h-castle, black a-castle, h-castle
478 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
479 for (let i
= 0; i
< 4; i
++) {
480 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
481 V
.ColumnToCoord(fenflags
.charAt(i
));
488 // Fen string fully describes the game state
491 // In printDiagram() fen isn't supply because only getPpath() is used
492 // TODO: find a better solution!
494 const fenParsed
= V
.ParseFen(fen
);
495 this.board
= V
.GetBoard(fenParsed
.position
);
496 this.turn
= fenParsed
.turn
;
497 this.movesCount
= parseInt(fenParsed
.movesCount
);
498 this.setOtherVariables(fen
);
501 // Scan board for kings positions
503 this.INIT_COL_KING
= { w: -1, b: -1 };
504 // Squares of white and black king:
505 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
506 const fenRows
= V
.ParseFen(fen
).position
.split("/");
507 const startRow
= { 'w': V
.size
.x
- 1, 'b': 0 };
508 for (let i
= 0; i
< fenRows
.length
; i
++) {
509 let k
= 0; //column index on board
510 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
511 switch (fenRows
[i
].charAt(j
)) {
513 this.kingPos
["b"] = [i
, k
];
514 this.INIT_COL_KING
["b"] = k
;
517 this.kingPos
["w"] = [i
, k
];
518 this.INIT_COL_KING
["w"] = k
;
521 const num
= parseInt(fenRows
[i
].charAt(j
));
522 if (!isNaN(num
)) k
+= num
- 1;
530 // Some additional variables from FEN (variant dependant)
531 setOtherVariables(fen
) {
532 // Set flags and enpassant:
533 const parsedFen
= V
.ParseFen(fen
);
534 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
535 if (V
.HasEnpassant
) {
537 parsedFen
.enpassant
!= "-"
538 ? this.getEpSquare(parsedFen
.enpassant
)
540 this.epSquares
= [epSq
];
542 // Search for kings positions:
546 /////////////////////
550 return { x: 8, y: 8 };
553 // Color of thing on square (i,j). 'undefined' if square is empty
555 return this.board
[i
][j
].charAt(0);
558 // Piece type on square (i,j). 'undefined' if square is empty
560 return this.board
[i
][j
].charAt(1);
563 // Get opponent color
564 static GetOppCol(color
) {
565 return color
== "w" ? "b" : "w";
568 // Pieces codes (for a clearer code)
575 static get KNIGHT() {
578 static get BISHOP() {
589 static get PIECES() {
590 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
598 // Some pieces movements
629 // All possible moves from selected square
630 getPotentialMovesFrom([x
, y
]) {
631 switch (this.getPiece(x
, y
)) {
633 return this.getPotentialPawnMoves([x
, y
]);
635 return this.getPotentialRookMoves([x
, y
]);
637 return this.getPotentialKnightMoves([x
, y
]);
639 return this.getPotentialBishopMoves([x
, y
]);
641 return this.getPotentialQueenMoves([x
, y
]);
643 return this.getPotentialKingMoves([x
, y
]);
645 return []; //never reached
648 // Build a regular move from its initial and destination squares.
649 // tr: transformation
650 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
651 const initColor
= this.getColor(sx
, sy
);
652 const initPiece
= this.getPiece(sx
, sy
);
658 c: tr
? tr
.c : initColor
,
659 p: tr
? tr
.p : initPiece
672 // The opponent piece disappears if we take it
673 if (this.board
[ex
][ey
] != V
.EMPTY
) {
678 c: this.getColor(ex
, ey
),
679 p: this.getPiece(ex
, ey
)
687 // Generic method to find possible moves of non-pawn pieces:
688 // "sliding or jumping"
689 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
691 outerLoop: for (let step
of steps
) {
694 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
695 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
696 if (oneStep
) continue outerLoop
;
700 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
701 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
706 // Special case of en-passant captures: treated separately
707 getEnpassantCaptures([x
, y
], shiftX
) {
708 const Lep
= this.epSquares
.length
;
709 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
710 let enpassantMove
= null;
713 epSquare
.x
== x
+ shiftX
&&
714 Math
.abs(epSquare
.y
- y
) == 1
716 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
717 enpassantMove
.vanish
.push({
720 // Captured piece is usually a pawn, but next line seems harmless
721 p: this.getPiece(x
, epSquare
.y
),
722 c: this.getColor(x
, epSquare
.y
)
725 return !!enpassantMove
? [enpassantMove
] : [];
728 // Consider all potential promotions:
729 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
730 let finalPieces
= [V
.PAWN
];
731 const color
= this.turn
; //this.getColor(x1, y1);
732 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
733 if (x2
== lastRank
) {
734 // promotions arg: special override for Hiddenqueen variant
735 if (!!promotions
) finalPieces
= promotions
;
736 else if (!!V
.PawnSpecs
.promotions
)
737 finalPieces
= V
.PawnSpecs
.promotions
;
740 for (let piece
of finalPieces
) {
741 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
742 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
746 // What are the pawn moves from square x,y ?
747 getPotentialPawnMoves([x
, y
], promotions
) {
748 const color
= this.turn
; //this.getColor(x, y);
749 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
750 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
751 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
753 // Pawn movements in shiftX direction:
754 const getPawnMoves
= (shiftX
) => {
756 // NOTE: next condition is generally true (no pawn on last rank)
757 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
758 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
759 // One square forward
760 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
761 // Next condition because pawns on 1st rank can generally jump
763 V
.PawnSpecs
.twoSquares
&&
765 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
767 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
770 if (this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
) {
772 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
774 V
.PawnSpecs
.threeSquares
&&
775 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
777 // Three squares jump
778 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
784 if (V
.PawnSpecs
.canCapture
) {
785 for (let shiftY
of [-1, 1]) {
791 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
792 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
795 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
800 V
.PawnSpecs
.captureBackward
&&
801 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
802 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
803 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
806 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
817 let pMoves
= getPawnMoves(pawnShiftX
);
818 if (V
.PawnSpecs
.bidirectional
)
819 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
821 if (V
.HasEnpassant
) {
822 // NOTE: backward en-passant captures are not considered
823 // because no rules define them (for now).
824 Array
.prototype.push
.apply(
826 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
833 // What are the rook moves from square x,y ?
834 getPotentialRookMoves(sq
) {
835 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
838 // What are the knight moves from square x,y ?
839 getPotentialKnightMoves(sq
) {
840 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
843 // What are the bishop moves from square x,y ?
844 getPotentialBishopMoves(sq
) {
845 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
848 // What are the queen moves from square x,y ?
849 getPotentialQueenMoves(sq
) {
850 return this.getSlideNJumpMoves(
852 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
856 // What are the king moves from square x,y ?
857 getPotentialKingMoves(sq
) {
858 // Initialize with normal moves
859 let moves
= this.getSlideNJumpMoves(
861 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
864 if (V
.HasCastle
) moves
= moves
.concat(this.getCastleMoves(sq
));
868 // "castleInCheck" arg to let some variants castle under check
869 getCastleMoves([x
, y
], castleInCheck
) {
870 const c
= this.getColor(x
, y
);
871 if (x
!= (c
== "w" ? V
.size
.x
- 1 : 0) || y
!= this.INIT_COL_KING
[c
])
872 return []; //x isn't first rank, or king has moved (shortcut)
875 const oppCol
= V
.GetOppCol(c
);
879 const finalSquares
= [
881 [V
.size
.y
- 2, V
.size
.y
- 3]
886 castleSide
++ //large, then small
888 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
889 // If this code is reached, rook and king are on initial position
891 // NOTE: in some variants this is not a rook
892 const rookPos
= this.castleFlags
[c
][castleSide
];
893 if (this.board
[x
][rookPos
] == V
.EMPTY
|| this.getColor(x
, rookPos
) != c
)
894 // Rook is not here, or changed color (see Benedict)
897 // Nothing on the path of the king ? (and no checks)
898 const castlingPiece
= this.getPiece(x
, rookPos
);
899 const finDist
= finalSquares
[castleSide
][0] - y
;
900 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
904 // NOTE: "castling" arg is used by some variants (Monster),
905 // where "isAttacked" is overloaded in an infinite-recursive way.
906 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
, "castling")) ||
907 (this.board
[x
][i
] != V
.EMPTY
&&
908 // NOTE: next check is enough, because of chessboard constraints
909 (this.getColor(x
, i
) != c
||
910 ![V
.KING
, castlingPiece
].includes(this.getPiece(x
, i
))))
912 continue castlingCheck
;
915 } while (i
!= finalSquares
[castleSide
][0]);
917 // Nothing on the path to the rook?
918 step
= castleSide
== 0 ? -1 : 1;
919 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
920 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
923 // Nothing on final squares, except maybe king and castling rook?
924 for (i
= 0; i
< 2; i
++) {
926 finalSquares
[castleSide
][i
] != rookPos
&&
927 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
929 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
||
930 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
933 continue castlingCheck
;
937 // If this code is reached, castle is valid
943 y: finalSquares
[castleSide
][0],
949 y: finalSquares
[castleSide
][1],
955 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
956 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
959 Math
.abs(y
- rookPos
) <= 2
960 ? { x: x
, y: rookPos
}
961 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
972 // For the interface: possible moves for the current turn from square sq
973 getPossibleMovesFrom(sq
) {
974 return this.filterValid(this.getPotentialMovesFrom(sq
));
977 // TODO: promotions (into R,B,N,Q) should be filtered only once
979 if (moves
.length
== 0) return [];
980 const color
= this.turn
;
981 return moves
.filter(m
=> {
983 const res
= !this.underCheck(color
);
989 getAllPotentialMoves() {
990 const color
= this.turn
;
991 let potentialMoves
= [];
992 for (let i
= 0; i
< V
.size
.x
; i
++) {
993 for (let j
= 0; j
< V
.size
.y
; j
++) {
994 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
995 Array
.prototype.push
.apply(
997 this.getPotentialMovesFrom([i
, j
])
1002 return potentialMoves
;
1005 // Search for all valid moves considering current turn
1006 // (for engine and game end)
1007 getAllValidMoves() {
1008 return this.filterValid(this.getAllPotentialMoves());
1011 // Stop at the first move found
1012 // TODO: not really, it explores all moves from a square (one is enough).
1014 const color
= this.turn
;
1015 for (let i
= 0; i
< V
.size
.x
; i
++) {
1016 for (let j
= 0; j
< V
.size
.y
; j
++) {
1017 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1018 const moves
= this.getPotentialMovesFrom([i
, j
]);
1019 if (moves
.length
> 0) {
1020 for (let k
= 0; k
< moves
.length
; k
++)
1021 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1029 // Check if pieces of given color are attacking (king) on square x,y
1030 isAttacked(sq
, color
) {
1032 this.isAttackedByPawn(sq
, color
) ||
1033 this.isAttackedByRook(sq
, color
) ||
1034 this.isAttackedByKnight(sq
, color
) ||
1035 this.isAttackedByBishop(sq
, color
) ||
1036 this.isAttackedByQueen(sq
, color
) ||
1037 this.isAttackedByKing(sq
, color
)
1041 // Generic method for non-pawn pieces ("sliding or jumping"):
1042 // is x,y attacked by a piece of given color ?
1043 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1044 for (let step
of steps
) {
1045 let rx
= x
+ step
[0],
1047 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1052 V
.OnBoard(rx
, ry
) &&
1053 this.getPiece(rx
, ry
) == piece
&&
1054 this.getColor(rx
, ry
) == color
1062 // Is square x,y attacked by 'color' pawns ?
1063 isAttackedByPawn(sq
, color
) {
1064 const pawnShift
= (color
== "w" ? 1 : -1);
1065 return this.isAttackedBySlideNJump(
1069 [[pawnShift
, 1], [pawnShift
, -1]],
1074 // Is square x,y attacked by 'color' rooks ?
1075 isAttackedByRook(sq
, color
) {
1076 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1079 // Is square x,y attacked by 'color' knights ?
1080 isAttackedByKnight(sq
, color
) {
1081 return this.isAttackedBySlideNJump(
1090 // Is square x,y attacked by 'color' bishops ?
1091 isAttackedByBishop(sq
, color
) {
1092 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1095 // Is square x,y attacked by 'color' queens ?
1096 isAttackedByQueen(sq
, color
) {
1097 return this.isAttackedBySlideNJump(
1101 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1105 // Is square x,y attacked by 'color' king(s) ?
1106 isAttackedByKing(sq
, color
) {
1107 return this.isAttackedBySlideNJump(
1111 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1116 // Is color under check after his move ?
1118 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1124 // Apply a move on board
1125 static PlayOnBoard(board
, move) {
1126 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1127 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1129 // Un-apply the played move
1130 static UndoOnBoard(board
, move) {
1131 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1132 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1139 // if (!this.states) this.states = [];
1140 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1141 // this.states.push(stateFen);
1144 // Save flags (for undo)
1145 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1146 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1147 V
.PlayOnBoard(this.board
, move);
1148 this.turn
= V
.GetOppCol(this.turn
);
1150 this.postPlay(move);
1153 updateCastleFlags(move, piece
) {
1154 const c
= V
.GetOppCol(this.turn
);
1155 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1156 // Update castling flags if rooks are moved
1157 const oppCol
= this.turn
;
1158 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1159 if (piece
== V
.KING
&& move.appear
.length
> 0)
1160 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1162 move.start
.x
== firstRank
&& //our rook moves?
1163 this.castleFlags
[c
].includes(move.start
.y
)
1165 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1166 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1168 // NOTE: not "else if" because a rook could take an opposing rook
1170 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1171 this.castleFlags
[oppCol
].includes(move.end
.y
)
1173 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1174 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1178 // After move is played, update variables + flags
1180 const c
= V
.GetOppCol(this.turn
);
1181 let piece
= undefined;
1182 if (move.vanish
.length
>= 1)
1183 // Usual case, something is moved
1184 piece
= move.vanish
[0].p
;
1186 // Crazyhouse-like variants
1187 piece
= move.appear
[0].p
;
1189 // Update king position + flags
1190 if (piece
== V
.KING
&& move.appear
.length
> 0) {
1191 this.kingPos
[c
][0] = move.appear
[0].x
;
1192 this.kingPos
[c
][1] = move.appear
[0].y
;
1194 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1201 if (V
.HasEnpassant
) this.epSquares
.pop();
1202 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1203 V
.UndoOnBoard(this.board
, move);
1204 this.turn
= V
.GetOppCol(this.turn
);
1206 this.postUndo(move);
1209 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1210 // if (stateFen != this.states[this.states.length-1]) debugger;
1211 // this.states.pop();
1214 // After move is undo-ed *and flags resetted*, un-update other variables
1215 // TODO: more symmetry, by storing flags increment in move (?!)
1217 // (Potentially) Reset king position
1218 const c
= this.getColor(move.start
.x
, move.start
.y
);
1219 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1220 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1226 // What is the score ? (Interesting if game is over)
1228 if (this.atLeastOneMove()) return "*";
1230 const color
= this.turn
;
1231 // No valid move: stalemate or checkmate?
1232 if (!this.underCheck(color
)) return "1/2";
1234 return (color
== "w" ? "0-1" : "1-0");
1241 static get VALUES() {
1252 // "Checkmate" (unreachable eval)
1253 static get INFINITY() {
1257 // At this value or above, the game is over
1258 static get THRESHOLD_MATE() {
1262 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1263 static get SEARCH_DEPTH() {
1267 // 'movesList' arg for some variants to provide a custom list
1268 getComputerMove(movesList
) {
1269 const maxeval
= V
.INFINITY
;
1270 const color
= this.turn
;
1271 let moves1
= movesList
|| this.getAllValidMoves();
1273 if (moves1
.length
== 0)
1274 // TODO: this situation should not happen
1277 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1278 for (let i
= 0; i
< moves1
.length
; i
++) {
1279 this.play(moves1
[i
]);
1280 const score1
= this.getCurrentScore();
1281 if (score1
!= "*") {
1285 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1287 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1288 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1289 this.undo(moves1
[i
]);
1292 // Initial self evaluation is very low: "I'm checkmated"
1293 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1294 // Initial enemy evaluation is very low too, for him
1295 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1296 // Second half-move:
1297 let moves2
= this.getAllValidMoves();
1298 for (let j
= 0; j
< moves2
.length
; j
++) {
1299 this.play(moves2
[j
]);
1300 const score2
= this.getCurrentScore();
1301 let evalPos
= 0; //1/2 value
1304 evalPos
= this.evalPosition();
1314 (color
== "w" && evalPos
< eval2
) ||
1315 (color
== "b" && evalPos
> eval2
)
1319 this.undo(moves2
[j
]);
1322 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1323 (color
== "b" && eval2
< moves1
[i
].eval
)
1325 moves1
[i
].eval
= eval2
;
1327 this.undo(moves1
[i
]);
1329 moves1
.sort((a
, b
) => {
1330 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1332 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1334 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1335 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1336 for (let i
= 0; i
< moves1
.length
; i
++) {
1337 this.play(moves1
[i
]);
1338 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1340 0.1 * moves1
[i
].eval
+
1341 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1342 this.undo(moves1
[i
]);
1344 moves1
.sort((a
, b
) => {
1345 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1349 let candidates
= [0];
1350 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1352 return moves1
[candidates
[randInt(candidates
.length
)]];
1355 alphabeta(depth
, alpha
, beta
) {
1356 const maxeval
= V
.INFINITY
;
1357 const color
= this.turn
;
1358 const score
= this.getCurrentScore();
1360 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1361 if (depth
== 0) return this.evalPosition();
1362 const moves
= this.getAllValidMoves();
1363 let v
= color
== "w" ? -maxeval : maxeval
;
1365 for (let i
= 0; i
< moves
.length
; i
++) {
1366 this.play(moves
[i
]);
1367 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1368 this.undo(moves
[i
]);
1369 alpha
= Math
.max(alpha
, v
);
1370 if (alpha
>= beta
) break; //beta cutoff
1375 for (let i
= 0; i
< moves
.length
; i
++) {
1376 this.play(moves
[i
]);
1377 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1378 this.undo(moves
[i
]);
1379 beta
= Math
.min(beta
, v
);
1380 if (alpha
>= beta
) break; //alpha cutoff
1388 // Just count material for now
1389 for (let i
= 0; i
< V
.size
.x
; i
++) {
1390 for (let j
= 0; j
< V
.size
.y
; j
++) {
1391 if (this.board
[i
][j
] != V
.EMPTY
) {
1392 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1393 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1400 /////////////////////////
1401 // MOVES + GAME NOTATION
1402 /////////////////////////
1404 // Context: just before move is played, turn hasn't changed
1405 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1407 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1409 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1411 // Translate final square
1412 const finalSquare
= V
.CoordsToSquare(move.end
);
1414 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1415 if (piece
== V
.PAWN
) {
1418 if (move.vanish
.length
> move.appear
.length
) {
1420 const startColumn
= V
.CoordToColumn(move.start
.y
);
1421 notation
= startColumn
+ "x" + finalSquare
;
1423 else notation
= finalSquare
;
1424 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1426 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1431 piece
.toUpperCase() +
1432 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1437 static GetUnambiguousNotation(move) {
1438 // Machine-readable format with all the informations about the move
1440 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1441 ? V
.CoordsToSquare(move.start
)
1444 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1445 ? V
.CoordsToSquare(move.end
)
1448 (!!move.appear
&& move.appear
.length
> 0
1449 ? move.appear
.map(a
=>
1450 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1453 (!!move.vanish
&& move.vanish
.length
> 0
1454 ? move.vanish
.map(a
=>
1455 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")