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
|| { x: o
.vanish
[0].x
, y: o
.vanish
[0].y
};
26 this.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
{
37 // Some variants don't have flags:
38 static get HasFlags() {
43 static get HasCastle() {
47 // Pawns specifications
48 static get PawnSpecs() {
50 directions: { 'w': -1, 'b': 1 },
51 initShift: { w: 1, b: 1 },
54 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
56 captureBackward: false,
61 // En-passant captures need a stack of squares:
62 static get HasEnpassant() {
66 // Some variants cannot have analyse mode
67 static get CanAnalyze() {
70 // Patch: issues with javascript OOP, objects can't access static fields.
75 // Some variants show incomplete information,
76 // and thus show only a partial moves list or no list at all.
77 static get ShowMoves() {
84 // Sometimes moves must remain hidden until game ends
85 static get SomeHiddenMoves() {
88 get someHiddenMoves() {
89 return V
.SomeHiddenMoves
;
92 // Generally true, unless the variant includes random effects
93 static get CorrConfirm() {
97 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
102 // Some variants always show the same orientation
103 static get CanFlip() {
110 // For (generally old) variants without checkered board
111 static get Monochrome() {
115 // Some games are drawn unusually (bottom right corner is black)
116 static get DarkBottomRight() {
120 // Some variants require lines drawing
124 // Draw all inter-squares lines
125 for (let i
= 0; i
<= V
.size
.x
; i
++)
126 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
127 for (let j
= 0; j
<= V
.size
.y
; j
++)
128 lines
.push([[0, j
], [V
.size
.x
, j
]]);
134 // In some variants, the player who repeat a position loses
135 static get LoseOnRepetition() {
138 // And in some others (Iceage), repetitions should be ignored:
139 static get IgnoreRepetition() {
143 // At some stages, some games could wait clicks only:
148 // Some variants use click infos:
153 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
158 static get IMAGE_EXTENSION() {
159 // All pieces should be in the SVG format
163 // Turn "wb" into "B" (for FEN)
164 static board2fen(b
) {
165 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
168 // Turn "p" into "bp" (for board)
169 static fen2board(f
) {
170 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
173 // Check if FEN describes a board situation correctly
174 static IsGoodFen(fen
) {
175 const fenParsed
= V
.ParseFen(fen
);
177 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
179 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
180 // 3) Check moves count
181 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
184 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
186 // 5) Check enpassant
189 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
196 // Is position part of the FEN a priori correct?
197 static IsGoodPosition(position
) {
198 if (position
.length
== 0) return false;
199 const rows
= position
.split("/");
200 if (rows
.length
!= V
.size
.x
) return false;
201 let kings
= { "k": 0, "K": 0 };
202 for (let row
of rows
) {
204 for (let i
= 0; i
< row
.length
; i
++) {
205 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
206 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
208 const num
= parseInt(row
[i
], 10);
209 if (isNaN(num
) || num
<= 0) return false;
213 if (sumElts
!= V
.size
.y
) return false;
215 // Both kings should be on board. Exactly one per color.
216 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
221 static IsGoodTurn(turn
) {
222 return ["w", "b"].includes(turn
);
226 static IsGoodFlags(flags
) {
227 // NOTE: a little too permissive to work with more variants
228 return !!flags
.match(/^[a-z]{4,4}$/);
231 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
232 static IsGoodEnpassant(enpassant
) {
233 if (enpassant
!= "-") {
234 const ep
= V
.SquareToCoords(enpassant
);
235 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
240 // 3 --> d (column number to letter)
241 static CoordToColumn(colnum
) {
242 return String
.fromCharCode(97 + colnum
);
245 // d --> 3 (column letter to number)
246 static ColumnToCoord(column
) {
247 return column
.charCodeAt(0) - 97;
251 static SquareToCoords(sq
) {
253 // NOTE: column is always one char => max 26 columns
254 // row is counted from black side => subtraction
255 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
256 y: sq
[0].charCodeAt() - 97
261 static CoordsToSquare(coords
) {
262 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
265 // Path to pieces (standard ones in pieces/ folder)
270 // Path to promotion pieces (usually the same)
272 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
275 // Aggregates flags into one object
277 return this.castleFlags
;
281 disaggregateFlags(flags
) {
282 this.castleFlags
= flags
;
285 // En-passant square, if any
286 getEpSquare(moveOrSquare
) {
287 if (!moveOrSquare
) return undefined; //TODO: necessary line?!
288 if (typeof moveOrSquare
=== "string") {
289 const square
= moveOrSquare
;
290 if (square
== "-") return undefined;
291 return V
.SquareToCoords(square
);
293 // Argument is a move:
294 const move = moveOrSquare
;
295 const s
= move.start
,
299 Math
.abs(s
.x
- e
.x
) == 2 &&
300 // Next conditions for variants like Atomic or Rifle, Recycle...
301 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
302 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
309 return undefined; //default
312 // Can thing on square1 take thing on square2
313 canTake([x1
, y1
], [x2
, y2
]) {
314 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
317 // Is (x,y) on the chessboard?
318 static OnBoard(x
, y
) {
319 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
322 // Used in interface: 'side' arg == player color
323 canIplay(side
, [x
, y
]) {
324 return this.turn
== side
&& this.getColor(x
, y
) == side
;
327 // On which squares is color under check ? (for interface)
329 const color
= this.turn
;
331 this.underCheck(color
)
332 // kingPos must be duplicated, because it may change:
333 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
341 // Setup the initial random (asymmetric) position
342 static GenRandInitFen(randomness
) {
345 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
347 let pieces
= { w: new Array(8), b: new Array(8) };
349 // Shuffle pieces on first (and last rank if randomness == 2)
350 for (let c
of ["w", "b"]) {
351 if (c
== 'b' && randomness
== 1) {
352 pieces
['b'] = pieces
['w'];
357 let positions
= ArrayFun
.range(8);
359 // Get random squares for bishops
360 let randIndex
= 2 * randInt(4);
361 const bishop1Pos
= positions
[randIndex
];
362 // The second bishop must be on a square of different color
363 let randIndex_tmp
= 2 * randInt(4) + 1;
364 const bishop2Pos
= positions
[randIndex_tmp
];
365 // Remove chosen squares
366 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
367 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
369 // Get random squares for knights
370 randIndex
= randInt(6);
371 const knight1Pos
= positions
[randIndex
];
372 positions
.splice(randIndex
, 1);
373 randIndex
= randInt(5);
374 const knight2Pos
= positions
[randIndex
];
375 positions
.splice(randIndex
, 1);
377 // Get random square for queen
378 randIndex
= randInt(4);
379 const queenPos
= positions
[randIndex
];
380 positions
.splice(randIndex
, 1);
382 // Rooks and king positions are now fixed,
383 // because of the ordering rook-king-rook
384 const rook1Pos
= positions
[0];
385 const kingPos
= positions
[1];
386 const rook2Pos
= positions
[2];
388 // Finally put the shuffled pieces in the board array
389 pieces
[c
][rook1Pos
] = "r";
390 pieces
[c
][knight1Pos
] = "n";
391 pieces
[c
][bishop1Pos
] = "b";
392 pieces
[c
][queenPos
] = "q";
393 pieces
[c
][kingPos
] = "k";
394 pieces
[c
][bishop2Pos
] = "b";
395 pieces
[c
][knight2Pos
] = "n";
396 pieces
[c
][rook2Pos
] = "r";
397 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
399 // Add turn + flags + enpassant
401 pieces
["b"].join("") +
402 "/pppppppp/8/8/8/8/PPPPPPPP/" +
403 pieces
["w"].join("").toUpperCase() +
404 " w 0 " + flags
+ " -"
408 // "Parse" FEN: just return untransformed string data
409 static ParseFen(fen
) {
410 const fenParts
= fen
.split(" ");
412 position: fenParts
[0],
414 movesCount: fenParts
[2]
417 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
418 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
422 // Return current fen (game state)
425 this.getBaseFen() + " " +
426 this.getTurnFen() + " " +
428 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
429 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
434 // Omit movesCount, only variable allowed to differ
436 this.getBaseFen() + "_" +
438 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
439 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
443 // Position part of the FEN string
445 const format
= (count
) => {
446 // if more than 9 consecutive free spaces, break the integer,
447 // otherwise FEN parsing will fail.
448 if (count
<= 9) return count
;
449 // Most boards of size < 18:
450 if (count
<= 18) return "9" + (count
- 9);
452 return "99" + (count
- 18);
455 for (let i
= 0; i
< V
.size
.x
; i
++) {
457 for (let j
= 0; j
< V
.size
.y
; j
++) {
458 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
460 if (emptyCount
> 0) {
461 // Add empty squares in-between
462 position
+= format(emptyCount
);
465 position
+= V
.board2fen(this.board
[i
][j
]);
468 if (emptyCount
> 0) {
470 position
+= format(emptyCount
);
472 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
481 // Flags part of the FEN string
485 for (let c
of ["w", "b"])
486 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
490 // Enpassant part of the FEN string
492 const L
= this.epSquares
.length
;
493 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
494 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
497 // Turn position fen into double array ["wb","wp","bk",...]
498 static GetBoard(position
) {
499 const rows
= position
.split("/");
500 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
501 for (let i
= 0; i
< rows
.length
; i
++) {
503 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
504 const character
= rows
[i
][indexInRow
];
505 const num
= parseInt(character
, 10);
506 // If num is a number, just shift j:
507 if (!isNaN(num
)) j
+= num
;
508 // Else: something at position i,j
509 else board
[i
][j
++] = V
.fen2board(character
);
515 // Extract (relevant) flags from fen
517 // white a-castle, h-castle, black a-castle, h-castle
518 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
519 for (let i
= 0; i
< 4; i
++) {
520 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
521 V
.ColumnToCoord(fenflags
.charAt(i
));
528 // Fen string fully describes the game state
531 // In printDiagram() fen isn't supply because only getPpath() is used
532 // TODO: find a better solution!
534 const fenParsed
= V
.ParseFen(fen
);
535 this.board
= V
.GetBoard(fenParsed
.position
);
536 this.turn
= fenParsed
.turn
;
537 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
538 this.setOtherVariables(fen
);
541 // Scan board for kings positions
542 // TODO: should be done from board, no need for the complete FEN
544 // Squares of white and black king:
545 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
546 const fenRows
= V
.ParseFen(fen
).position
.split("/");
547 for (let i
= 0; i
< fenRows
.length
; i
++) {
548 let k
= 0; //column index on board
549 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
550 switch (fenRows
[i
].charAt(j
)) {
552 this.kingPos
["b"] = [i
, k
];
555 this.kingPos
["w"] = [i
, k
];
558 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
559 if (!isNaN(num
)) k
+= num
- 1;
567 // Some additional variables from FEN (variant dependant)
568 setOtherVariables(fen
) {
569 // Set flags and enpassant:
570 const parsedFen
= V
.ParseFen(fen
);
571 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
572 if (V
.HasEnpassant
) {
574 parsedFen
.enpassant
!= "-"
575 ? this.getEpSquare(parsedFen
.enpassant
)
577 this.epSquares
= [epSq
];
579 // Search for kings positions:
583 /////////////////////
587 return { x: 8, y: 8 };
590 // Color of thing on square (i,j). 'undefined' if square is empty
592 return this.board
[i
][j
].charAt(0);
595 // Piece type on square (i,j). 'undefined' if square is empty
597 return this.board
[i
][j
].charAt(1);
600 // Get opponent color
601 static GetOppCol(color
) {
602 return color
== "w" ? "b" : "w";
605 // Pieces codes (for a clearer code)
612 static get KNIGHT() {
615 static get BISHOP() {
626 static get PIECES() {
627 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
635 // Some pieces movements
666 // All possible moves from selected square
667 getPotentialMovesFrom(sq
) {
668 switch (this.getPiece(sq
[0], sq
[1])) {
669 case V
.PAWN: return this.getPotentialPawnMoves(sq
);
670 case V
.ROOK: return this.getPotentialRookMoves(sq
);
671 case V
.KNIGHT: return this.getPotentialKnightMoves(sq
);
672 case V
.BISHOP: return this.getPotentialBishopMoves(sq
);
673 case V
.QUEEN: return this.getPotentialQueenMoves(sq
);
674 case V
.KING: return this.getPotentialKingMoves(sq
);
676 return []; //never reached (but some variants may use it: Bario...)
679 // Build a regular move from its initial and destination squares.
680 // tr: transformation
681 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
682 const initColor
= this.getColor(sx
, sy
);
683 const initPiece
= this.board
[sx
][sy
].charAt(1);
689 c: !!tr
? tr
.c : initColor
,
690 p: !!tr
? tr
.p : initPiece
703 // The opponent piece disappears if we take it
704 if (this.board
[ex
][ey
] != V
.EMPTY
) {
709 c: this.getColor(ex
, ey
),
710 p: this.board
[ex
][ey
].charAt(1)
718 // Generic method to find possible moves of non-pawn pieces:
719 // "sliding or jumping"
720 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
722 outerLoop: for (let step
of steps
) {
725 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
726 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
727 if (!!oneStep
) continue outerLoop
;
731 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
732 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
737 // Special case of en-passant captures: treated separately
738 getEnpassantCaptures([x
, y
], shiftX
) {
739 const Lep
= this.epSquares
.length
;
740 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
741 let enpassantMove
= null;
744 epSquare
.x
== x
+ shiftX
&&
745 Math
.abs(epSquare
.y
- y
) == 1
747 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
748 enpassantMove
.vanish
.push({
751 p: this.board
[x
][epSquare
.y
].charAt(1),
752 c: this.getColor(x
, epSquare
.y
)
755 return !!enpassantMove
? [enpassantMove
] : [];
758 // Consider all potential promotions:
759 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
760 let finalPieces
= [V
.PAWN
];
761 const color
= this.turn
; //this.getColor(x1, y1);
762 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
763 if (x2
== lastRank
) {
764 // promotions arg: special override for Hiddenqueen variant
765 if (!!promotions
) finalPieces
= promotions
;
766 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
769 for (let piece
of finalPieces
) {
770 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
771 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
775 // What are the pawn moves from square x,y ?
776 getPotentialPawnMoves([x
, y
], promotions
) {
777 const color
= this.turn
; //this.getColor(x, y);
778 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
779 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
780 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
781 const forward
= (color
== 'w' ? -1 : 1);
783 // Pawn movements in shiftX direction:
784 const getPawnMoves
= (shiftX
) => {
786 // NOTE: next condition is generally true (no pawn on last rank)
787 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
788 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
789 // One square forward (or backward)
790 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
791 // Next condition because pawns on 1st rank can generally jump
793 V
.PawnSpecs
.twoSquares
&&
795 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
797 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
802 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
805 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
807 V
.PawnSpecs
.threeSquares
&&
808 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
810 // Three squares jump
811 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
817 if (V
.PawnSpecs
.canCapture
) {
818 for (let shiftY
of [-1, 1]) {
819 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
821 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
822 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
825 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
830 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
831 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
832 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
833 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
836 [x
, y
], [x
- shiftX
, y
+ shiftY
],
847 let pMoves
= getPawnMoves(pawnShiftX
);
848 if (V
.PawnSpecs
.bidirectional
)
849 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
851 if (V
.HasEnpassant
) {
852 // NOTE: backward en-passant captures are not considered
853 // because no rules define them (for now).
854 Array
.prototype.push
.apply(
856 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
863 // What are the rook moves from square x,y ?
864 getPotentialRookMoves(sq
) {
865 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
868 // What are the knight moves from square x,y ?
869 getPotentialKnightMoves(sq
) {
870 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
873 // What are the bishop moves from square x,y ?
874 getPotentialBishopMoves(sq
) {
875 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
878 // What are the queen moves from square x,y ?
879 getPotentialQueenMoves(sq
) {
880 return this.getSlideNJumpMoves(
882 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
886 // What are the king moves from square x,y ?
887 getPotentialKingMoves(sq
) {
888 // Initialize with normal moves
889 let moves
= this.getSlideNJumpMoves(
891 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
894 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
895 moves
= moves
.concat(this.getCastleMoves(sq
));
899 // "castleInCheck" arg to let some variants castle under check
900 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
901 const c
= this.getColor(x
, y
);
904 const oppCol
= V
.GetOppCol(c
);
907 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
908 const castlingKing
= this.board
[x
][y
].charAt(1);
912 castleSide
++ //large, then small
914 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
915 // If this code is reached, rook and king are on initial position
917 // NOTE: in some variants this is not a rook
918 const rookPos
= this.castleFlags
[c
][castleSide
];
919 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
921 this.board
[x
][rookPos
] == V
.EMPTY
||
922 this.getColor(x
, rookPos
) != c
||
923 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
925 // Rook is not here, or changed color (see Benedict)
929 // Nothing on the path of the king ? (and no checks)
930 const finDist
= finalSquares
[castleSide
][0] - y
;
931 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
935 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
937 this.board
[x
][i
] != V
.EMPTY
&&
938 // NOTE: next check is enough, because of chessboard constraints
939 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
942 continue castlingCheck
;
945 } while (i
!= finalSquares
[castleSide
][0]);
947 // Nothing on the path to the rook?
948 step
= castleSide
== 0 ? -1 : 1;
949 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
950 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
953 // Nothing on final squares, except maybe king and castling rook?
954 for (i
= 0; i
< 2; i
++) {
956 finalSquares
[castleSide
][i
] != rookPos
&&
957 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
959 finalSquares
[castleSide
][i
] != y
||
960 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
963 continue castlingCheck
;
967 // If this code is reached, castle is valid
973 y: finalSquares
[castleSide
][0],
979 y: finalSquares
[castleSide
][1],
985 // King might be initially disguised (Titan...)
986 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
987 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
990 Math
.abs(y
- rookPos
) <= 2
991 ? { x: x
, y: rookPos
}
992 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1000 ////////////////////
1003 // For the interface: possible moves for the current turn from square sq
1004 getPossibleMovesFrom(sq
) {
1005 return this.filterValid(this.getPotentialMovesFrom(sq
));
1008 // TODO: promotions (into R,B,N,Q) should be filtered only once
1009 filterValid(moves
) {
1010 if (moves
.length
== 0) return [];
1011 const color
= this.turn
;
1012 return moves
.filter(m
=> {
1014 const res
= !this.underCheck(color
);
1020 getAllPotentialMoves() {
1021 const color
= this.turn
;
1022 let potentialMoves
= [];
1023 for (let i
= 0; i
< V
.size
.x
; i
++) {
1024 for (let j
= 0; j
< V
.size
.y
; j
++) {
1025 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1026 Array
.prototype.push
.apply(
1028 this.getPotentialMovesFrom([i
, j
])
1033 return potentialMoves
;
1036 // Search for all valid moves considering current turn
1037 // (for engine and game end)
1038 getAllValidMoves() {
1039 return this.filterValid(this.getAllPotentialMoves());
1042 // Stop at the first move found
1043 // TODO: not really, it explores all moves from a square (one is enough).
1044 // Possible fix: add extra arg "oneMove" to getPotentialMovesFrom,
1045 // and then return only boolean true at first move found
1046 // (in all getPotentialXXXMoves() ... for all variants ...)
1048 const color
= this.turn
;
1049 for (let i
= 0; i
< V
.size
.x
; i
++) {
1050 for (let j
= 0; j
< V
.size
.y
; j
++) {
1051 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1052 const moves
= this.getPotentialMovesFrom([i
, j
]);
1053 if (moves
.length
> 0) {
1054 for (let k
= 0; k
< moves
.length
; k
++)
1055 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1063 // Check if pieces of given color are attacking (king) on square x,y
1064 isAttacked(sq
, color
) {
1066 this.isAttackedByPawn(sq
, color
) ||
1067 this.isAttackedByRook(sq
, color
) ||
1068 this.isAttackedByKnight(sq
, color
) ||
1069 this.isAttackedByBishop(sq
, color
) ||
1070 this.isAttackedByQueen(sq
, color
) ||
1071 this.isAttackedByKing(sq
, color
)
1075 // Generic method for non-pawn pieces ("sliding or jumping"):
1076 // is x,y attacked by a piece of given color ?
1077 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1078 for (let step
of steps
) {
1079 let rx
= x
+ step
[0],
1081 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1086 V
.OnBoard(rx
, ry
) &&
1087 this.board
[rx
][ry
] != V
.EMPTY
&&
1088 this.getPiece(rx
, ry
) == piece
&&
1089 this.getColor(rx
, ry
) == color
1097 // Is square x,y attacked by 'color' pawns ?
1098 isAttackedByPawn(sq
, color
) {
1099 const pawnShift
= (color
== "w" ? 1 : -1);
1100 return this.isAttackedBySlideNJump(
1104 [[pawnShift
, 1], [pawnShift
, -1]],
1109 // Is square x,y attacked by 'color' rooks ?
1110 isAttackedByRook(sq
, color
) {
1111 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1114 // Is square x,y attacked by 'color' knights ?
1115 isAttackedByKnight(sq
, color
) {
1116 return this.isAttackedBySlideNJump(
1125 // Is square x,y attacked by 'color' bishops ?
1126 isAttackedByBishop(sq
, color
) {
1127 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1130 // Is square x,y attacked by 'color' queens ?
1131 isAttackedByQueen(sq
, color
) {
1132 return this.isAttackedBySlideNJump(
1136 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1140 // Is square x,y attacked by 'color' king(s) ?
1141 isAttackedByKing(sq
, color
) {
1142 return this.isAttackedBySlideNJump(
1146 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1151 // Is color under check after his move ?
1153 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1159 // Apply a move on board
1160 static PlayOnBoard(board
, move) {
1161 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1162 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1164 // Un-apply the played move
1165 static UndoOnBoard(board
, move) {
1166 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1167 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1174 // if (!this.states) this.states = [];
1175 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1176 // this.states.push(stateFen);
1179 // Save flags (for undo)
1180 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1181 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1182 V
.PlayOnBoard(this.board
, move);
1183 this.turn
= V
.GetOppCol(this.turn
);
1185 this.postPlay(move);
1188 updateCastleFlags(move, piece
, color
) {
1189 // TODO: check flags. If already off, no need to always re-evaluate
1190 const c
= color
|| V
.GetOppCol(this.turn
);
1191 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1192 // Update castling flags if rooks are moved
1193 const oppCol
= this.turn
;
1194 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1195 if (piece
== V
.KING
&& move.appear
.length
> 0)
1196 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1198 move.start
.x
== firstRank
&& //our rook moves?
1199 this.castleFlags
[c
].includes(move.start
.y
)
1201 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1202 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1204 // NOTE: not "else if" because a rook could take an opposing rook
1206 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1207 this.castleFlags
[oppCol
].includes(move.end
.y
)
1209 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1210 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1214 // After move is played, update variables + flags
1216 const c
= V
.GetOppCol(this.turn
);
1217 let piece
= undefined;
1218 if (move.vanish
.length
>= 1)
1219 // Usual case, something is moved
1220 piece
= move.vanish
[0].p
;
1222 // Crazyhouse-like variants
1223 piece
= move.appear
[0].p
;
1225 // Update king position + flags
1226 if (piece
== V
.KING
&& move.appear
.length
> 0)
1227 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1228 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1235 if (V
.HasEnpassant
) this.epSquares
.pop();
1236 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1237 V
.UndoOnBoard(this.board
, move);
1238 this.turn
= V
.GetOppCol(this.turn
);
1240 this.postUndo(move);
1243 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1244 // if (stateFen != this.states[this.states.length-1]) debugger;
1245 // this.states.pop();
1248 // After move is undo-ed *and flags resetted*, un-update other variables
1249 // TODO: more symmetry, by storing flags increment in move (?!)
1251 // (Potentially) Reset king position
1252 const c
= this.getColor(move.start
.x
, move.start
.y
);
1253 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1254 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1260 // What is the score ? (Interesting if game is over)
1262 if (this.atLeastOneMove()) return "*";
1264 const color
= this.turn
;
1265 // No valid move: stalemate or checkmate?
1266 if (!this.underCheck(color
)) return "1/2";
1268 return (color
== "w" ? "0-1" : "1-0");
1275 static get VALUES() {
1286 // "Checkmate" (unreachable eval)
1287 static get INFINITY() {
1291 // At this value or above, the game is over
1292 static get THRESHOLD_MATE() {
1296 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1297 static get SEARCH_DEPTH() {
1301 // 'movesList' arg for some variants to provide a custom list
1302 getComputerMove(movesList
) {
1303 const maxeval
= V
.INFINITY
;
1304 const color
= this.turn
;
1305 let moves1
= movesList
|| this.getAllValidMoves();
1307 if (moves1
.length
== 0)
1308 // TODO: this situation should not happen
1311 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1312 for (let i
= 0; i
< moves1
.length
; i
++) {
1313 this.play(moves1
[i
]);
1314 const score1
= this.getCurrentScore();
1315 if (score1
!= "*") {
1319 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1321 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1322 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1323 this.undo(moves1
[i
]);
1326 // Initial self evaluation is very low: "I'm checkmated"
1327 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1328 // Initial enemy evaluation is very low too, for him
1329 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1330 // Second half-move:
1331 let moves2
= this.getAllValidMoves();
1332 for (let j
= 0; j
< moves2
.length
; j
++) {
1333 this.play(moves2
[j
]);
1334 const score2
= this.getCurrentScore();
1335 let evalPos
= 0; //1/2 value
1338 evalPos
= this.evalPosition();
1348 (color
== "w" && evalPos
< eval2
) ||
1349 (color
== "b" && evalPos
> eval2
)
1353 this.undo(moves2
[j
]);
1356 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1357 (color
== "b" && eval2
< moves1
[i
].eval
)
1359 moves1
[i
].eval
= eval2
;
1361 this.undo(moves1
[i
]);
1363 moves1
.sort((a
, b
) => {
1364 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1366 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1368 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1369 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1370 for (let i
= 0; i
< moves1
.length
; i
++) {
1371 this.play(moves1
[i
]);
1372 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1374 0.1 * moves1
[i
].eval
+
1375 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1376 this.undo(moves1
[i
]);
1378 moves1
.sort((a
, b
) => {
1379 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1383 let candidates
= [0];
1384 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1386 return moves1
[candidates
[randInt(candidates
.length
)]];
1389 alphabeta(depth
, alpha
, beta
) {
1390 const maxeval
= V
.INFINITY
;
1391 const color
= this.turn
;
1392 const score
= this.getCurrentScore();
1394 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1395 if (depth
== 0) return this.evalPosition();
1396 const moves
= this.getAllValidMoves();
1397 let v
= color
== "w" ? -maxeval : maxeval
;
1399 for (let i
= 0; i
< moves
.length
; i
++) {
1400 this.play(moves
[i
]);
1401 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1402 this.undo(moves
[i
]);
1403 alpha
= Math
.max(alpha
, v
);
1404 if (alpha
>= beta
) break; //beta cutoff
1409 for (let i
= 0; i
< moves
.length
; i
++) {
1410 this.play(moves
[i
]);
1411 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1412 this.undo(moves
[i
]);
1413 beta
= Math
.min(beta
, v
);
1414 if (alpha
>= beta
) break; //alpha cutoff
1422 // Just count material for now
1423 for (let i
= 0; i
< V
.size
.x
; i
++) {
1424 for (let j
= 0; j
< V
.size
.y
; j
++) {
1425 if (this.board
[i
][j
] != V
.EMPTY
) {
1426 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1427 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1434 /////////////////////////
1435 // MOVES + GAME NOTATION
1436 /////////////////////////
1438 // Context: just before move is played, turn hasn't changed
1439 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1441 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1443 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1445 // Translate final square
1446 const finalSquare
= V
.CoordsToSquare(move.end
);
1448 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1449 if (piece
== V
.PAWN
) {
1452 if (move.vanish
.length
> move.appear
.length
) {
1454 const startColumn
= V
.CoordToColumn(move.start
.y
);
1455 notation
= startColumn
+ "x" + finalSquare
;
1457 else notation
= finalSquare
;
1458 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1460 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1465 piece
.toUpperCase() +
1466 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1471 static GetUnambiguousNotation(move) {
1472 // Machine-readable format with all the informations about the move
1474 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1475 ? V
.CoordsToSquare(move.start
)
1478 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1479 ? V
.CoordsToSquare(move.end
)
1482 (!!move.appear
&& move.appear
.length
> 0
1483 ? move.appear
.map(a
=>
1484 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1487 (!!move.vanish
&& move.vanish
.length
> 0
1488 ? move.vanish
.map(a
=>
1489 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")