5919bc3480f7bc4bd85f5a80781df96d841d1665
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 }
54 static AbbreviateOptions(opts
) {
56 // Randomness is a special option: (TODO?)
57 //return "R" + opts.randomness;
60 static IsValidOptions(opts
) {
64 // Some variants don't have flags:
65 static get HasFlags() {
70 static get HasCastle() {
74 // Pawns specifications
75 static get PawnSpecs() {
77 directions: { 'w': -1, 'b': 1 },
78 initShift: { w: 1, b: 1 },
81 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
83 captureBackward: false,
88 // En-passant captures need a stack of squares:
89 static get HasEnpassant() {
93 // Some variants cannot have analyse mode
94 static get CanAnalyze() {
97 // Patch: issues with javascript OOP, objects can't access static fields.
102 // Some variants show incomplete information,
103 // and thus show only a partial moves list or no list at all.
104 static get ShowMoves() {
111 // Sometimes moves must remain hidden until game ends
112 static get SomeHiddenMoves() {
115 get someHiddenMoves() {
116 return V
.SomeHiddenMoves
;
119 // Generally true, unless the variant includes random effects
120 static get CorrConfirm() {
124 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
125 get showFirstTurn() {
129 // Some variants always show the same orientation
130 static get CanFlip() {
137 // NOTE: these will disappear once each variant has its dedicated SVG board.
138 // For (generally old) variants without checkered board
139 static get Monochrome() {
142 // Some games are drawn unusually (bottom right corner is black)
143 static get DarkBottomRight() {
146 // Some variants require lines drawing
150 // Draw all inter-squares lines
151 for (let i
= 0; i
<= V
.size
.x
; i
++)
152 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
153 for (let j
= 0; j
<= V
.size
.y
; j
++)
154 lines
.push([[0, j
], [V
.size
.x
, j
]]);
160 // In some variants, the player who repeat a position loses
161 static get LoseOnRepetition() {
164 // And in some others (Iceage), repetitions should be ignored:
165 static get IgnoreRepetition() {
169 // In some variants, result depends on the position:
170 return V
.LoseOnRepetition
;
173 // At some stages, some games could wait clicks only:
178 // Some variants use click infos:
183 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
188 static get IMAGE_EXTENSION() {
189 // All pieces should be in the SVG format
193 // Turn "wb" into "B" (for FEN)
194 static board2fen(b
) {
195 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
198 // Turn "p" into "bp" (for board)
199 static fen2board(f
) {
200 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
203 // Check if FEN describes a board situation correctly
204 static IsGoodFen(fen
) {
205 const fenParsed
= V
.ParseFen(fen
);
207 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
209 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
210 // 3) Check moves count
211 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
214 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
216 // 5) Check enpassant
219 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
226 // Is position part of the FEN a priori correct?
227 static IsGoodPosition(position
) {
228 if (position
.length
== 0) return false;
229 const rows
= position
.split("/");
230 if (rows
.length
!= V
.size
.x
) return false;
231 let kings
= { "k": 0, "K": 0 };
232 for (let row
of rows
) {
234 for (let i
= 0; i
< row
.length
; i
++) {
235 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
236 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
238 const num
= parseInt(row
[i
], 10);
239 if (isNaN(num
) || num
<= 0) return false;
243 if (sumElts
!= V
.size
.y
) return false;
245 // Both kings should be on board. Exactly one per color.
246 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
251 static IsGoodTurn(turn
) {
252 return ["w", "b"].includes(turn
);
256 static IsGoodFlags(flags
) {
257 // NOTE: a little too permissive to work with more variants
258 return !!flags
.match(/^[a-z]{4,4}$/);
261 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
262 static IsGoodEnpassant(enpassant
) {
263 if (enpassant
!= "-") {
264 const ep
= V
.SquareToCoords(enpassant
);
265 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
270 // 3 --> d (column number to letter)
271 static CoordToColumn(colnum
) {
272 return String
.fromCharCode(97 + colnum
);
275 // d --> 3 (column letter to number)
276 static ColumnToCoord(column
) {
277 return column
.charCodeAt(0) - 97;
281 static SquareToCoords(sq
) {
283 // NOTE: column is always one char => max 26 columns
284 // row is counted from black side => subtraction
285 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
286 y: sq
[0].charCodeAt() - 97
291 static CoordsToSquare(coords
) {
292 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
295 // Path to pieces (standard ones in pieces/ folder)
300 // Path to promotion pieces (usually the same)
302 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
305 // Aggregates flags into one object
307 return this.castleFlags
;
311 disaggregateFlags(flags
) {
312 this.castleFlags
= flags
;
315 // En-passant square, if any
316 getEpSquare(moveOrSquare
) {
317 if (!moveOrSquare
) return undefined; //TODO: necessary line?!
318 if (typeof moveOrSquare
=== "string") {
319 const square
= moveOrSquare
;
320 if (square
== "-") return undefined;
321 return V
.SquareToCoords(square
);
323 // Argument is a move:
324 const move = moveOrSquare
;
325 const s
= move.start
,
329 Math
.abs(s
.x
- e
.x
) == 2 &&
330 // Next conditions for variants like Atomic or Rifle, Recycle...
331 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
332 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
339 return undefined; //default
342 // Can thing on square1 take thing on square2
343 canTake([x1
, y1
], [x2
, y2
]) {
344 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
347 // Is (x,y) on the chessboard?
348 static OnBoard(x
, y
) {
349 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
352 // Used in interface: 'side' arg == player color
353 canIplay(side
, [x
, y
]) {
354 return this.turn
== side
&& this.getColor(x
, y
) == side
;
357 // On which squares is color under check ? (for interface)
359 const color
= this.turn
;
361 this.underCheck(color
)
362 // kingPos must be duplicated, because it may change:
363 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
371 // Setup the initial random (asymmetric) position
372 static GenRandInitFen(options
) {
373 if (!options
.randomness
|| options
.randomness
== 0)
375 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
377 let pieces
= { w: new Array(8), b: new Array(8) };
379 // Shuffle pieces on first (and last rank if randomness == 2)
380 for (let c
of ["w", "b"]) {
381 if (c
== 'b' && options
.randomness
== 1) {
382 pieces
['b'] = pieces
['w'];
387 let positions
= ArrayFun
.range(8);
389 // Get random squares for bishops
390 let randIndex
= 2 * randInt(4);
391 const bishop1Pos
= positions
[randIndex
];
392 // The second bishop must be on a square of different color
393 let randIndex_tmp
= 2 * randInt(4) + 1;
394 const bishop2Pos
= positions
[randIndex_tmp
];
395 // Remove chosen squares
396 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
397 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
399 // Get random squares for knights
400 randIndex
= randInt(6);
401 const knight1Pos
= positions
[randIndex
];
402 positions
.splice(randIndex
, 1);
403 randIndex
= randInt(5);
404 const knight2Pos
= positions
[randIndex
];
405 positions
.splice(randIndex
, 1);
407 // Get random square for queen
408 randIndex
= randInt(4);
409 const queenPos
= positions
[randIndex
];
410 positions
.splice(randIndex
, 1);
412 // Rooks and king positions are now fixed,
413 // because of the ordering rook-king-rook
414 const rook1Pos
= positions
[0];
415 const kingPos
= positions
[1];
416 const rook2Pos
= positions
[2];
418 // Finally put the shuffled pieces in the board array
419 pieces
[c
][rook1Pos
] = "r";
420 pieces
[c
][knight1Pos
] = "n";
421 pieces
[c
][bishop1Pos
] = "b";
422 pieces
[c
][queenPos
] = "q";
423 pieces
[c
][kingPos
] = "k";
424 pieces
[c
][bishop2Pos
] = "b";
425 pieces
[c
][knight2Pos
] = "n";
426 pieces
[c
][rook2Pos
] = "r";
427 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
429 // Add turn + flags + enpassant
431 pieces
["b"].join("") +
432 "/pppppppp/8/8/8/8/PPPPPPPP/" +
433 pieces
["w"].join("").toUpperCase() +
434 " w 0 " + flags
+ " -"
438 // "Parse" FEN: just return untransformed string data
439 static ParseFen(fen
) {
440 const fenParts
= fen
.split(" ");
442 position: fenParts
[0],
444 movesCount: fenParts
[2]
447 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
448 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
452 // Return current fen (game state)
455 this.getBaseFen() + " " +
456 this.getTurnFen() + " " +
458 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
459 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
464 // Omit movesCount, only variable allowed to differ
466 this.getBaseFen() + "_" +
468 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
469 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
473 // Position part of the FEN string
475 const format
= (count
) => {
476 // if more than 9 consecutive free spaces, break the integer,
477 // otherwise FEN parsing will fail.
478 if (count
<= 9) return count
;
479 // Most boards of size < 18:
480 if (count
<= 18) return "9" + (count
- 9);
482 return "99" + (count
- 18);
485 for (let i
= 0; i
< V
.size
.x
; i
++) {
487 for (let j
= 0; j
< V
.size
.y
; j
++) {
488 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
490 if (emptyCount
> 0) {
491 // Add empty squares in-between
492 position
+= format(emptyCount
);
495 position
+= V
.board2fen(this.board
[i
][j
]);
498 if (emptyCount
> 0) {
500 position
+= format(emptyCount
);
502 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
511 // Flags part of the FEN string
515 for (let c
of ["w", "b"])
516 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
520 // Enpassant part of the FEN string
522 const L
= this.epSquares
.length
;
523 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
524 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
527 // Turn position fen into double array ["wb","wp","bk",...]
528 static GetBoard(position
) {
529 const rows
= position
.split("/");
530 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
531 for (let i
= 0; i
< rows
.length
; i
++) {
533 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
534 const character
= rows
[i
][indexInRow
];
535 const num
= parseInt(character
, 10);
536 // If num is a number, just shift j:
537 if (!isNaN(num
)) j
+= num
;
538 // Else: something at position i,j
539 else board
[i
][j
++] = V
.fen2board(character
);
545 // Extract (relevant) flags from fen
547 // white a-castle, h-castle, black a-castle, h-castle
548 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
549 for (let i
= 0; i
< 4; i
++) {
550 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
551 V
.ColumnToCoord(fenflags
.charAt(i
));
558 // Fen string fully describes the game state
561 // In printDiagram() fen isn't supply because only getPpath() is used
562 // TODO: find a better solution!
564 const fenParsed
= V
.ParseFen(fen
);
565 this.board
= V
.GetBoard(fenParsed
.position
);
566 this.turn
= fenParsed
.turn
;
567 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
568 this.setOtherVariables(fen
);
571 // Scan board for kings positions
572 // TODO: should be done from board, no need for the complete FEN
574 // Squares of white and black king:
575 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
576 const fenRows
= V
.ParseFen(fen
).position
.split("/");
577 for (let i
= 0; i
< fenRows
.length
; i
++) {
578 let k
= 0; //column index on board
579 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
580 switch (fenRows
[i
].charAt(j
)) {
582 this.kingPos
["b"] = [i
, k
];
585 this.kingPos
["w"] = [i
, k
];
588 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
589 if (!isNaN(num
)) k
+= num
- 1;
597 // Some additional variables from FEN (variant dependant)
598 setOtherVariables(fen
) {
599 // Set flags and enpassant:
600 const parsedFen
= V
.ParseFen(fen
);
601 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
602 if (V
.HasEnpassant
) {
604 parsedFen
.enpassant
!= "-"
605 ? this.getEpSquare(parsedFen
.enpassant
)
607 this.epSquares
= [epSq
];
609 // Search for kings positions:
613 /////////////////////
617 return { x: 8, y: 8 };
620 // Color of thing on square (i,j). 'undefined' if square is empty
622 return this.board
[i
][j
].charAt(0);
625 // Piece type on square (i,j). 'undefined' if square is empty
627 return this.board
[i
][j
].charAt(1);
630 // Get opponent color
631 static GetOppCol(color
) {
632 return color
== "w" ? "b" : "w";
635 // Pieces codes (for a clearer code)
642 static get KNIGHT() {
645 static get BISHOP() {
656 static get PIECES() {
657 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
665 // Some pieces movements
696 // All possible moves from selected square
697 getPotentialMovesFrom(sq
) {
698 switch (this.getPiece(sq
[0], sq
[1])) {
699 case V
.PAWN: return this.getPotentialPawnMoves(sq
);
700 case V
.ROOK: return this.getPotentialRookMoves(sq
);
701 case V
.KNIGHT: return this.getPotentialKnightMoves(sq
);
702 case V
.BISHOP: return this.getPotentialBishopMoves(sq
);
703 case V
.QUEEN: return this.getPotentialQueenMoves(sq
);
704 case V
.KING: return this.getPotentialKingMoves(sq
);
706 return []; //never reached (but some variants may use it: Bario...)
709 // Build a regular move from its initial and destination squares.
710 // tr: transformation
711 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
712 const initColor
= this.getColor(sx
, sy
);
713 const initPiece
= this.board
[sx
][sy
].charAt(1);
719 c: !!tr
? tr
.c : initColor
,
720 p: !!tr
? tr
.p : initPiece
733 // The opponent piece disappears if we take it
734 if (this.board
[ex
][ey
] != V
.EMPTY
) {
739 c: this.getColor(ex
, ey
),
740 p: this.board
[ex
][ey
].charAt(1)
748 // Generic method to find possible moves of non-pawn pieces:
749 // "sliding or jumping"
750 getSlideNJumpMoves([x
, y
], steps
, nbSteps
) {
752 outerLoop: for (let step
of steps
) {
756 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
757 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
758 if (nbSteps
&& ++stepCounter
>= nbSteps
) continue outerLoop
;
762 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
763 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
768 // Special case of en-passant captures: treated separately
769 getEnpassantCaptures([x
, y
], shiftX
) {
770 const Lep
= this.epSquares
.length
;
771 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
772 let enpassantMove
= null;
775 epSquare
.x
== x
+ shiftX
&&
776 Math
.abs(epSquare
.y
- y
) == 1
778 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
779 enpassantMove
.vanish
.push({
782 p: this.board
[x
][epSquare
.y
].charAt(1),
783 c: this.getColor(x
, epSquare
.y
)
786 return !!enpassantMove
? [enpassantMove
] : [];
789 // Consider all potential promotions:
790 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
791 let finalPieces
= [V
.PAWN
];
792 const color
= this.turn
; //this.getColor(x1, y1);
793 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
794 if (x2
== lastRank
) {
795 // promotions arg: special override for Hiddenqueen variant
796 if (!!promotions
) finalPieces
= promotions
;
797 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
799 for (let piece
of finalPieces
) {
800 const tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
801 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
805 // What are the pawn moves from square x,y ?
806 getPotentialPawnMoves([x
, y
], promotions
) {
807 const color
= this.turn
; //this.getColor(x, y);
808 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
809 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
810 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
811 const forward
= (color
== 'w' ? -1 : 1);
813 // Pawn movements in shiftX direction:
814 const getPawnMoves
= (shiftX
) => {
816 // NOTE: next condition is generally true (no pawn on last rank)
817 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
818 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
819 // One square forward (or backward)
820 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
821 // Next condition because pawns on 1st rank can generally jump
823 V
.PawnSpecs
.twoSquares
&&
825 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
827 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
832 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
835 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
837 V
.PawnSpecs
.threeSquares
&&
838 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
840 // Three squares jump
841 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
847 if (V
.PawnSpecs
.canCapture
) {
848 for (let shiftY
of [-1, 1]) {
849 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
851 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
852 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
855 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
860 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
861 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
862 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
863 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
866 [x
, y
], [x
- shiftX
, y
+ shiftY
],
877 let pMoves
= getPawnMoves(pawnShiftX
);
878 if (V
.PawnSpecs
.bidirectional
)
879 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
881 if (V
.HasEnpassant
) {
882 // NOTE: backward en-passant captures are not considered
883 // because no rules define them (for now).
884 Array
.prototype.push
.apply(
886 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
893 // What are the rook moves from square x,y ?
894 getPotentialRookMoves(sq
) {
895 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
898 // What are the knight moves from square x,y ?
899 getPotentialKnightMoves(sq
) {
900 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], 1);
903 // What are the bishop moves from square x,y ?
904 getPotentialBishopMoves(sq
) {
905 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
908 // What are the queen moves from square x,y ?
909 getPotentialQueenMoves(sq
) {
910 return this.getSlideNJumpMoves(
911 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
914 // What are the king moves from square x,y ?
915 getPotentialKingMoves(sq
) {
916 // Initialize with normal moves
917 let moves
= this.getSlideNJumpMoves(
918 sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), 1);
919 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
920 moves
= moves
.concat(this.getCastleMoves(sq
));
924 // "castleInCheck" arg to let some variants castle under check
925 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
926 const c
= this.getColor(x
, y
);
929 const oppCol
= V
.GetOppCol(c
);
932 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
933 const castlingKing
= this.board
[x
][y
].charAt(1);
937 castleSide
++ //large, then small
939 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
940 // If this code is reached, rook and king are on initial position
942 // NOTE: in some variants this is not a rook
943 const rookPos
= this.castleFlags
[c
][castleSide
];
944 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
946 this.board
[x
][rookPos
] == V
.EMPTY
||
947 this.getColor(x
, rookPos
) != c
||
948 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
950 // Rook is not here, or changed color (see Benedict)
954 // Nothing on the path of the king ? (and no checks)
955 const finDist
= finalSquares
[castleSide
][0] - y
;
956 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
960 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
962 this.board
[x
][i
] != V
.EMPTY
&&
963 // NOTE: next check is enough, because of chessboard constraints
964 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
967 continue castlingCheck
;
970 } while (i
!= finalSquares
[castleSide
][0]);
972 // Nothing on the path to the rook?
973 step
= castleSide
== 0 ? -1 : 1;
974 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
975 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
978 // Nothing on final squares, except maybe king and castling rook?
979 for (i
= 0; i
< 2; i
++) {
981 finalSquares
[castleSide
][i
] != rookPos
&&
982 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
984 finalSquares
[castleSide
][i
] != y
||
985 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
988 continue castlingCheck
;
992 // If this code is reached, castle is valid
998 y: finalSquares
[castleSide
][0],
1004 y: finalSquares
[castleSide
][1],
1010 // King might be initially disguised (Titan...)
1011 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1012 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1015 Math
.abs(y
- rookPos
) <= 2
1016 ? { x: x
, y: rookPos
}
1017 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1025 ////////////////////
1028 // For the interface: possible moves for the current turn from square sq
1029 getPossibleMovesFrom(sq
) {
1030 return this.filterValid(this.getPotentialMovesFrom(sq
));
1033 // TODO: promotions (into R,B,N,Q) should be filtered only once
1034 filterValid(moves
) {
1035 if (moves
.length
== 0) return [];
1036 const color
= this.turn
;
1037 return moves
.filter(m
=> {
1039 const res
= !this.underCheck(color
);
1045 getAllPotentialMoves() {
1046 const color
= this.turn
;
1047 let potentialMoves
= [];
1048 for (let i
= 0; i
< V
.size
.x
; i
++) {
1049 for (let j
= 0; j
< V
.size
.y
; j
++) {
1050 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1051 Array
.prototype.push
.apply(
1053 this.getPotentialMovesFrom([i
, j
])
1058 return potentialMoves
;
1061 // Search for all valid moves considering current turn
1062 // (for engine and game end)
1063 getAllValidMoves() {
1064 return this.filterValid(this.getAllPotentialMoves());
1067 // Stop at the first move found
1068 // TODO: not really, it explores all moves from a square (one is enough).
1069 // Possible fix: add extra arg "oneMove" to getPotentialMovesFrom,
1070 // and then return only boolean true at first move found
1071 // (in all getPotentialXXXMoves() ... for all variants ...)
1073 const color
= this.turn
;
1074 for (let i
= 0; i
< V
.size
.x
; i
++) {
1075 for (let j
= 0; j
< V
.size
.y
; j
++) {
1076 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1077 const moves
= this.getPotentialMovesFrom([i
, j
]);
1078 if (moves
.length
> 0) {
1079 for (let k
= 0; k
< moves
.length
; k
++)
1080 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1088 // Check if pieces of given color are attacking (king) on square x,y
1089 isAttacked(sq
, color
) {
1091 this.isAttackedByPawn(sq
, color
) ||
1092 this.isAttackedByRook(sq
, color
) ||
1093 this.isAttackedByKnight(sq
, color
) ||
1094 this.isAttackedByBishop(sq
, color
) ||
1095 this.isAttackedByQueen(sq
, color
) ||
1096 this.isAttackedByKing(sq
, color
)
1100 // Generic method for non-pawn pieces ("sliding or jumping"):
1101 // is x,y attacked by a piece of given color ?
1102 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, nbSteps
) {
1103 for (let step
of steps
) {
1104 let rx
= x
+ step
[0],
1106 let stepCounter
= 1;
1108 V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&&
1109 (!nbSteps
|| stepCounter
< nbSteps
)
1116 V
.OnBoard(rx
, ry
) &&
1117 this.board
[rx
][ry
] != V
.EMPTY
&&
1118 this.getPiece(rx
, ry
) == piece
&&
1119 this.getColor(rx
, ry
) == color
1127 // Is square x,y attacked by 'color' pawns ?
1128 isAttackedByPawn(sq
, color
) {
1129 const pawnShift
= (color
== "w" ? 1 : -1);
1130 return this.isAttackedBySlideNJump(
1134 [[pawnShift
, 1], [pawnShift
, -1]],
1139 // Is square x,y attacked by 'color' rooks ?
1140 isAttackedByRook(sq
, color
) {
1141 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1144 // Is square x,y attacked by 'color' knights ?
1145 isAttackedByKnight(sq
, color
) {
1146 return this.isAttackedBySlideNJump(
1155 // Is square x,y attacked by 'color' bishops ?
1156 isAttackedByBishop(sq
, color
) {
1157 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1160 // Is square x,y attacked by 'color' queens ?
1161 isAttackedByQueen(sq
, color
) {
1162 return this.isAttackedBySlideNJump(
1166 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1170 // Is square x,y attacked by 'color' king(s) ?
1171 isAttackedByKing(sq
, color
) {
1172 return this.isAttackedBySlideNJump(
1176 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1181 // Is color under check after his move ?
1183 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1189 // Apply a move on board
1190 static PlayOnBoard(board
, move) {
1191 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1192 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1194 // Un-apply the played move
1195 static UndoOnBoard(board
, move) {
1196 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1197 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1204 // if (!this.states) this.states = [];
1205 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1206 // this.states.push(stateFen);
1209 // Save flags (for undo)
1210 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1211 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1212 V
.PlayOnBoard(this.board
, move);
1213 this.turn
= V
.GetOppCol(this.turn
);
1215 this.postPlay(move);
1218 updateCastleFlags(move, piece
, color
) {
1219 // TODO: check flags. If already off, no need to always re-evaluate
1220 const c
= color
|| V
.GetOppCol(this.turn
);
1221 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1222 // Update castling flags if rooks are moved
1223 const oppCol
= this.turn
;
1224 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1225 if (piece
== V
.KING
&& move.appear
.length
> 0)
1226 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1228 move.start
.x
== firstRank
&& //our rook moves?
1229 this.castleFlags
[c
].includes(move.start
.y
)
1231 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1232 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1234 // NOTE: not "else if" because a rook could take an opposing rook
1236 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1237 this.castleFlags
[oppCol
].includes(move.end
.y
)
1239 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1240 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1244 // After move is played, update variables + flags
1246 const c
= V
.GetOppCol(this.turn
);
1247 let piece
= undefined;
1248 if (move.vanish
.length
>= 1)
1249 // Usual case, something is moved
1250 piece
= move.vanish
[0].p
;
1252 // Crazyhouse-like variants
1253 piece
= move.appear
[0].p
;
1255 // Update king position + flags
1256 if (piece
== V
.KING
&& move.appear
.length
> 0)
1257 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1258 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1265 if (V
.HasEnpassant
) this.epSquares
.pop();
1266 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1267 V
.UndoOnBoard(this.board
, move);
1268 this.turn
= V
.GetOppCol(this.turn
);
1270 this.postUndo(move);
1273 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1274 // if (stateFen != this.states[this.states.length-1]) debugger;
1275 // this.states.pop();
1278 // After move is undo-ed *and flags resetted*, un-update other variables
1279 // TODO: more symmetry, by storing flags increment in move (?!)
1281 // (Potentially) Reset king position
1282 const c
= this.getColor(move.start
.x
, move.start
.y
);
1283 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1284 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1290 // What is the score ? (Interesting if game is over)
1292 if (this.atLeastOneMove()) return "*";
1294 const color
= this.turn
;
1295 // No valid move: stalemate or checkmate?
1296 if (!this.underCheck(color
)) return "1/2";
1298 return (color
== "w" ? "0-1" : "1-0");
1305 static get VALUES() {
1316 // "Checkmate" (unreachable eval)
1317 static get INFINITY() {
1321 // At this value or above, the game is over
1322 static get THRESHOLD_MATE() {
1326 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1327 static get SEARCH_DEPTH() {
1331 // 'movesList' arg for some variants to provide a custom list
1332 getComputerMove(movesList
) {
1333 const maxeval
= V
.INFINITY
;
1334 const color
= this.turn
;
1335 let moves1
= movesList
|| this.getAllValidMoves();
1337 if (moves1
.length
== 0)
1338 // TODO: this situation should not happen
1341 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1342 for (let i
= 0; i
< moves1
.length
; i
++) {
1343 this.play(moves1
[i
]);
1344 const score1
= this.getCurrentScore();
1345 if (score1
!= "*") {
1349 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1351 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1352 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1353 this.undo(moves1
[i
]);
1356 // Initial self evaluation is very low: "I'm checkmated"
1357 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1358 // Initial enemy evaluation is very low too, for him
1359 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1360 // Second half-move:
1361 let moves2
= this.getAllValidMoves();
1362 for (let j
= 0; j
< moves2
.length
; j
++) {
1363 this.play(moves2
[j
]);
1364 const score2
= this.getCurrentScore();
1365 let evalPos
= 0; //1/2 value
1368 evalPos
= this.evalPosition();
1378 (color
== "w" && evalPos
< eval2
) ||
1379 (color
== "b" && evalPos
> eval2
)
1383 this.undo(moves2
[j
]);
1386 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1387 (color
== "b" && eval2
< moves1
[i
].eval
)
1389 moves1
[i
].eval
= eval2
;
1391 this.undo(moves1
[i
]);
1393 moves1
.sort((a
, b
) => {
1394 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1396 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1398 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1399 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1400 for (let i
= 0; i
< moves1
.length
; i
++) {
1401 this.play(moves1
[i
]);
1402 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1404 0.1 * moves1
[i
].eval
+
1405 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1406 this.undo(moves1
[i
]);
1408 moves1
.sort((a
, b
) => {
1409 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1413 let candidates
= [0];
1414 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1416 return moves1
[candidates
[randInt(candidates
.length
)]];
1419 alphabeta(depth
, alpha
, beta
) {
1420 const maxeval
= V
.INFINITY
;
1421 const color
= this.turn
;
1422 const score
= this.getCurrentScore();
1424 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1425 if (depth
== 0) return this.evalPosition();
1426 const moves
= this.getAllValidMoves();
1427 let v
= color
== "w" ? -maxeval : maxeval
;
1429 for (let i
= 0; i
< moves
.length
; i
++) {
1430 this.play(moves
[i
]);
1431 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1432 this.undo(moves
[i
]);
1433 alpha
= Math
.max(alpha
, v
);
1434 if (alpha
>= beta
) break; //beta cutoff
1439 for (let i
= 0; i
< moves
.length
; i
++) {
1440 this.play(moves
[i
]);
1441 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1442 this.undo(moves
[i
]);
1443 beta
= Math
.min(beta
, v
);
1444 if (alpha
>= beta
) break; //alpha cutoff
1452 // Just count material for now
1453 for (let i
= 0; i
< V
.size
.x
; i
++) {
1454 for (let j
= 0; j
< V
.size
.y
; j
++) {
1455 if (this.board
[i
][j
] != V
.EMPTY
) {
1456 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1457 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1464 /////////////////////////
1465 // MOVES + GAME NOTATION
1466 /////////////////////////
1468 // Context: just before move is played, turn hasn't changed
1469 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1471 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1473 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1475 // Translate final square
1476 const finalSquare
= V
.CoordsToSquare(move.end
);
1478 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1479 if (piece
== V
.PAWN
) {
1482 if (move.vanish
.length
> move.appear
.length
) {
1484 const startColumn
= V
.CoordToColumn(move.start
.y
);
1485 notation
= startColumn
+ "x" + finalSquare
;
1487 else notation
= finalSquare
;
1488 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1490 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1495 piece
.toUpperCase() +
1496 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1501 static GetUnambiguousNotation(move) {
1502 // Machine-readable format with all the informations about the move
1504 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1505 ? V
.CoordsToSquare(move.start
)
1508 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1509 ? V
.CoordsToSquare(move.end
)
1512 (!!move.appear
&& move.appear
.length
> 0
1513 ? move.appear
.map(a
=>
1514 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1517 (!!move.vanish
&& move.vanish
.length
> 0
1518 ? move.vanish
.map(a
=>
1519 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")