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 static get Options() {
42 variable: "randomness",
45 { label: "Deterministic", value: 0 },
46 { label: "Symmetric random", value: 1 },
47 { label: "Asymmetric random", value: 2 }
55 static AbbreviateOptions(opts
) {
57 // Randomness is a special option: (TODO?)
58 //return "R" + opts.randomness;
61 static IsValidOptions(opts
) {
65 // Some variants don't have flags:
66 static get HasFlags() {
71 static get HasCastle() {
75 // Pawns specifications
76 static get PawnSpecs() {
78 directions: { 'w': -1, 'b': 1 },
79 initShift: { w: 1, b: 1 },
82 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
84 captureBackward: false,
89 // En-passant captures need a stack of squares:
90 static get HasEnpassant() {
94 // Some variants cannot have analyse mode
95 static get CanAnalyze() {
98 // Patch: issues with javascript OOP, objects can't access static fields.
103 // Some variants show incomplete information,
104 // and thus show only a partial moves list or no list at all.
105 static get ShowMoves() {
112 // Sometimes moves must remain hidden until game ends
113 static get SomeHiddenMoves() {
116 get someHiddenMoves() {
117 return V
.SomeHiddenMoves
;
120 // Generally true, unless the variant includes random effects
121 static get CorrConfirm() {
125 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
126 get showFirstTurn() {
130 // Some variants always show the same orientation
131 static get CanFlip() {
138 // NOTE: these will disappear once each variant has its dedicated SVG board.
139 // For (generally old) variants without checkered board
140 static get Monochrome() {
143 // Some games are drawn unusually (bottom right corner is black)
144 static get DarkBottomRight() {
147 // Some variants require lines drawing
151 // Draw all inter-squares lines
152 for (let i
= 0; i
<= V
.size
.x
; i
++)
153 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
154 for (let j
= 0; j
<= V
.size
.y
; j
++)
155 lines
.push([[0, j
], [V
.size
.x
, j
]]);
161 // In some variants, the player who repeat a position loses
162 static get LoseOnRepetition() {
165 // And in some others (Iceage), repetitions should be ignored:
166 static get IgnoreRepetition() {
170 // In some variants, result depends on the position:
171 return V
.LoseOnRepetition
;
174 // At some stages, some games could wait clicks only:
179 // Some variants use click infos:
184 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
189 static get IMAGE_EXTENSION() {
190 // All pieces should be in the SVG format
194 // Turn "wb" into "B" (for FEN)
195 static board2fen(b
) {
196 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
199 // Turn "p" into "bp" (for board)
200 static fen2board(f
) {
201 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
204 // Check if FEN describes a board situation correctly
205 static IsGoodFen(fen
) {
206 const fenParsed
= V
.ParseFen(fen
);
208 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
210 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
211 // 3) Check moves count
212 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
215 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
217 // 5) Check enpassant
220 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
227 // Is position part of the FEN a priori correct?
228 static IsGoodPosition(position
) {
229 if (position
.length
== 0) return false;
230 const rows
= position
.split("/");
231 if (rows
.length
!= V
.size
.x
) return false;
232 let kings
= { "k": 0, "K": 0 };
233 for (let row
of rows
) {
235 for (let i
= 0; i
< row
.length
; i
++) {
236 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
237 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
239 const num
= parseInt(row
[i
], 10);
240 if (isNaN(num
) || num
<= 0) return false;
244 if (sumElts
!= V
.size
.y
) return false;
246 // Both kings should be on board. Exactly one per color.
247 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
252 static IsGoodTurn(turn
) {
253 return ["w", "b"].includes(turn
);
257 static IsGoodFlags(flags
) {
258 // NOTE: a little too permissive to work with more variants
259 return !!flags
.match(/^[a-z]{4,4}$/);
262 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
263 static IsGoodEnpassant(enpassant
) {
264 if (enpassant
!= "-") {
265 const ep
= V
.SquareToCoords(enpassant
);
266 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
271 // 3 --> d (column number to letter)
272 static CoordToColumn(colnum
) {
273 return String
.fromCharCode(97 + colnum
);
276 // d --> 3 (column letter to number)
277 static ColumnToCoord(column
) {
278 return column
.charCodeAt(0) - 97;
282 static SquareToCoords(sq
) {
284 // NOTE: column is always one char => max 26 columns
285 // row is counted from black side => subtraction
286 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
287 y: sq
[0].charCodeAt() - 97
292 static CoordsToSquare(coords
) {
293 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
296 // Path to pieces (standard ones in pieces/ folder)
301 // Path to promotion pieces (usually the same)
303 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
306 // Aggregates flags into one object
308 return this.castleFlags
;
312 disaggregateFlags(flags
) {
313 this.castleFlags
= flags
;
316 // En-passant square, if any
317 getEpSquare(moveOrSquare
) {
318 if (!moveOrSquare
) return undefined; //TODO: necessary line?!
319 if (typeof moveOrSquare
=== "string") {
320 const square
= moveOrSquare
;
321 if (square
== "-") return undefined;
322 return V
.SquareToCoords(square
);
324 // Argument is a move:
325 const move = moveOrSquare
;
326 const s
= move.start
,
330 Math
.abs(s
.x
- e
.x
) == 2 &&
331 // Next conditions for variants like Atomic or Rifle, Recycle...
332 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
333 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
340 return undefined; //default
343 // Can thing on square1 take thing on square2
344 canTake([x1
, y1
], [x2
, y2
]) {
345 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
348 // Is (x,y) on the chessboard?
349 static OnBoard(x
, y
) {
350 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
353 // Used in interface: 'side' arg == player color
354 canIplay(side
, [x
, y
]) {
355 return this.turn
== side
&& this.getColor(x
, y
) == side
;
358 // On which squares is color under check ? (for interface)
360 const color
= this.turn
;
362 this.underCheck(color
)
363 // kingPos must be duplicated, because it may change:
364 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
372 // Setup the initial random (asymmetric) position
373 static GenRandInitFen(options
) {
374 if (!options
.randomness
|| options
.randomness
== 0)
376 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
378 let pieces
= { w: new Array(8), b: new Array(8) };
380 // Shuffle pieces on first (and last rank if randomness == 2)
381 for (let c
of ["w", "b"]) {
382 if (c
== 'b' && options
.randomness
== 1) {
383 pieces
['b'] = pieces
['w'];
388 let positions
= ArrayFun
.range(8);
390 // Get random squares for bishops
391 let randIndex
= 2 * randInt(4);
392 const bishop1Pos
= positions
[randIndex
];
393 // The second bishop must be on a square of different color
394 let randIndex_tmp
= 2 * randInt(4) + 1;
395 const bishop2Pos
= positions
[randIndex_tmp
];
396 // Remove chosen squares
397 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
398 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
400 // Get random squares for knights
401 randIndex
= randInt(6);
402 const knight1Pos
= positions
[randIndex
];
403 positions
.splice(randIndex
, 1);
404 randIndex
= randInt(5);
405 const knight2Pos
= positions
[randIndex
];
406 positions
.splice(randIndex
, 1);
408 // Get random square for queen
409 randIndex
= randInt(4);
410 const queenPos
= positions
[randIndex
];
411 positions
.splice(randIndex
, 1);
413 // Rooks and king positions are now fixed,
414 // because of the ordering rook-king-rook
415 const rook1Pos
= positions
[0];
416 const kingPos
= positions
[1];
417 const rook2Pos
= positions
[2];
419 // Finally put the shuffled pieces in the board array
420 pieces
[c
][rook1Pos
] = "r";
421 pieces
[c
][knight1Pos
] = "n";
422 pieces
[c
][bishop1Pos
] = "b";
423 pieces
[c
][queenPos
] = "q";
424 pieces
[c
][kingPos
] = "k";
425 pieces
[c
][bishop2Pos
] = "b";
426 pieces
[c
][knight2Pos
] = "n";
427 pieces
[c
][rook2Pos
] = "r";
428 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
430 // Add turn + flags + enpassant
432 pieces
["b"].join("") +
433 "/pppppppp/8/8/8/8/PPPPPPPP/" +
434 pieces
["w"].join("").toUpperCase() +
435 " w 0 " + flags
+ " -"
439 // "Parse" FEN: just return untransformed string data
440 static ParseFen(fen
) {
441 const fenParts
= fen
.split(" ");
443 position: fenParts
[0],
445 movesCount: fenParts
[2]
448 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
449 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
453 // Return current fen (game state)
456 this.getBaseFen() + " " +
457 this.getTurnFen() + " " +
459 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
460 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
465 // Omit movesCount, only variable allowed to differ
467 this.getBaseFen() + "_" +
469 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
470 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
474 // Position part of the FEN string
476 const format
= (count
) => {
477 // if more than 9 consecutive free spaces, break the integer,
478 // otherwise FEN parsing will fail.
479 if (count
<= 9) return count
;
480 // Most boards of size < 18:
481 if (count
<= 18) return "9" + (count
- 9);
483 return "99" + (count
- 18);
486 for (let i
= 0; i
< V
.size
.x
; i
++) {
488 for (let j
= 0; j
< V
.size
.y
; j
++) {
489 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
491 if (emptyCount
> 0) {
492 // Add empty squares in-between
493 position
+= format(emptyCount
);
496 position
+= V
.board2fen(this.board
[i
][j
]);
499 if (emptyCount
> 0) {
501 position
+= format(emptyCount
);
503 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
512 // Flags part of the FEN string
516 for (let c
of ["w", "b"])
517 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
521 // Enpassant part of the FEN string
523 const L
= this.epSquares
.length
;
524 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
525 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
528 // Turn position fen into double array ["wb","wp","bk",...]
529 static GetBoard(position
) {
530 const rows
= position
.split("/");
531 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
532 for (let i
= 0; i
< rows
.length
; i
++) {
534 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
535 const character
= rows
[i
][indexInRow
];
536 const num
= parseInt(character
, 10);
537 // If num is a number, just shift j:
538 if (!isNaN(num
)) j
+= num
;
539 // Else: something at position i,j
540 else board
[i
][j
++] = V
.fen2board(character
);
546 // Extract (relevant) flags from fen
548 // white a-castle, h-castle, black a-castle, h-castle
549 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
550 for (let i
= 0; i
< 4; i
++) {
551 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
552 V
.ColumnToCoord(fenflags
.charAt(i
));
559 // Fen string fully describes the game state
562 // In printDiagram() fen isn't supply because only getPpath() is used
563 // TODO: find a better solution!
565 const fenParsed
= V
.ParseFen(fen
);
566 this.board
= V
.GetBoard(fenParsed
.position
);
567 this.turn
= fenParsed
.turn
;
568 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
569 this.setOtherVariables(fen
);
572 // Scan board for kings positions
573 // TODO: should be done from board, no need for the complete FEN
575 // Squares of white and black king:
576 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
577 const fenRows
= V
.ParseFen(fen
).position
.split("/");
578 for (let i
= 0; i
< fenRows
.length
; i
++) {
579 let k
= 0; //column index on board
580 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
581 switch (fenRows
[i
].charAt(j
)) {
583 this.kingPos
["b"] = [i
, k
];
586 this.kingPos
["w"] = [i
, k
];
589 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
590 if (!isNaN(num
)) k
+= num
- 1;
598 // Some additional variables from FEN (variant dependant)
599 setOtherVariables(fen
) {
600 // Set flags and enpassant:
601 const parsedFen
= V
.ParseFen(fen
);
602 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
603 if (V
.HasEnpassant
) {
605 parsedFen
.enpassant
!= "-"
606 ? this.getEpSquare(parsedFen
.enpassant
)
608 this.epSquares
= [epSq
];
610 // Search for kings positions:
614 /////////////////////
618 return { x: 8, y: 8 };
621 // Color of thing on square (i,j). 'undefined' if square is empty
623 return this.board
[i
][j
].charAt(0);
626 // Piece type on square (i,j). 'undefined' if square is empty
628 return this.board
[i
][j
].charAt(1);
631 // Get opponent color
632 static GetOppCol(color
) {
633 return color
== "w" ? "b" : "w";
636 // Pieces codes (for a clearer code)
643 static get KNIGHT() {
646 static get BISHOP() {
657 static get PIECES() {
658 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
666 // Some pieces movements
697 // All possible moves from selected square
698 getPotentialMovesFrom(sq
) {
699 switch (this.getPiece(sq
[0], sq
[1])) {
700 case V
.PAWN: return this.getPotentialPawnMoves(sq
);
701 case V
.ROOK: return this.getPotentialRookMoves(sq
);
702 case V
.KNIGHT: return this.getPotentialKnightMoves(sq
);
703 case V
.BISHOP: return this.getPotentialBishopMoves(sq
);
704 case V
.QUEEN: return this.getPotentialQueenMoves(sq
);
705 case V
.KING: return this.getPotentialKingMoves(sq
);
707 return []; //never reached (but some variants may use it: Bario...)
710 // Build a regular move from its initial and destination squares.
711 // tr: transformation
712 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
713 const initColor
= this.getColor(sx
, sy
);
714 const initPiece
= this.board
[sx
][sy
].charAt(1);
720 c: !!tr
? tr
.c : initColor
,
721 p: !!tr
? tr
.p : initPiece
734 // The opponent piece disappears if we take it
735 if (this.board
[ex
][ey
] != V
.EMPTY
) {
740 c: this.getColor(ex
, ey
),
741 p: this.board
[ex
][ey
].charAt(1)
749 // Generic method to find possible moves of non-pawn pieces:
750 // "sliding or jumping"
751 getSlideNJumpMoves([x
, y
], steps
, nbSteps
) {
753 outerLoop: for (let step
of steps
) {
757 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
758 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
759 if (nbSteps
&& ++stepCounter
>= nbSteps
) continue outerLoop
;
763 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
764 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
769 // Special case of en-passant captures: treated separately
770 getEnpassantCaptures([x
, y
], shiftX
) {
771 const Lep
= this.epSquares
.length
;
772 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
773 let enpassantMove
= null;
776 epSquare
.x
== x
+ shiftX
&&
777 Math
.abs(epSquare
.y
- y
) == 1
779 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
780 enpassantMove
.vanish
.push({
783 p: this.board
[x
][epSquare
.y
].charAt(1),
784 c: this.getColor(x
, epSquare
.y
)
787 return !!enpassantMove
? [enpassantMove
] : [];
790 // Consider all potential promotions:
791 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
792 let finalPieces
= [V
.PAWN
];
793 const color
= this.turn
; //this.getColor(x1, y1);
794 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
795 if (x2
== lastRank
) {
796 // promotions arg: special override for Hiddenqueen variant
797 if (!!promotions
) finalPieces
= promotions
;
798 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
800 for (let piece
of finalPieces
) {
801 const tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
802 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
806 // What are the pawn moves from square x,y ?
807 getPotentialPawnMoves([x
, y
], promotions
) {
808 const color
= this.turn
; //this.getColor(x, y);
809 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
810 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
811 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
812 const forward
= (color
== 'w' ? -1 : 1);
814 // Pawn movements in shiftX direction:
815 const getPawnMoves
= (shiftX
) => {
817 // NOTE: next condition is generally true (no pawn on last rank)
818 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
819 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
820 // One square forward (or backward)
821 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
822 // Next condition because pawns on 1st rank can generally jump
824 V
.PawnSpecs
.twoSquares
&&
826 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
828 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
833 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
836 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
838 V
.PawnSpecs
.threeSquares
&&
839 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
841 // Three squares jump
842 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
848 if (V
.PawnSpecs
.canCapture
) {
849 for (let shiftY
of [-1, 1]) {
850 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
852 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
853 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
856 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
861 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
862 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
863 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
864 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
867 [x
, y
], [x
- shiftX
, y
+ shiftY
],
878 let pMoves
= getPawnMoves(pawnShiftX
);
879 if (V
.PawnSpecs
.bidirectional
)
880 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
882 if (V
.HasEnpassant
) {
883 // NOTE: backward en-passant captures are not considered
884 // because no rules define them (for now).
885 Array
.prototype.push
.apply(
887 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
894 // What are the rook moves from square x,y ?
895 getPotentialRookMoves(sq
) {
896 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
899 // What are the knight moves from square x,y ?
900 getPotentialKnightMoves(sq
) {
901 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], 1);
904 // What are the bishop moves from square x,y ?
905 getPotentialBishopMoves(sq
) {
906 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
909 // What are the queen moves from square x,y ?
910 getPotentialQueenMoves(sq
) {
911 return this.getSlideNJumpMoves(
912 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
915 // What are the king moves from square x,y ?
916 getPotentialKingMoves(sq
) {
917 // Initialize with normal moves
918 let moves
= this.getSlideNJumpMoves(
919 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), 1);
920 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
921 moves
= moves
.concat(this.getCastleMoves(sq
));
925 // "castleInCheck" arg to let some variants castle under check
926 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
927 const c
= this.getColor(x
, y
);
930 const oppCol
= V
.GetOppCol(c
);
933 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
934 const castlingKing
= this.board
[x
][y
].charAt(1);
938 castleSide
++ //large, then small
940 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
941 // If this code is reached, rook and king are on initial position
943 // NOTE: in some variants this is not a rook
944 const rookPos
= this.castleFlags
[c
][castleSide
];
945 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
947 this.board
[x
][rookPos
] == V
.EMPTY
||
948 this.getColor(x
, rookPos
) != c
||
949 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
951 // Rook is not here, or changed color (see Benedict)
955 // Nothing on the path of the king ? (and no checks)
956 const finDist
= finalSquares
[castleSide
][0] - y
;
957 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
961 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
963 this.board
[x
][i
] != V
.EMPTY
&&
964 // NOTE: next check is enough, because of chessboard constraints
965 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
968 continue castlingCheck
;
971 } while (i
!= finalSquares
[castleSide
][0]);
973 // Nothing on the path to the rook?
974 step
= castleSide
== 0 ? -1 : 1;
975 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
976 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
979 // Nothing on final squares, except maybe king and castling rook?
980 for (i
= 0; i
< 2; i
++) {
982 finalSquares
[castleSide
][i
] != rookPos
&&
983 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
985 finalSquares
[castleSide
][i
] != y
||
986 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
989 continue castlingCheck
;
993 // If this code is reached, castle is valid
999 y: finalSquares
[castleSide
][0],
1005 y: finalSquares
[castleSide
][1],
1011 // King might be initially disguised (Titan...)
1012 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1013 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1016 Math
.abs(y
- rookPos
) <= 2
1017 ? { x: x
, y: rookPos
}
1018 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1026 ////////////////////
1029 // For the interface: possible moves for the current turn from square sq
1030 getPossibleMovesFrom(sq
) {
1031 return this.filterValid(this.getPotentialMovesFrom(sq
));
1034 // TODO: promotions (into R,B,N,Q) should be filtered only once
1035 filterValid(moves
) {
1036 if (moves
.length
== 0) return [];
1037 const color
= this.turn
;
1038 return moves
.filter(m
=> {
1040 const res
= !this.underCheck(color
);
1046 getAllPotentialMoves() {
1047 const color
= this.turn
;
1048 let potentialMoves
= [];
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 Array
.prototype.push
.apply(
1054 this.getPotentialMovesFrom([i
, j
])
1059 return potentialMoves
;
1062 // Search for all valid moves considering current turn
1063 // (for engine and game end)
1064 getAllValidMoves() {
1065 return this.filterValid(this.getAllPotentialMoves());
1068 // Stop at the first move found
1069 // TODO: not really, it explores all moves from a square (one is enough).
1070 // Possible fix: add extra arg "oneMove" to getPotentialMovesFrom,
1071 // and then return only boolean true at first move found
1072 // (in all getPotentialXXXMoves() ... for all variants ...)
1074 const color
= this.turn
;
1075 for (let i
= 0; i
< V
.size
.x
; i
++) {
1076 for (let j
= 0; j
< V
.size
.y
; j
++) {
1077 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1078 const moves
= this.getPotentialMovesFrom([i
, j
]);
1079 if (moves
.length
> 0) {
1080 for (let k
= 0; k
< moves
.length
; k
++)
1081 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1089 // Check if pieces of given color are attacking (king) on square x,y
1090 isAttacked(sq
, color
) {
1092 this.isAttackedByPawn(sq
, color
) ||
1093 this.isAttackedByRook(sq
, color
) ||
1094 this.isAttackedByKnight(sq
, color
) ||
1095 this.isAttackedByBishop(sq
, color
) ||
1096 this.isAttackedByQueen(sq
, color
) ||
1097 this.isAttackedByKing(sq
, color
)
1101 // Generic method for non-pawn pieces ("sliding or jumping"):
1102 // is x,y attacked by a piece of given color ?
1103 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, nbSteps
) {
1104 for (let step
of steps
) {
1105 let rx
= x
+ step
[0],
1107 let stepCounter
= 1;
1109 V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&&
1110 (!nbSteps
|| stepCounter
< nbSteps
)
1117 V
.OnBoard(rx
, ry
) &&
1118 this.board
[rx
][ry
] != V
.EMPTY
&&
1119 this.getPiece(rx
, ry
) == piece
&&
1120 this.getColor(rx
, ry
) == color
1128 // Is square x,y attacked by 'color' pawns ?
1129 isAttackedByPawn(sq
, color
) {
1130 const pawnShift
= (color
== "w" ? 1 : -1);
1131 return this.isAttackedBySlideNJump(
1135 [[pawnShift
, 1], [pawnShift
, -1]],
1140 // Is square x,y attacked by 'color' rooks ?
1141 isAttackedByRook(sq
, color
) {
1142 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1145 // Is square x,y attacked by 'color' knights ?
1146 isAttackedByKnight(sq
, color
) {
1147 return this.isAttackedBySlideNJump(
1156 // Is square x,y attacked by 'color' bishops ?
1157 isAttackedByBishop(sq
, color
) {
1158 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1161 // Is square x,y attacked by 'color' queens ?
1162 isAttackedByQueen(sq
, color
) {
1163 return this.isAttackedBySlideNJump(
1167 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1171 // Is square x,y attacked by 'color' king(s) ?
1172 isAttackedByKing(sq
, color
) {
1173 return this.isAttackedBySlideNJump(
1177 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1182 // Is color under check after his move ?
1184 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1190 // Apply a move on board
1191 static PlayOnBoard(board
, move) {
1192 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1193 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1195 // Un-apply the played move
1196 static UndoOnBoard(board
, move) {
1197 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1198 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1205 // if (!this.states) this.states = [];
1206 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1207 // this.states.push(stateFen);
1210 // Save flags (for undo)
1211 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1212 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1213 V
.PlayOnBoard(this.board
, move);
1214 this.turn
= V
.GetOppCol(this.turn
);
1216 this.postPlay(move);
1219 updateCastleFlags(move, piece
, color
) {
1220 // TODO: check flags. If already off, no need to always re-evaluate
1221 const c
= color
|| V
.GetOppCol(this.turn
);
1222 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1223 // Update castling flags if rooks are moved
1224 const oppCol
= this.turn
;
1225 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1226 if (piece
== V
.KING
&& move.appear
.length
> 0)
1227 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1229 move.start
.x
== firstRank
&& //our rook moves?
1230 this.castleFlags
[c
].includes(move.start
.y
)
1232 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1233 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1235 // NOTE: not "else if" because a rook could take an opposing rook
1237 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1238 this.castleFlags
[oppCol
].includes(move.end
.y
)
1240 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1241 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1245 // After move is played, update variables + flags
1247 const c
= V
.GetOppCol(this.turn
);
1248 let piece
= undefined;
1249 if (move.vanish
.length
>= 1)
1250 // Usual case, something is moved
1251 piece
= move.vanish
[0].p
;
1253 // Crazyhouse-like variants
1254 piece
= move.appear
[0].p
;
1256 // Update king position + flags
1257 if (piece
== V
.KING
&& move.appear
.length
> 0)
1258 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1259 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1266 if (V
.HasEnpassant
) this.epSquares
.pop();
1267 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1268 V
.UndoOnBoard(this.board
, move);
1269 this.turn
= V
.GetOppCol(this.turn
);
1271 this.postUndo(move);
1274 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1275 // if (stateFen != this.states[this.states.length-1]) debugger;
1276 // this.states.pop();
1279 // After move is undo-ed *and flags resetted*, un-update other variables
1280 // TODO: more symmetry, by storing flags increment in move (?!)
1282 // (Potentially) Reset king position
1283 const c
= this.getColor(move.start
.x
, move.start
.y
);
1284 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1285 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1291 // What is the score ? (Interesting if game is over)
1293 if (this.atLeastOneMove()) return "*";
1295 const color
= this.turn
;
1296 // No valid move: stalemate or checkmate?
1297 if (!this.underCheck(color
)) return "1/2";
1299 return (color
== "w" ? "0-1" : "1-0");
1306 static get VALUES() {
1317 // "Checkmate" (unreachable eval)
1318 static get INFINITY() {
1322 // At this value or above, the game is over
1323 static get THRESHOLD_MATE() {
1327 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1328 static get SEARCH_DEPTH() {
1332 // 'movesList' arg for some variants to provide a custom list
1333 getComputerMove(movesList
) {
1334 const maxeval
= V
.INFINITY
;
1335 const color
= this.turn
;
1336 let moves1
= movesList
|| this.getAllValidMoves();
1338 if (moves1
.length
== 0)
1339 // TODO: this situation should not happen
1342 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1343 for (let i
= 0; i
< moves1
.length
; i
++) {
1344 this.play(moves1
[i
]);
1345 const score1
= this.getCurrentScore();
1346 if (score1
!= "*") {
1350 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1352 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1353 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1354 this.undo(moves1
[i
]);
1357 // Initial self evaluation is very low: "I'm checkmated"
1358 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1359 // Initial enemy evaluation is very low too, for him
1360 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1361 // Second half-move:
1362 let moves2
= this.getAllValidMoves();
1363 for (let j
= 0; j
< moves2
.length
; j
++) {
1364 this.play(moves2
[j
]);
1365 const score2
= this.getCurrentScore();
1366 let evalPos
= 0; //1/2 value
1369 evalPos
= this.evalPosition();
1379 (color
== "w" && evalPos
< eval2
) ||
1380 (color
== "b" && evalPos
> eval2
)
1384 this.undo(moves2
[j
]);
1387 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1388 (color
== "b" && eval2
< moves1
[i
].eval
)
1390 moves1
[i
].eval
= eval2
;
1392 this.undo(moves1
[i
]);
1394 moves1
.sort((a
, b
) => {
1395 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1397 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1399 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1400 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1401 for (let i
= 0; i
< moves1
.length
; i
++) {
1402 this.play(moves1
[i
]);
1403 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1405 0.1 * moves1
[i
].eval
+
1406 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1407 this.undo(moves1
[i
]);
1409 moves1
.sort((a
, b
) => {
1410 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1414 let candidates
= [0];
1415 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1417 return moves1
[candidates
[randInt(candidates
.length
)]];
1420 alphabeta(depth
, alpha
, beta
) {
1421 const maxeval
= V
.INFINITY
;
1422 const color
= this.turn
;
1423 const score
= this.getCurrentScore();
1425 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1426 if (depth
== 0) return this.evalPosition();
1427 const moves
= this.getAllValidMoves();
1428 let v
= color
== "w" ? -maxeval : maxeval
;
1430 for (let i
= 0; i
< moves
.length
; i
++) {
1431 this.play(moves
[i
]);
1432 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1433 this.undo(moves
[i
]);
1434 alpha
= Math
.max(alpha
, v
);
1435 if (alpha
>= beta
) break; //beta cutoff
1440 for (let i
= 0; i
< moves
.length
; i
++) {
1441 this.play(moves
[i
]);
1442 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1443 this.undo(moves
[i
]);
1444 beta
= Math
.min(beta
, v
);
1445 if (alpha
>= beta
) break; //alpha cutoff
1453 // Just count material for now
1454 for (let i
= 0; i
< V
.size
.x
; i
++) {
1455 for (let j
= 0; j
< V
.size
.y
; j
++) {
1456 if (this.board
[i
][j
] != V
.EMPTY
) {
1457 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1458 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1465 /////////////////////////
1466 // MOVES + GAME NOTATION
1467 /////////////////////////
1469 // Context: just before move is played, turn hasn't changed
1470 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1472 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1474 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1476 // Translate final square
1477 const finalSquare
= V
.CoordsToSquare(move.end
);
1479 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1480 if (piece
== V
.PAWN
) {
1483 if (move.vanish
.length
> move.appear
.length
) {
1485 const startColumn
= V
.CoordToColumn(move.start
.y
);
1486 notation
= startColumn
+ "x" + finalSquare
;
1488 else notation
= finalSquare
;
1489 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1491 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1496 piece
.toUpperCase() +
1497 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1502 static GetUnambiguousNotation(move) {
1503 // Machine-readable format with all the informations about the move
1505 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1506 ? V
.CoordsToSquare(move.start
)
1509 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1510 ? V
.CoordsToSquare(move.end
)
1513 (!!move.appear
&& move.appear
.length
> 0
1514 ? move.appear
.map(a
=>
1515 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1518 (!!move.vanish
&& move.vanish
.length
> 0
1519 ? move.vanish
.map(a
=>
1520 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")