7c1c8232698368cebb01288c8aeef90c9e41618e
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 // For (generally old) variants without checkered board
139 static get Monochrome() {
143 // Some games are drawn unusually (bottom right corner is black)
144 static get DarkBottomRight() {
148 // Some variants require lines drawing
152 // Draw all inter-squares lines
153 for (let i
= 0; i
<= V
.size
.x
; i
++)
154 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
155 for (let j
= 0; j
<= V
.size
.y
; j
++)
156 lines
.push([[0, j
], [V
.size
.x
, j
]]);
162 // In some variants, the player who repeat a position loses
163 static get LoseOnRepetition() {
166 // And in some others (Iceage), repetitions should be ignored:
167 static get IgnoreRepetition() {
171 // In some variants, result depends on the position:
172 return V
.LoseOnRepetition
;
175 // At some stages, some games could wait clicks only:
180 // Some variants use click infos:
185 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
190 static get IMAGE_EXTENSION() {
191 // All pieces should be in the SVG format
195 // Turn "wb" into "B" (for FEN)
196 static board2fen(b
) {
197 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
200 // Turn "p" into "bp" (for board)
201 static fen2board(f
) {
202 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
205 // Check if FEN describes a board situation correctly
206 static IsGoodFen(fen
) {
207 const fenParsed
= V
.ParseFen(fen
);
209 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
211 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
212 // 3) Check moves count
213 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
216 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
218 // 5) Check enpassant
221 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
228 // Is position part of the FEN a priori correct?
229 static IsGoodPosition(position
) {
230 if (position
.length
== 0) return false;
231 const rows
= position
.split("/");
232 if (rows
.length
!= V
.size
.x
) return false;
233 let kings
= { "k": 0, "K": 0 };
234 for (let row
of rows
) {
236 for (let i
= 0; i
< row
.length
; i
++) {
237 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
238 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
240 const num
= parseInt(row
[i
], 10);
241 if (isNaN(num
) || num
<= 0) return false;
245 if (sumElts
!= V
.size
.y
) return false;
247 // Both kings should be on board. Exactly one per color.
248 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
253 static IsGoodTurn(turn
) {
254 return ["w", "b"].includes(turn
);
258 static IsGoodFlags(flags
) {
259 // NOTE: a little too permissive to work with more variants
260 return !!flags
.match(/^[a-z]{4,4}$/);
263 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
264 static IsGoodEnpassant(enpassant
) {
265 if (enpassant
!= "-") {
266 const ep
= V
.SquareToCoords(enpassant
);
267 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
272 // 3 --> d (column number to letter)
273 static CoordToColumn(colnum
) {
274 return String
.fromCharCode(97 + colnum
);
277 // d --> 3 (column letter to number)
278 static ColumnToCoord(column
) {
279 return column
.charCodeAt(0) - 97;
283 static SquareToCoords(sq
) {
285 // NOTE: column is always one char => max 26 columns
286 // row is counted from black side => subtraction
287 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
288 y: sq
[0].charCodeAt() - 97
293 static CoordsToSquare(coords
) {
294 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
297 // Path to pieces (standard ones in pieces/ folder)
302 // Path to promotion pieces (usually the same)
304 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
307 // Aggregates flags into one object
309 return this.castleFlags
;
313 disaggregateFlags(flags
) {
314 this.castleFlags
= flags
;
317 // En-passant square, if any
318 getEpSquare(moveOrSquare
) {
319 if (!moveOrSquare
) return undefined; //TODO: necessary line?!
320 if (typeof moveOrSquare
=== "string") {
321 const square
= moveOrSquare
;
322 if (square
== "-") return undefined;
323 return V
.SquareToCoords(square
);
325 // Argument is a move:
326 const move = moveOrSquare
;
327 const s
= move.start
,
331 Math
.abs(s
.x
- e
.x
) == 2 &&
332 // Next conditions for variants like Atomic or Rifle, Recycle...
333 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
334 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
341 return undefined; //default
344 // Can thing on square1 take thing on square2
345 canTake([x1
, y1
], [x2
, y2
]) {
346 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
349 // Is (x,y) on the chessboard?
350 static OnBoard(x
, y
) {
351 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
354 // Used in interface: 'side' arg == player color
355 canIplay(side
, [x
, y
]) {
356 return this.turn
== side
&& this.getColor(x
, y
) == side
;
359 // On which squares is color under check ? (for interface)
361 const color
= this.turn
;
363 this.underCheck(color
)
364 // kingPos must be duplicated, because it may change:
365 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
373 // Setup the initial random (asymmetric) position
374 static GenRandInitFen(options
) {
375 if (!options
.randomness
|| options
.randomness
== 0)
377 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
379 let pieces
= { w: new Array(8), b: new Array(8) };
381 // Shuffle pieces on first (and last rank if randomness == 2)
382 for (let c
of ["w", "b"]) {
383 if (c
== 'b' && options
.randomness
== 1) {
384 pieces
['b'] = pieces
['w'];
389 let positions
= ArrayFun
.range(8);
391 // Get random squares for bishops
392 let randIndex
= 2 * randInt(4);
393 const bishop1Pos
= positions
[randIndex
];
394 // The second bishop must be on a square of different color
395 let randIndex_tmp
= 2 * randInt(4) + 1;
396 const bishop2Pos
= positions
[randIndex_tmp
];
397 // Remove chosen squares
398 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
399 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
401 // Get random squares for knights
402 randIndex
= randInt(6);
403 const knight1Pos
= positions
[randIndex
];
404 positions
.splice(randIndex
, 1);
405 randIndex
= randInt(5);
406 const knight2Pos
= positions
[randIndex
];
407 positions
.splice(randIndex
, 1);
409 // Get random square for queen
410 randIndex
= randInt(4);
411 const queenPos
= positions
[randIndex
];
412 positions
.splice(randIndex
, 1);
414 // Rooks and king positions are now fixed,
415 // because of the ordering rook-king-rook
416 const rook1Pos
= positions
[0];
417 const kingPos
= positions
[1];
418 const rook2Pos
= positions
[2];
420 // Finally put the shuffled pieces in the board array
421 pieces
[c
][rook1Pos
] = "r";
422 pieces
[c
][knight1Pos
] = "n";
423 pieces
[c
][bishop1Pos
] = "b";
424 pieces
[c
][queenPos
] = "q";
425 pieces
[c
][kingPos
] = "k";
426 pieces
[c
][bishop2Pos
] = "b";
427 pieces
[c
][knight2Pos
] = "n";
428 pieces
[c
][rook2Pos
] = "r";
429 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
431 // Add turn + flags + enpassant
433 pieces
["b"].join("") +
434 "/pppppppp/8/8/8/8/PPPPPPPP/" +
435 pieces
["w"].join("").toUpperCase() +
436 " w 0 " + flags
+ " -"
440 // "Parse" FEN: just return untransformed string data
441 static ParseFen(fen
) {
442 const fenParts
= fen
.split(" ");
444 position: fenParts
[0],
446 movesCount: fenParts
[2]
449 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
450 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
454 // Return current fen (game state)
457 this.getBaseFen() + " " +
458 this.getTurnFen() + " " +
460 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
461 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
466 // Omit movesCount, only variable allowed to differ
468 this.getBaseFen() + "_" +
470 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
471 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
475 // Position part of the FEN string
477 const format
= (count
) => {
478 // if more than 9 consecutive free spaces, break the integer,
479 // otherwise FEN parsing will fail.
480 if (count
<= 9) return count
;
481 // Most boards of size < 18:
482 if (count
<= 18) return "9" + (count
- 9);
484 return "99" + (count
- 18);
487 for (let i
= 0; i
< V
.size
.x
; i
++) {
489 for (let j
= 0; j
< V
.size
.y
; j
++) {
490 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
492 if (emptyCount
> 0) {
493 // Add empty squares in-between
494 position
+= format(emptyCount
);
497 position
+= V
.board2fen(this.board
[i
][j
]);
500 if (emptyCount
> 0) {
502 position
+= format(emptyCount
);
504 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
513 // Flags part of the FEN string
517 for (let c
of ["w", "b"])
518 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
522 // Enpassant part of the FEN string
524 const L
= this.epSquares
.length
;
525 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
526 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
529 // Turn position fen into double array ["wb","wp","bk",...]
530 static GetBoard(position
) {
531 const rows
= position
.split("/");
532 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
533 for (let i
= 0; i
< rows
.length
; i
++) {
535 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
536 const character
= rows
[i
][indexInRow
];
537 const num
= parseInt(character
, 10);
538 // If num is a number, just shift j:
539 if (!isNaN(num
)) j
+= num
;
540 // Else: something at position i,j
541 else board
[i
][j
++] = V
.fen2board(character
);
547 // Extract (relevant) flags from fen
549 // white a-castle, h-castle, black a-castle, h-castle
550 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
551 for (let i
= 0; i
< 4; i
++) {
552 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
553 V
.ColumnToCoord(fenflags
.charAt(i
));
560 // Fen string fully describes the game state
563 // In printDiagram() fen isn't supply because only getPpath() is used
564 // TODO: find a better solution!
566 const fenParsed
= V
.ParseFen(fen
);
567 this.board
= V
.GetBoard(fenParsed
.position
);
568 this.turn
= fenParsed
.turn
;
569 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
570 this.setOtherVariables(fen
);
573 // Scan board for kings positions
574 // TODO: should be done from board, no need for the complete FEN
576 // Squares of white and black king:
577 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
578 const fenRows
= V
.ParseFen(fen
).position
.split("/");
579 for (let i
= 0; i
< fenRows
.length
; i
++) {
580 let k
= 0; //column index on board
581 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
582 switch (fenRows
[i
].charAt(j
)) {
584 this.kingPos
["b"] = [i
, k
];
587 this.kingPos
["w"] = [i
, k
];
590 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
591 if (!isNaN(num
)) k
+= num
- 1;
599 // Some additional variables from FEN (variant dependant)
600 setOtherVariables(fen
) {
601 // Set flags and enpassant:
602 const parsedFen
= V
.ParseFen(fen
);
603 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
604 if (V
.HasEnpassant
) {
606 parsedFen
.enpassant
!= "-"
607 ? this.getEpSquare(parsedFen
.enpassant
)
609 this.epSquares
= [epSq
];
611 // Search for kings positions:
615 /////////////////////
619 return { x: 8, y: 8 };
622 // Color of thing on square (i,j). 'undefined' if square is empty
624 return this.board
[i
][j
].charAt(0);
627 // Piece type on square (i,j). 'undefined' if square is empty
629 return this.board
[i
][j
].charAt(1);
632 // Get opponent color
633 static GetOppCol(color
) {
634 return color
== "w" ? "b" : "w";
637 // Pieces codes (for a clearer code)
644 static get KNIGHT() {
647 static get BISHOP() {
658 static get PIECES() {
659 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
667 // Some pieces movements
698 // All possible moves from selected square
699 getPotentialMovesFrom(sq
) {
700 switch (this.getPiece(sq
[0], sq
[1])) {
701 case V
.PAWN: return this.getPotentialPawnMoves(sq
);
702 case V
.ROOK: return this.getPotentialRookMoves(sq
);
703 case V
.KNIGHT: return this.getPotentialKnightMoves(sq
);
704 case V
.BISHOP: return this.getPotentialBishopMoves(sq
);
705 case V
.QUEEN: return this.getPotentialQueenMoves(sq
);
706 case V
.KING: return this.getPotentialKingMoves(sq
);
708 return []; //never reached (but some variants may use it: Bario...)
711 // Build a regular move from its initial and destination squares.
712 // tr: transformation
713 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
714 const initColor
= this.getColor(sx
, sy
);
715 const initPiece
= this.board
[sx
][sy
].charAt(1);
721 c: !!tr
? tr
.c : initColor
,
722 p: !!tr
? tr
.p : initPiece
735 // The opponent piece disappears if we take it
736 if (this.board
[ex
][ey
] != V
.EMPTY
) {
741 c: this.getColor(ex
, ey
),
742 p: this.board
[ex
][ey
].charAt(1)
750 // Generic method to find possible moves of non-pawn pieces:
751 // "sliding or jumping"
752 getSlideNJumpMoves([x
, y
], steps
, nbSteps
) {
754 outerLoop: for (let step
of steps
) {
758 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
759 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
760 if (nbSteps
&& ++stepCounter
>= nbSteps
) continue outerLoop
;
764 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
765 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
770 // Special case of en-passant captures: treated separately
771 getEnpassantCaptures([x
, y
], shiftX
) {
772 const Lep
= this.epSquares
.length
;
773 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
774 let enpassantMove
= null;
777 epSquare
.x
== x
+ shiftX
&&
778 Math
.abs(epSquare
.y
- y
) == 1
780 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
781 enpassantMove
.vanish
.push({
784 p: this.board
[x
][epSquare
.y
].charAt(1),
785 c: this.getColor(x
, epSquare
.y
)
788 return !!enpassantMove
? [enpassantMove
] : [];
791 // Consider all potential promotions:
792 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
793 let finalPieces
= [V
.PAWN
];
794 const color
= this.turn
; //this.getColor(x1, y1);
795 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
796 if (x2
== lastRank
) {
797 // promotions arg: special override for Hiddenqueen variant
798 if (!!promotions
) finalPieces
= promotions
;
799 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
801 for (let piece
of finalPieces
) {
802 const tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
803 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
807 // What are the pawn moves from square x,y ?
808 getPotentialPawnMoves([x
, y
], promotions
) {
809 const color
= this.turn
; //this.getColor(x, y);
810 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
811 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
812 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
813 const forward
= (color
== 'w' ? -1 : 1);
815 // Pawn movements in shiftX direction:
816 const getPawnMoves
= (shiftX
) => {
818 // NOTE: next condition is generally true (no pawn on last rank)
819 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
820 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
821 // One square forward (or backward)
822 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
823 // Next condition because pawns on 1st rank can generally jump
825 V
.PawnSpecs
.twoSquares
&&
827 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
829 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
834 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
837 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
839 V
.PawnSpecs
.threeSquares
&&
840 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
842 // Three squares jump
843 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
849 if (V
.PawnSpecs
.canCapture
) {
850 for (let shiftY
of [-1, 1]) {
851 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
853 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
854 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
857 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
862 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
863 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
864 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
865 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
868 [x
, y
], [x
- shiftX
, y
+ shiftY
],
879 let pMoves
= getPawnMoves(pawnShiftX
);
880 if (V
.PawnSpecs
.bidirectional
)
881 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
883 if (V
.HasEnpassant
) {
884 // NOTE: backward en-passant captures are not considered
885 // because no rules define them (for now).
886 Array
.prototype.push
.apply(
888 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
895 // What are the rook moves from square x,y ?
896 getPotentialRookMoves(sq
) {
897 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
900 // What are the knight moves from square x,y ?
901 getPotentialKnightMoves(sq
) {
902 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], 1);
905 // What are the bishop moves from square x,y ?
906 getPotentialBishopMoves(sq
) {
907 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
910 // What are the queen moves from square x,y ?
911 getPotentialQueenMoves(sq
) {
912 return this.getSlideNJumpMoves(
913 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
916 // What are the king moves from square x,y ?
917 getPotentialKingMoves(sq
) {
918 // Initialize with normal moves
919 let moves
= this.getSlideNJumpMoves(
920 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), 1);
921 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
922 moves
= moves
.concat(this.getCastleMoves(sq
));
926 // "castleInCheck" arg to let some variants castle under check
927 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
928 const c
= this.getColor(x
, y
);
931 const oppCol
= V
.GetOppCol(c
);
934 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
935 const castlingKing
= this.board
[x
][y
].charAt(1);
939 castleSide
++ //large, then small
941 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
942 // If this code is reached, rook and king are on initial position
944 // NOTE: in some variants this is not a rook
945 const rookPos
= this.castleFlags
[c
][castleSide
];
946 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
948 this.board
[x
][rookPos
] == V
.EMPTY
||
949 this.getColor(x
, rookPos
) != c
||
950 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
952 // Rook is not here, or changed color (see Benedict)
956 // Nothing on the path of the king ? (and no checks)
957 const finDist
= finalSquares
[castleSide
][0] - y
;
958 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
962 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
964 this.board
[x
][i
] != V
.EMPTY
&&
965 // NOTE: next check is enough, because of chessboard constraints
966 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
969 continue castlingCheck
;
972 } while (i
!= finalSquares
[castleSide
][0]);
974 // Nothing on the path to the rook?
975 step
= castleSide
== 0 ? -1 : 1;
976 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
977 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
980 // Nothing on final squares, except maybe king and castling rook?
981 for (i
= 0; i
< 2; i
++) {
983 finalSquares
[castleSide
][i
] != rookPos
&&
984 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
986 finalSquares
[castleSide
][i
] != y
||
987 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
990 continue castlingCheck
;
994 // If this code is reached, castle is valid
1000 y: finalSquares
[castleSide
][0],
1006 y: finalSquares
[castleSide
][1],
1012 // King might be initially disguised (Titan...)
1013 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1014 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1017 Math
.abs(y
- rookPos
) <= 2
1018 ? { x: x
, y: rookPos
}
1019 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1027 ////////////////////
1030 // For the interface: possible moves for the current turn from square sq
1031 getPossibleMovesFrom(sq
) {
1032 return this.filterValid(this.getPotentialMovesFrom(sq
));
1035 // TODO: promotions (into R,B,N,Q) should be filtered only once
1036 filterValid(moves
) {
1037 if (moves
.length
== 0) return [];
1038 const color
= this.turn
;
1039 return moves
.filter(m
=> {
1041 const res
= !this.underCheck(color
);
1047 getAllPotentialMoves() {
1048 const color
= this.turn
;
1049 let potentialMoves
= [];
1050 for (let i
= 0; i
< V
.size
.x
; i
++) {
1051 for (let j
= 0; j
< V
.size
.y
; j
++) {
1052 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1053 Array
.prototype.push
.apply(
1055 this.getPotentialMovesFrom([i
, j
])
1060 return potentialMoves
;
1063 // Search for all valid moves considering current turn
1064 // (for engine and game end)
1065 getAllValidMoves() {
1066 return this.filterValid(this.getAllPotentialMoves());
1069 // Stop at the first move found
1070 // TODO: not really, it explores all moves from a square (one is enough).
1071 // Possible fix: add extra arg "oneMove" to getPotentialMovesFrom,
1072 // and then return only boolean true at first move found
1073 // (in all getPotentialXXXMoves() ... for all variants ...)
1075 const color
= this.turn
;
1076 for (let i
= 0; i
< V
.size
.x
; i
++) {
1077 for (let j
= 0; j
< V
.size
.y
; j
++) {
1078 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1079 const moves
= this.getPotentialMovesFrom([i
, j
]);
1080 if (moves
.length
> 0) {
1081 for (let k
= 0; k
< moves
.length
; k
++)
1082 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1090 // Check if pieces of given color are attacking (king) on square x,y
1091 isAttacked(sq
, color
) {
1093 this.isAttackedByPawn(sq
, color
) ||
1094 this.isAttackedByRook(sq
, color
) ||
1095 this.isAttackedByKnight(sq
, color
) ||
1096 this.isAttackedByBishop(sq
, color
) ||
1097 this.isAttackedByQueen(sq
, color
) ||
1098 this.isAttackedByKing(sq
, color
)
1102 // Generic method for non-pawn pieces ("sliding or jumping"):
1103 // is x,y attacked by a piece of given color ?
1104 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, nbSteps
) {
1105 for (let step
of steps
) {
1106 let rx
= x
+ step
[0],
1108 let stepCounter
= 1;
1110 V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&&
1111 (!nbSteps
|| stepCounter
< nbSteps
)
1118 V
.OnBoard(rx
, ry
) &&
1119 this.board
[rx
][ry
] != V
.EMPTY
&&
1120 this.getPiece(rx
, ry
) == piece
&&
1121 this.getColor(rx
, ry
) == color
1129 // Is square x,y attacked by 'color' pawns ?
1130 isAttackedByPawn(sq
, color
) {
1131 const pawnShift
= (color
== "w" ? 1 : -1);
1132 return this.isAttackedBySlideNJump(
1136 [[pawnShift
, 1], [pawnShift
, -1]],
1141 // Is square x,y attacked by 'color' rooks ?
1142 isAttackedByRook(sq
, color
) {
1143 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1146 // Is square x,y attacked by 'color' knights ?
1147 isAttackedByKnight(sq
, color
) {
1148 return this.isAttackedBySlideNJump(
1157 // Is square x,y attacked by 'color' bishops ?
1158 isAttackedByBishop(sq
, color
) {
1159 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1162 // Is square x,y attacked by 'color' queens ?
1163 isAttackedByQueen(sq
, color
) {
1164 return this.isAttackedBySlideNJump(
1168 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1172 // Is square x,y attacked by 'color' king(s) ?
1173 isAttackedByKing(sq
, color
) {
1174 return this.isAttackedBySlideNJump(
1178 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1183 // Is color under check after his move ?
1185 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1191 // Apply a move on board
1192 static PlayOnBoard(board
, move) {
1193 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1194 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1196 // Un-apply the played move
1197 static UndoOnBoard(board
, move) {
1198 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1199 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1206 // if (!this.states) this.states = [];
1207 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1208 // this.states.push(stateFen);
1211 // Save flags (for undo)
1212 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1213 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1214 V
.PlayOnBoard(this.board
, move);
1215 this.turn
= V
.GetOppCol(this.turn
);
1217 this.postPlay(move);
1220 updateCastleFlags(move, piece
, color
) {
1221 // TODO: check flags. If already off, no need to always re-evaluate
1222 const c
= color
|| V
.GetOppCol(this.turn
);
1223 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1224 // Update castling flags if rooks are moved
1225 const oppCol
= this.turn
;
1226 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1227 if (piece
== V
.KING
&& move.appear
.length
> 0)
1228 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1230 move.start
.x
== firstRank
&& //our rook moves?
1231 this.castleFlags
[c
].includes(move.start
.y
)
1233 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1234 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1236 // NOTE: not "else if" because a rook could take an opposing rook
1238 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1239 this.castleFlags
[oppCol
].includes(move.end
.y
)
1241 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1242 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1246 // After move is played, update variables + flags
1248 const c
= V
.GetOppCol(this.turn
);
1249 let piece
= undefined;
1250 if (move.vanish
.length
>= 1)
1251 // Usual case, something is moved
1252 piece
= move.vanish
[0].p
;
1254 // Crazyhouse-like variants
1255 piece
= move.appear
[0].p
;
1257 // Update king position + flags
1258 if (piece
== V
.KING
&& move.appear
.length
> 0)
1259 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1260 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1267 if (V
.HasEnpassant
) this.epSquares
.pop();
1268 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1269 V
.UndoOnBoard(this.board
, move);
1270 this.turn
= V
.GetOppCol(this.turn
);
1272 this.postUndo(move);
1275 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1276 // if (stateFen != this.states[this.states.length-1]) debugger;
1277 // this.states.pop();
1280 // After move is undo-ed *and flags resetted*, un-update other variables
1281 // TODO: more symmetry, by storing flags increment in move (?!)
1283 // (Potentially) Reset king position
1284 const c
= this.getColor(move.start
.x
, move.start
.y
);
1285 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1286 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1292 // What is the score ? (Interesting if game is over)
1294 if (this.atLeastOneMove()) return "*";
1296 const color
= this.turn
;
1297 // No valid move: stalemate or checkmate?
1298 if (!this.underCheck(color
)) return "1/2";
1300 return (color
== "w" ? "0-1" : "1-0");
1307 static get VALUES() {
1318 // "Checkmate" (unreachable eval)
1319 static get INFINITY() {
1323 // At this value or above, the game is over
1324 static get THRESHOLD_MATE() {
1328 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1329 static get SEARCH_DEPTH() {
1333 // 'movesList' arg for some variants to provide a custom list
1334 getComputerMove(movesList
) {
1335 const maxeval
= V
.INFINITY
;
1336 const color
= this.turn
;
1337 let moves1
= movesList
|| this.getAllValidMoves();
1339 if (moves1
.length
== 0)
1340 // TODO: this situation should not happen
1343 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1344 for (let i
= 0; i
< moves1
.length
; i
++) {
1345 this.play(moves1
[i
]);
1346 const score1
= this.getCurrentScore();
1347 if (score1
!= "*") {
1351 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1353 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1354 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1355 this.undo(moves1
[i
]);
1358 // Initial self evaluation is very low: "I'm checkmated"
1359 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1360 // Initial enemy evaluation is very low too, for him
1361 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1362 // Second half-move:
1363 let moves2
= this.getAllValidMoves();
1364 for (let j
= 0; j
< moves2
.length
; j
++) {
1365 this.play(moves2
[j
]);
1366 const score2
= this.getCurrentScore();
1367 let evalPos
= 0; //1/2 value
1370 evalPos
= this.evalPosition();
1380 (color
== "w" && evalPos
< eval2
) ||
1381 (color
== "b" && evalPos
> eval2
)
1385 this.undo(moves2
[j
]);
1388 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1389 (color
== "b" && eval2
< moves1
[i
].eval
)
1391 moves1
[i
].eval
= eval2
;
1393 this.undo(moves1
[i
]);
1395 moves1
.sort((a
, b
) => {
1396 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1398 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1400 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1401 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1402 for (let i
= 0; i
< moves1
.length
; i
++) {
1403 this.play(moves1
[i
]);
1404 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1406 0.1 * moves1
[i
].eval
+
1407 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1408 this.undo(moves1
[i
]);
1410 moves1
.sort((a
, b
) => {
1411 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1415 let candidates
= [0];
1416 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1418 return moves1
[candidates
[randInt(candidates
.length
)]];
1421 alphabeta(depth
, alpha
, beta
) {
1422 const maxeval
= V
.INFINITY
;
1423 const color
= this.turn
;
1424 const score
= this.getCurrentScore();
1426 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1427 if (depth
== 0) return this.evalPosition();
1428 const moves
= this.getAllValidMoves();
1429 let v
= color
== "w" ? -maxeval : maxeval
;
1431 for (let i
= 0; i
< moves
.length
; i
++) {
1432 this.play(moves
[i
]);
1433 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1434 this.undo(moves
[i
]);
1435 alpha
= Math
.max(alpha
, v
);
1436 if (alpha
>= beta
) break; //beta cutoff
1441 for (let i
= 0; i
< moves
.length
; i
++) {
1442 this.play(moves
[i
]);
1443 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1444 this.undo(moves
[i
]);
1445 beta
= Math
.min(beta
, v
);
1446 if (alpha
>= beta
) break; //alpha cutoff
1454 // Just count material for now
1455 for (let i
= 0; i
< V
.size
.x
; i
++) {
1456 for (let j
= 0; j
< V
.size
.y
; j
++) {
1457 if (this.board
[i
][j
] != V
.EMPTY
) {
1458 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1459 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1466 /////////////////////////
1467 // MOVES + GAME NOTATION
1468 /////////////////////////
1470 // Context: just before move is played, turn hasn't changed
1471 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1473 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1475 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1477 // Translate final square
1478 const finalSquare
= V
.CoordsToSquare(move.end
);
1480 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1481 if (piece
== V
.PAWN
) {
1484 if (move.vanish
.length
> move.appear
.length
) {
1486 const startColumn
= V
.CoordToColumn(move.start
.y
);
1487 notation
= startColumn
+ "x" + finalSquare
;
1489 else notation
= finalSquare
;
1490 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1492 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1497 piece
.toUpperCase() +
1498 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1503 static GetUnambiguousNotation(move) {
1504 // Machine-readable format with all the informations about the move
1506 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1507 ? V
.CoordsToSquare(move.start
)
1510 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1511 ? V
.CoordsToSquare(move.end
)
1514 (!!move.appear
&& move.appear
.length
> 0
1515 ? move.appear
.map(a
=>
1516 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1519 (!!move.vanish
&& move.vanish
.length
> 0
1520 ? move.vanish
.map(a
=>
1521 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")