0549139877e5ad5ebb1ed6bc54b318febb4ce212
1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
4 import { ArrayFun
} from "@/utils/array";
5 import { randInt
, shuffle
} from "@/utils/alea";
7 // class "PiPo": Piece + Position
8 export const PiPo
= class PiPo
{
9 // o: {piece[p], color[c], posX[x], posY[y]}
18 export const Move
= class Move
{
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
23 this.appear
= o
.appear
;
24 this.vanish
= o
.vanish
;
25 this.start
= o
.start
|| { x: o
.vanish
[0].x
, y: o
.vanish
[0].y
};
26 this.end
= o
.end
|| { x: o
.appear
[0].x
, y: o
.appear
[0].y
};
30 // NOTE: x coords = top to bottom; y = left to right
31 // (from white player perspective)
32 export const ChessRules
= class ChessRules
{
37 // Some variants don't have flags:
38 static get HasFlags() {
43 static get HasCastle() {
47 // Pawns specifications
48 static get PawnSpecs() {
50 directions: { 'w': -1, 'b': 1 },
51 initShift: { w: 1, b: 1 },
54 promotions: [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
],
56 captureBackward: false,
61 // En-passant captures need a stack of squares:
62 static get HasEnpassant() {
66 // Some variants cannot have analyse mode
67 static get CanAnalyze() {
70 // Patch: issues with javascript OOP, objects can't access static fields.
75 // Some variants show incomplete information,
76 // and thus show only a partial moves list or no list at all.
77 static get ShowMoves() {
84 // Sometimes moves must remain hidden until game ends
85 static get SomeHiddenMoves() {
88 get someHiddenMoves() {
89 return V
.SomeHiddenMoves
;
92 // Generally true, unless the variant includes random effects
93 static get CorrConfirm() {
97 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
102 // Some variants always show the same orientation
103 static get CanFlip() {
110 // For (generally old) variants without checkered board
111 static get Monochrome() {
115 // Some games are drawn unusually (bottom right corner is black)
116 static get DarkBottomRight() {
120 // Some variants require lines drawing
124 // Draw all inter-squares lines
125 for (let i
= 0; i
<= V
.size
.x
; i
++)
126 lines
.push([[i
, 0], [i
, V
.size
.y
]]);
127 for (let j
= 0; j
<= V
.size
.y
; j
++)
128 lines
.push([[0, j
], [V
.size
.x
, j
]]);
134 // In some variants, the player who repeat a position loses
135 static get LoseOnRepetition() {
139 // At some stages, some games could wait clicks only:
144 // Some variants use click infos:
149 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
154 static get IMAGE_EXTENSION() {
155 // All pieces should be in the SVG format
159 // Turn "wb" into "B" (for FEN)
160 static board2fen(b
) {
161 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
164 // Turn "p" into "bp" (for board)
165 static fen2board(f
) {
166 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
169 // Check if FEN describes a board situation correctly
170 static IsGoodFen(fen
) {
171 const fenParsed
= V
.ParseFen(fen
);
173 if (!V
.IsGoodPosition(fenParsed
.position
)) return false;
175 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
)) return false;
176 // 3) Check moves count
177 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
, 10) >= 0))
180 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
182 // 5) Check enpassant
185 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
))
192 // Is position part of the FEN a priori correct?
193 static IsGoodPosition(position
) {
194 if (position
.length
== 0) return false;
195 const rows
= position
.split("/");
196 if (rows
.length
!= V
.size
.x
) return false;
197 let kings
= { "k": 0, "K": 0 };
198 for (let row
of rows
) {
200 for (let i
= 0; i
< row
.length
; i
++) {
201 if (['K','k'].includes(row
[i
])) kings
[row
[i
]]++;
202 if (V
.PIECES
.includes(row
[i
].toLowerCase())) sumElts
++;
204 const num
= parseInt(row
[i
], 10);
205 if (isNaN(num
) || num
<= 0) return false;
209 if (sumElts
!= V
.size
.y
) return false;
211 // Both kings should be on board. Exactly one per color.
212 if (Object
.values(kings
).some(v
=> v
!= 1)) return false;
217 static IsGoodTurn(turn
) {
218 return ["w", "b"].includes(turn
);
222 static IsGoodFlags(flags
) {
223 // NOTE: a little too permissive to work with more variants
224 return !!flags
.match(/^[a-z]{4,4}$/);
227 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
228 static IsGoodEnpassant(enpassant
) {
229 if (enpassant
!= "-") {
230 const ep
= V
.SquareToCoords(enpassant
);
231 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
236 // 3 --> d (column number to letter)
237 static CoordToColumn(colnum
) {
238 return String
.fromCharCode(97 + colnum
);
241 // d --> 3 (column letter to number)
242 static ColumnToCoord(column
) {
243 return column
.charCodeAt(0) - 97;
247 static SquareToCoords(sq
) {
249 // NOTE: column is always one char => max 26 columns
250 // row is counted from black side => subtraction
251 x: V
.size
.x
- parseInt(sq
.substr(1), 10),
252 y: sq
[0].charCodeAt() - 97
257 static CoordsToSquare(coords
) {
258 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
261 // Path to pieces (standard ones in pieces/ folder)
266 // Path to promotion pieces (usually the same)
268 return this.getPpath(m
.appear
[0].c
+ m
.appear
[0].p
);
271 // Aggregates flags into one object
273 return this.castleFlags
;
277 disaggregateFlags(flags
) {
278 this.castleFlags
= flags
;
281 // En-passant square, if any
282 getEpSquare(moveOrSquare
) {
283 if (!moveOrSquare
) return undefined; //TODO: necessary line?!
284 if (typeof moveOrSquare
=== "string") {
285 const square
= moveOrSquare
;
286 if (square
== "-") return undefined;
287 return V
.SquareToCoords(square
);
289 // Argument is a move:
290 const move = moveOrSquare
;
291 const s
= move.start
,
295 Math
.abs(s
.x
- e
.x
) == 2 &&
296 // Next conditions for variants like Atomic or Rifle, Recycle...
297 (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
) &&
298 (move.vanish
.length
> 0 && move.vanish
[0].p
== V
.PAWN
)
305 return undefined; //default
308 // Can thing on square1 take thing on square2
309 canTake([x1
, y1
], [x2
, y2
]) {
310 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
313 // Is (x,y) on the chessboard?
314 static OnBoard(x
, y
) {
315 return x
>= 0 && x
< V
.size
.x
&& y
>= 0 && y
< V
.size
.y
;
318 // Used in interface: 'side' arg == player color
319 canIplay(side
, [x
, y
]) {
320 return this.turn
== side
&& this.getColor(x
, y
) == side
;
323 // On which squares is color under check ? (for interface)
325 const color
= this.turn
;
327 this.underCheck(color
)
328 // kingPos must be duplicated, because it may change:
329 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))]
337 // Setup the initial random (asymmetric) position
338 static GenRandInitFen(randomness
) {
341 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
343 let pieces
= { w: new Array(8), b: new Array(8) };
345 // Shuffle pieces on first (and last rank if randomness == 2)
346 for (let c
of ["w", "b"]) {
347 if (c
== 'b' && randomness
== 1) {
348 pieces
['b'] = pieces
['w'];
353 let positions
= ArrayFun
.range(8);
355 // Get random squares for bishops
356 let randIndex
= 2 * randInt(4);
357 const bishop1Pos
= positions
[randIndex
];
358 // The second bishop must be on a square of different color
359 let randIndex_tmp
= 2 * randInt(4) + 1;
360 const bishop2Pos
= positions
[randIndex_tmp
];
361 // Remove chosen squares
362 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
363 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
365 // Get random squares for knights
366 randIndex
= randInt(6);
367 const knight1Pos
= positions
[randIndex
];
368 positions
.splice(randIndex
, 1);
369 randIndex
= randInt(5);
370 const knight2Pos
= positions
[randIndex
];
371 positions
.splice(randIndex
, 1);
373 // Get random square for queen
374 randIndex
= randInt(4);
375 const queenPos
= positions
[randIndex
];
376 positions
.splice(randIndex
, 1);
378 // Rooks and king positions are now fixed,
379 // because of the ordering rook-king-rook
380 const rook1Pos
= positions
[0];
381 const kingPos
= positions
[1];
382 const rook2Pos
= positions
[2];
384 // Finally put the shuffled pieces in the board array
385 pieces
[c
][rook1Pos
] = "r";
386 pieces
[c
][knight1Pos
] = "n";
387 pieces
[c
][bishop1Pos
] = "b";
388 pieces
[c
][queenPos
] = "q";
389 pieces
[c
][kingPos
] = "k";
390 pieces
[c
][bishop2Pos
] = "b";
391 pieces
[c
][knight2Pos
] = "n";
392 pieces
[c
][rook2Pos
] = "r";
393 flags
+= V
.CoordToColumn(rook1Pos
) + V
.CoordToColumn(rook2Pos
);
395 // Add turn + flags + enpassant
397 pieces
["b"].join("") +
398 "/pppppppp/8/8/8/8/PPPPPPPP/" +
399 pieces
["w"].join("").toUpperCase() +
400 " w 0 " + flags
+ " -"
404 // "Parse" FEN: just return untransformed string data
405 static ParseFen(fen
) {
406 const fenParts
= fen
.split(" ");
408 position: fenParts
[0],
410 movesCount: fenParts
[2]
413 if (V
.HasFlags
) Object
.assign(res
, { flags: fenParts
[nextIdx
++] });
414 if (V
.HasEnpassant
) Object
.assign(res
, { enpassant: fenParts
[nextIdx
] });
418 // Return current fen (game state)
421 this.getBaseFen() + " " +
422 this.getTurnFen() + " " +
424 (V
.HasFlags
? " " + this.getFlagsFen() : "") +
425 (V
.HasEnpassant
? " " + this.getEnpassantFen() : "")
430 // Omit movesCount, only variable allowed to differ
432 this.getBaseFen() + "_" +
434 (V
.HasFlags
? "_" + this.getFlagsFen() : "") +
435 (V
.HasEnpassant
? "_" + this.getEnpassantFen() : "")
439 // Position part of the FEN string
441 const format
= (count
) => {
442 // if more than 9 consecutive free spaces, break the integer,
443 // otherwise FEN parsing will fail.
444 if (count
<= 9) return count
;
445 // Currently only boards of size up to 11 or 12:
446 return "9" + (count
- 9);
449 for (let i
= 0; i
< V
.size
.x
; i
++) {
451 for (let j
= 0; j
< V
.size
.y
; j
++) {
452 if (this.board
[i
][j
] == V
.EMPTY
) emptyCount
++;
454 if (emptyCount
> 0) {
455 // Add empty squares in-between
456 position
+= format(emptyCount
);
459 position
+= V
.board2fen(this.board
[i
][j
]);
462 if (emptyCount
> 0) {
464 position
+= format(emptyCount
);
466 if (i
< V
.size
.x
- 1) position
+= "/"; //separate rows
475 // Flags part of the FEN string
479 for (let c
of ["w", "b"])
480 flags
+= this.castleFlags
[c
].map(V
.CoordToColumn
).join("");
484 // Enpassant part of the FEN string
486 const L
= this.epSquares
.length
;
487 if (!this.epSquares
[L
- 1]) return "-"; //no en-passant
488 return V
.CoordsToSquare(this.epSquares
[L
- 1]);
491 // Turn position fen into double array ["wb","wp","bk",...]
492 static GetBoard(position
) {
493 const rows
= position
.split("/");
494 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
495 for (let i
= 0; i
< rows
.length
; i
++) {
497 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
498 const character
= rows
[i
][indexInRow
];
499 const num
= parseInt(character
, 10);
500 // If num is a number, just shift j:
501 if (!isNaN(num
)) j
+= num
;
502 // Else: something at position i,j
503 else board
[i
][j
++] = V
.fen2board(character
);
509 // Extract (relevant) flags from fen
511 // white a-castle, h-castle, black a-castle, h-castle
512 this.castleFlags
= { w: [-1, -1], b: [-1, -1] };
513 for (let i
= 0; i
< 4; i
++) {
514 this.castleFlags
[i
< 2 ? "w" : "b"][i
% 2] =
515 V
.ColumnToCoord(fenflags
.charAt(i
));
522 // Fen string fully describes the game state
525 // In printDiagram() fen isn't supply because only getPpath() is used
526 // TODO: find a better solution!
528 const fenParsed
= V
.ParseFen(fen
);
529 this.board
= V
.GetBoard(fenParsed
.position
);
530 this.turn
= fenParsed
.turn
;
531 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
532 this.setOtherVariables(fen
);
535 // Scan board for kings positions
536 // TODO: should be done from board, no need for the complete FEN
538 // Squares of white and black king:
539 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
540 const fenRows
= V
.ParseFen(fen
).position
.split("/");
541 for (let i
= 0; i
< fenRows
.length
; i
++) {
542 let k
= 0; //column index on board
543 for (let j
= 0; j
< fenRows
[i
].length
; j
++) {
544 switch (fenRows
[i
].charAt(j
)) {
546 this.kingPos
["b"] = [i
, k
];
549 this.kingPos
["w"] = [i
, k
];
552 const num
= parseInt(fenRows
[i
].charAt(j
), 10);
553 if (!isNaN(num
)) k
+= num
- 1;
561 // Some additional variables from FEN (variant dependant)
562 setOtherVariables(fen
) {
563 // Set flags and enpassant:
564 const parsedFen
= V
.ParseFen(fen
);
565 if (V
.HasFlags
) this.setFlags(parsedFen
.flags
);
566 if (V
.HasEnpassant
) {
568 parsedFen
.enpassant
!= "-"
569 ? this.getEpSquare(parsedFen
.enpassant
)
571 this.epSquares
= [epSq
];
573 // Search for kings positions:
577 /////////////////////
581 return { x: 8, y: 8 };
584 // Color of thing on square (i,j). 'undefined' if square is empty
586 return this.board
[i
][j
].charAt(0);
589 // Piece type on square (i,j). 'undefined' if square is empty
591 return this.board
[i
][j
].charAt(1);
594 // Get opponent color
595 static GetOppCol(color
) {
596 return color
== "w" ? "b" : "w";
599 // Pieces codes (for a clearer code)
606 static get KNIGHT() {
609 static get BISHOP() {
620 static get PIECES() {
621 return [V
.PAWN
, V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.KING
];
629 // Some pieces movements
660 // All possible moves from selected square
661 getPotentialMovesFrom(sq
) {
662 switch (this.getPiece(sq
[0], sq
[1])) {
663 case V
.PAWN: return this.getPotentialPawnMoves(sq
);
664 case V
.ROOK: return this.getPotentialRookMoves(sq
);
665 case V
.KNIGHT: return this.getPotentialKnightMoves(sq
);
666 case V
.BISHOP: return this.getPotentialBishopMoves(sq
);
667 case V
.QUEEN: return this.getPotentialQueenMoves(sq
);
668 case V
.KING: return this.getPotentialKingMoves(sq
);
670 return []; //never reached (but some variants may use it: Bario...)
673 // Build a regular move from its initial and destination squares.
674 // tr: transformation
675 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
676 const initColor
= this.getColor(sx
, sy
);
677 const initPiece
= this.board
[sx
][sy
].charAt(1);
683 c: !!tr
? tr
.c : initColor
,
684 p: !!tr
? tr
.p : initPiece
697 // The opponent piece disappears if we take it
698 if (this.board
[ex
][ey
] != V
.EMPTY
) {
703 c: this.getColor(ex
, ey
),
704 p: this.board
[ex
][ey
].charAt(1)
712 // Generic method to find possible moves of non-pawn pieces:
713 // "sliding or jumping"
714 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
716 outerLoop: for (let step
of steps
) {
719 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
720 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
721 if (!!oneStep
) continue outerLoop
;
725 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
]))
726 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
731 // Special case of en-passant captures: treated separately
732 getEnpassantCaptures([x
, y
], shiftX
) {
733 const Lep
= this.epSquares
.length
;
734 const epSquare
= this.epSquares
[Lep
- 1]; //always at least one element
735 let enpassantMove
= null;
738 epSquare
.x
== x
+ shiftX
&&
739 Math
.abs(epSquare
.y
- y
) == 1
741 enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
742 enpassantMove
.vanish
.push({
745 p: this.board
[x
][epSquare
.y
].charAt(1),
746 c: this.getColor(x
, epSquare
.y
)
749 return !!enpassantMove
? [enpassantMove
] : [];
752 // Consider all potential promotions:
753 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
754 let finalPieces
= [V
.PAWN
];
755 const color
= this.turn
; //this.getColor(x1, y1);
756 const lastRank
= (color
== "w" ? 0 : V
.size
.x
- 1);
757 if (x2
== lastRank
) {
758 // promotions arg: special override for Hiddenqueen variant
759 if (!!promotions
) finalPieces
= promotions
;
760 else if (!!V
.PawnSpecs
.promotions
) finalPieces
= V
.PawnSpecs
.promotions
;
763 for (let piece
of finalPieces
) {
764 tr
= (piece
!= V
.PAWN
? { c: color
, p: piece
} : null);
765 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
769 // What are the pawn moves from square x,y ?
770 getPotentialPawnMoves([x
, y
], promotions
) {
771 const color
= this.turn
; //this.getColor(x, y);
772 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
773 const pawnShiftX
= V
.PawnSpecs
.directions
[color
];
774 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
775 const forward
= (color
== 'w' ? -1 : 1);
777 // Pawn movements in shiftX direction:
778 const getPawnMoves
= (shiftX
) => {
780 // NOTE: next condition is generally true (no pawn on last rank)
781 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
782 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
783 // One square forward (or backward)
784 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
785 // Next condition because pawns on 1st rank can generally jump
787 V
.PawnSpecs
.twoSquares
&&
789 (color
== 'w' && x
>= V
.size
.x
- 1 - V
.PawnSpecs
.initShift
['w'])
791 (color
== 'b' && x
<= V
.PawnSpecs
.initShift
['b'])
796 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
799 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
801 V
.PawnSpecs
.threeSquares
&&
802 this.board
[x
+ 3 * shiftX
][y
] == V
.EMPTY
804 // Three squares jump
805 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
811 if (V
.PawnSpecs
.canCapture
) {
812 for (let shiftY
of [-1, 1]) {
813 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
) {
815 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
816 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
819 [x
, y
], [x
+ shiftX
, y
+ shiftY
],
824 V
.PawnSpecs
.captureBackward
&& shiftX
== forward
&&
825 x
- shiftX
>= 0 && x
- shiftX
< V
.size
.x
&&
826 this.board
[x
- shiftX
][y
+ shiftY
] != V
.EMPTY
&&
827 this.canTake([x
, y
], [x
- shiftX
, y
+ shiftY
])
830 [x
, y
], [x
- shiftX
, y
+ shiftY
],
841 let pMoves
= getPawnMoves(pawnShiftX
);
842 if (V
.PawnSpecs
.bidirectional
)
843 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
845 if (V
.HasEnpassant
) {
846 // NOTE: backward en-passant captures are not considered
847 // because no rules define them (for now).
848 Array
.prototype.push
.apply(
850 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
857 // What are the rook moves from square x,y ?
858 getPotentialRookMoves(sq
) {
859 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
862 // What are the knight moves from square x,y ?
863 getPotentialKnightMoves(sq
) {
864 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
867 // What are the bishop moves from square x,y ?
868 getPotentialBishopMoves(sq
) {
869 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
872 // What are the queen moves from square x,y ?
873 getPotentialQueenMoves(sq
) {
874 return this.getSlideNJumpMoves(
876 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
880 // What are the king moves from square x,y ?
881 getPotentialKingMoves(sq
) {
882 // Initialize with normal moves
883 let moves
= this.getSlideNJumpMoves(
885 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
888 if (V
.HasCastle
&& this.castleFlags
[this.turn
].some(v
=> v
< V
.size
.y
))
889 moves
= moves
.concat(this.getCastleMoves(sq
));
893 // "castleInCheck" arg to let some variants castle under check
894 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
895 const c
= this.getColor(x
, y
);
898 const oppCol
= V
.GetOppCol(c
);
901 finalSquares
= finalSquares
|| [ [2, 3], [V
.size
.y
- 2, V
.size
.y
- 3] ];
902 const castlingKing
= this.board
[x
][y
].charAt(1);
906 castleSide
++ //large, then small
908 if (this.castleFlags
[c
][castleSide
] >= V
.size
.y
) continue;
909 // If this code is reached, rook and king are on initial position
911 // NOTE: in some variants this is not a rook
912 const rookPos
= this.castleFlags
[c
][castleSide
];
913 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
915 this.board
[x
][rookPos
] == V
.EMPTY
||
916 this.getColor(x
, rookPos
) != c
||
917 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
919 // Rook is not here, or changed color (see Benedict)
923 // Nothing on the path of the king ? (and no checks)
924 const finDist
= finalSquares
[castleSide
][0] - y
;
925 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
929 (!castleInCheck
&& this.isAttacked([x
, i
], oppCol
)) ||
931 this.board
[x
][i
] != V
.EMPTY
&&
932 // NOTE: next check is enough, because of chessboard constraints
933 (this.getColor(x
, i
) != c
|| ![y
, rookPos
].includes(i
))
936 continue castlingCheck
;
939 } while (i
!= finalSquares
[castleSide
][0]);
941 // Nothing on the path to the rook?
942 step
= castleSide
== 0 ? -1 : 1;
943 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
944 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
947 // Nothing on final squares, except maybe king and castling rook?
948 for (i
= 0; i
< 2; i
++) {
950 finalSquares
[castleSide
][i
] != rookPos
&&
951 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
953 finalSquares
[castleSide
][i
] != y
||
954 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
957 continue castlingCheck
;
961 // If this code is reached, castle is valid
967 y: finalSquares
[castleSide
][0],
973 y: finalSquares
[castleSide
][1],
979 // King might be initially disguised (Titan...)
980 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
981 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
984 Math
.abs(y
- rookPos
) <= 2
985 ? { x: x
, y: rookPos
}
986 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
997 // For the interface: possible moves for the current turn from square sq
998 getPossibleMovesFrom(sq
) {
999 return this.filterValid(this.getPotentialMovesFrom(sq
));
1002 // TODO: promotions (into R,B,N,Q) should be filtered only once
1003 filterValid(moves
) {
1004 if (moves
.length
== 0) return [];
1005 const color
= this.turn
;
1006 return moves
.filter(m
=> {
1008 const res
= !this.underCheck(color
);
1014 getAllPotentialMoves() {
1015 const color
= this.turn
;
1016 let potentialMoves
= [];
1017 for (let i
= 0; i
< V
.size
.x
; i
++) {
1018 for (let j
= 0; j
< V
.size
.y
; j
++) {
1019 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1020 Array
.prototype.push
.apply(
1022 this.getPotentialMovesFrom([i
, j
])
1027 return potentialMoves
;
1030 // Search for all valid moves considering current turn
1031 // (for engine and game end)
1032 getAllValidMoves() {
1033 return this.filterValid(this.getAllPotentialMoves());
1036 // Stop at the first move found
1037 // TODO: not really, it explores all moves from a square (one is enough).
1039 const color
= this.turn
;
1040 for (let i
= 0; i
< V
.size
.x
; i
++) {
1041 for (let j
= 0; j
< V
.size
.y
; j
++) {
1042 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
, j
) == color
) {
1043 const moves
= this.getPotentialMovesFrom([i
, j
]);
1044 if (moves
.length
> 0) {
1045 for (let k
= 0; k
< moves
.length
; k
++)
1046 if (this.filterValid([moves
[k
]]).length
> 0) return true;
1054 // Check if pieces of given color are attacking (king) on square x,y
1055 isAttacked(sq
, color
) {
1057 this.isAttackedByPawn(sq
, color
) ||
1058 this.isAttackedByRook(sq
, color
) ||
1059 this.isAttackedByKnight(sq
, color
) ||
1060 this.isAttackedByBishop(sq
, color
) ||
1061 this.isAttackedByQueen(sq
, color
) ||
1062 this.isAttackedByKing(sq
, color
)
1066 // Generic method for non-pawn pieces ("sliding or jumping"):
1067 // is x,y attacked by a piece of given color ?
1068 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
1069 for (let step
of steps
) {
1070 let rx
= x
+ step
[0],
1072 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
1077 V
.OnBoard(rx
, ry
) &&
1078 this.board
[rx
][ry
] != V
.EMPTY
&&
1079 this.getPiece(rx
, ry
) == piece
&&
1080 this.getColor(rx
, ry
) == color
1088 // Is square x,y attacked by 'color' pawns ?
1089 isAttackedByPawn(sq
, color
) {
1090 const pawnShift
= (color
== "w" ? 1 : -1);
1091 return this.isAttackedBySlideNJump(
1095 [[pawnShift
, 1], [pawnShift
, -1]],
1100 // Is square x,y attacked by 'color' rooks ?
1101 isAttackedByRook(sq
, color
) {
1102 return this.isAttackedBySlideNJump(sq
, color
, V
.ROOK
, V
.steps
[V
.ROOK
]);
1105 // Is square x,y attacked by 'color' knights ?
1106 isAttackedByKnight(sq
, color
) {
1107 return this.isAttackedBySlideNJump(
1116 // Is square x,y attacked by 'color' bishops ?
1117 isAttackedByBishop(sq
, color
) {
1118 return this.isAttackedBySlideNJump(sq
, color
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
1121 // Is square x,y attacked by 'color' queens ?
1122 isAttackedByQueen(sq
, color
) {
1123 return this.isAttackedBySlideNJump(
1127 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])
1131 // Is square x,y attacked by 'color' king(s) ?
1132 isAttackedByKing(sq
, color
) {
1133 return this.isAttackedBySlideNJump(
1137 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
1142 // Is color under check after his move ?
1144 return this.isAttacked(this.kingPos
[color
], V
.GetOppCol(color
));
1150 // Apply a move on board
1151 static PlayOnBoard(board
, move) {
1152 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1153 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1155 // Un-apply the played move
1156 static UndoOnBoard(board
, move) {
1157 for (let psq
of move.appear
) board
[psq
.x
][psq
.y
] = V
.EMPTY
;
1158 for (let psq
of move.vanish
) board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1165 // if (!this.states) this.states = [];
1166 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1167 // this.states.push(stateFen);
1170 // Save flags (for undo)
1171 if (V
.HasFlags
) move.flags
= JSON
.stringify(this.aggregateFlags());
1172 if (V
.HasEnpassant
) this.epSquares
.push(this.getEpSquare(move));
1173 V
.PlayOnBoard(this.board
, move);
1174 this.turn
= V
.GetOppCol(this.turn
);
1176 this.postPlay(move);
1179 updateCastleFlags(move, piece
, color
) {
1180 // TODO: check flags. If already off, no need to always re-evaluate
1181 const c
= color
|| V
.GetOppCol(this.turn
);
1182 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
1183 // Update castling flags if rooks are moved
1184 const oppCol
= this.turn
;
1185 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1186 if (piece
== V
.KING
&& move.appear
.length
> 0)
1187 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1189 move.start
.x
== firstRank
&& //our rook moves?
1190 this.castleFlags
[c
].includes(move.start
.y
)
1192 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1193 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1195 // NOTE: not "else if" because a rook could take an opposing rook
1197 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1198 this.castleFlags
[oppCol
].includes(move.end
.y
)
1200 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1201 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1205 // After move is played, update variables + flags
1207 const c
= V
.GetOppCol(this.turn
);
1208 let piece
= undefined;
1209 if (move.vanish
.length
>= 1)
1210 // Usual case, something is moved
1211 piece
= move.vanish
[0].p
;
1213 // Crazyhouse-like variants
1214 piece
= move.appear
[0].p
;
1216 // Update king position + flags
1217 if (piece
== V
.KING
&& move.appear
.length
> 0)
1218 this.kingPos
[c
] = [move.appear
[0].x
, move.appear
[0].y
];
1219 if (V
.HasCastle
) this.updateCastleFlags(move, piece
);
1226 if (V
.HasEnpassant
) this.epSquares
.pop();
1227 if (V
.HasFlags
) this.disaggregateFlags(JSON
.parse(move.flags
));
1228 V
.UndoOnBoard(this.board
, move);
1229 this.turn
= V
.GetOppCol(this.turn
);
1231 this.postUndo(move);
1234 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1235 // if (stateFen != this.states[this.states.length-1]) debugger;
1236 // this.states.pop();
1239 // After move is undo-ed *and flags resetted*, un-update other variables
1240 // TODO: more symmetry, by storing flags increment in move (?!)
1242 // (Potentially) Reset king position
1243 const c
= this.getColor(move.start
.x
, move.start
.y
);
1244 if (this.getPiece(move.start
.x
, move.start
.y
) == V
.KING
)
1245 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1251 // What is the score ? (Interesting if game is over)
1253 if (this.atLeastOneMove()) return "*";
1255 const color
= this.turn
;
1256 // No valid move: stalemate or checkmate?
1257 if (!this.underCheck(color
)) return "1/2";
1259 return (color
== "w" ? "0-1" : "1-0");
1266 static get VALUES() {
1277 // "Checkmate" (unreachable eval)
1278 static get INFINITY() {
1282 // At this value or above, the game is over
1283 static get THRESHOLD_MATE() {
1287 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1288 static get SEARCH_DEPTH() {
1292 // 'movesList' arg for some variants to provide a custom list
1293 getComputerMove(movesList
) {
1294 const maxeval
= V
.INFINITY
;
1295 const color
= this.turn
;
1296 let moves1
= movesList
|| this.getAllValidMoves();
1298 if (moves1
.length
== 0)
1299 // TODO: this situation should not happen
1302 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1303 for (let i
= 0; i
< moves1
.length
; i
++) {
1304 this.play(moves1
[i
]);
1305 const score1
= this.getCurrentScore();
1306 if (score1
!= "*") {
1310 : (score1
== "1-0" ? 1 : -1) * maxeval
;
1312 if (V
.SEARCH_DEPTH
== 1 || score1
!= "*") {
1313 if (!moves1
[i
].eval
) moves1
[i
].eval
= this.evalPosition();
1314 this.undo(moves1
[i
]);
1317 // Initial self evaluation is very low: "I'm checkmated"
1318 moves1
[i
].eval
= (color
== "w" ? -1 : 1) * maxeval
;
1319 // Initial enemy evaluation is very low too, for him
1320 let eval2
= (color
== "w" ? 1 : -1) * maxeval
;
1321 // Second half-move:
1322 let moves2
= this.getAllValidMoves();
1323 for (let j
= 0; j
< moves2
.length
; j
++) {
1324 this.play(moves2
[j
]);
1325 const score2
= this.getCurrentScore();
1326 let evalPos
= 0; //1/2 value
1329 evalPos
= this.evalPosition();
1339 (color
== "w" && evalPos
< eval2
) ||
1340 (color
== "b" && evalPos
> eval2
)
1344 this.undo(moves2
[j
]);
1347 (color
== "w" && eval2
> moves1
[i
].eval
) ||
1348 (color
== "b" && eval2
< moves1
[i
].eval
)
1350 moves1
[i
].eval
= eval2
;
1352 this.undo(moves1
[i
]);
1354 moves1
.sort((a
, b
) => {
1355 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1357 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1359 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1360 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
) {
1361 for (let i
= 0; i
< moves1
.length
; i
++) {
1362 this.play(moves1
[i
]);
1363 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1365 0.1 * moves1
[i
].eval
+
1366 this.alphabeta(V
.SEARCH_DEPTH
- 1, -maxeval
, maxeval
);
1367 this.undo(moves1
[i
]);
1369 moves1
.sort((a
, b
) => {
1370 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1374 let candidates
= [0];
1375 for (let i
= 1; i
< moves1
.length
&& moves1
[i
].eval
== moves1
[0].eval
; i
++)
1377 return moves1
[candidates
[randInt(candidates
.length
)]];
1380 alphabeta(depth
, alpha
, beta
) {
1381 const maxeval
= V
.INFINITY
;
1382 const color
= this.turn
;
1383 const score
= this.getCurrentScore();
1385 return score
== "1/2" ? 0 : (score
== "1-0" ? 1 : -1) * maxeval
;
1386 if (depth
== 0) return this.evalPosition();
1387 const moves
= this.getAllValidMoves();
1388 let v
= color
== "w" ? -maxeval : maxeval
;
1390 for (let i
= 0; i
< moves
.length
; i
++) {
1391 this.play(moves
[i
]);
1392 v
= Math
.max(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1393 this.undo(moves
[i
]);
1394 alpha
= Math
.max(alpha
, v
);
1395 if (alpha
>= beta
) break; //beta cutoff
1400 for (let i
= 0; i
< moves
.length
; i
++) {
1401 this.play(moves
[i
]);
1402 v
= Math
.min(v
, this.alphabeta(depth
- 1, alpha
, beta
));
1403 this.undo(moves
[i
]);
1404 beta
= Math
.min(beta
, v
);
1405 if (alpha
>= beta
) break; //alpha cutoff
1413 // Just count material for now
1414 for (let i
= 0; i
< V
.size
.x
; i
++) {
1415 for (let j
= 0; j
< V
.size
.y
; j
++) {
1416 if (this.board
[i
][j
] != V
.EMPTY
) {
1417 const sign
= this.getColor(i
, j
) == "w" ? 1 : -1;
1418 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
, j
)];
1425 /////////////////////////
1426 // MOVES + GAME NOTATION
1427 /////////////////////////
1429 // Context: just before move is played, turn hasn't changed
1430 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1432 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
1434 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
1436 // Translate final square
1437 const finalSquare
= V
.CoordsToSquare(move.end
);
1439 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1440 if (piece
== V
.PAWN
) {
1443 if (move.vanish
.length
> move.appear
.length
) {
1445 const startColumn
= V
.CoordToColumn(move.start
.y
);
1446 notation
= startColumn
+ "x" + finalSquare
;
1448 else notation
= finalSquare
;
1449 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
)
1451 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1456 piece
.toUpperCase() +
1457 (move.vanish
.length
> move.appear
.length
? "x" : "") +
1462 static GetUnambiguousNotation(move) {
1463 // Machine-readable format with all the informations about the move
1465 (!!move.start
&& V
.OnBoard(move.start
.x
, move.start
.y
)
1466 ? V
.CoordsToSquare(move.start
)
1469 (!!move.end
&& V
.OnBoard(move.end
.x
, move.end
.y
)
1470 ? V
.CoordsToSquare(move.end
)
1473 (!!move.appear
&& move.appear
.length
> 0
1474 ? move.appear
.map(a
=>
1475 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")
1478 (!!move.vanish
&& move.vanish
.length
> 0
1479 ? move.vanish
.map(a
=>
1480 a
.c
+ a
.p
+ V
.CoordsToSquare({ x: a
.x
, y: a
.y
})).join(".")