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 { random
, sample
, shuffle
} from "@/utils/alea";
7 export const PiPo
= class PiPo
//Piece+Position
9 // o: {piece[p], color[c], posX[x], posY[y]}
19 // TODO: for animation, moves should contains "moving" and "fading" maybe...
20 export const Move
= class Move
22 // o: {appear, vanish, [start,] [end,]}
23 // appear,vanish = arrays of PiPo
24 // start,end = coordinates to apply to trigger move visually (think castle)
27 this.appear
= o
.appear
;
28 this.vanish
= o
.vanish
;
29 this.start
= !!o
.start
? o
.start : {x:o
.vanish
[0].x
, y:o
.vanish
[0].y
};
30 this.end
= !!o
.end
? o
.end : {x:o
.appear
[0].x
, y:o
.appear
[0].y
};
34 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
35 export const ChessRules
= class ChessRules
40 static get HasFlags() { return true; } //some variants don't have flags
42 static get HasEnpassant() { return true; } //some variants don't have ep.
47 return b
; //usual pieces in pieces/ folder
50 // Turn "wb" into "B" (for FEN)
53 return b
[0]=='w' ? b
[1].toUpperCase() : b
[1];
56 // Turn "p" into "bp" (for board)
59 return f
.charCodeAt()<=90 ? "w"+f
.toLowerCase() : "b"+f
;
62 // Check if FEN describe a position
65 const fenParsed
= V
.ParseFen(fen
);
67 if (!V
.IsGoodPosition(fenParsed
.position
))
70 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
))
72 // 3) Check moves count
73 if (!fenParsed
.movesCount
|| !(parseInt(fenParsed
.movesCount
) >= 0))
76 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
80 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
)))
87 // Is position part of the FEN a priori correct?
88 static IsGoodPosition(position
)
90 if (position
.length
== 0)
92 const rows
= position
.split("/");
93 if (rows
.length
!= V
.size
.x
)
98 for (let i
=0; i
<row
.length
; i
++)
100 if (V
.PIECES
.includes(row
[i
].toLowerCase()))
104 const num
= parseInt(row
[i
]);
110 if (sumElts
!= V
.size
.y
)
117 static IsGoodTurn(turn
)
119 return ["w","b"].includes(turn
);
123 static IsGoodFlags(flags
)
125 return !!flags
.match(/^[01]{4,4}$/);
128 static IsGoodEnpassant(enpassant
)
130 if (enpassant
!= "-")
132 const ep
= V
.SquareToCoords(fenParsed
.enpassant
);
133 if (isNaN(ep
.x
) || !V
.OnBoard(ep
))
139 // 3 --> d (column number to letter)
140 static CoordToColumn(colnum
)
142 return String
.fromCharCode(97 + colnum
);
145 // d --> 3 (column letter to number)
146 static ColumnToCoord(column
)
148 return column
.charCodeAt(0) - 97;
152 static SquareToCoords(sq
)
155 // NOTE: column is always one char => max 26 columns
156 // row is counted from black side => subtraction
157 x: V
.size
.x
- parseInt(sq
.substr(1)),
158 y: sq
[0].charCodeAt() - 97
163 static CoordsToSquare(coords
)
165 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
168 // Aggregates flags into one object
171 return this.castleFlags
;
175 disaggregateFlags(flags
)
177 this.castleFlags
= flags
;
180 // En-passant square, if any
181 getEpSquare(moveOrSquare
)
185 if (typeof moveOrSquare
=== "string")
187 const square
= moveOrSquare
;
190 return V
.SquareToCoords(square
);
192 // Argument is a move:
193 const move = moveOrSquare
;
194 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
195 // TODO: next conditions are first for Atomic, and third for Checkered
196 if (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
&& ["w","b"].includes(move.appear
[0].c
) && Math
.abs(sx
- ex
) == 2)
203 return undefined; //default
206 // Can thing on square1 take thing on square2
207 canTake([x1
,y1
], [x2
,y2
])
209 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
212 // Is (x,y) on the chessboard?
215 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
218 // Used in interface: 'side' arg == player color
219 canIplay(side
, [x
,y
])
221 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
224 // On which squares is color under check ? (for interface)
225 getCheckSquares(color
)
227 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)])
228 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
235 // Setup the initial random (assymetric) position
236 static GenRandInitFen()
238 let pieces
= { "w": new Array(8), "b": new Array(8) };
239 // Shuffle pieces on first and last rank
240 for (let c
of ["w","b"])
242 let positions
= ArrayFun
.range(8);
244 // Get random squares for bishops
245 let randIndex
= 2 * random(4);
246 const bishop1Pos
= positions
[randIndex
];
247 // The second bishop must be on a square of different color
248 let randIndex_tmp
= 2 * random(4) + 1;
249 const bishop2Pos
= positions
[randIndex_tmp
];
250 // Remove chosen squares
251 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
252 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
254 // Get random squares for knights
255 randIndex
= random(6);
256 const knight1Pos
= positions
[randIndex
];
257 positions
.splice(randIndex
, 1);
258 randIndex
= random(5);
259 const knight2Pos
= positions
[randIndex
];
260 positions
.splice(randIndex
, 1);
262 // Get random square for queen
263 randIndex
= random(4);
264 const queenPos
= positions
[randIndex
];
265 positions
.splice(randIndex
, 1);
267 // Rooks and king positions are now fixed,
268 // because of the ordering rook-king-rook
269 const rook1Pos
= positions
[0];
270 const kingPos
= positions
[1];
271 const rook2Pos
= positions
[2];
273 // Finally put the shuffled pieces in the board array
274 pieces
[c
][rook1Pos
] = 'r';
275 pieces
[c
][knight1Pos
] = 'n';
276 pieces
[c
][bishop1Pos
] = 'b';
277 pieces
[c
][queenPos
] = 'q';
278 pieces
[c
][kingPos
] = 'k';
279 pieces
[c
][bishop2Pos
] = 'b';
280 pieces
[c
][knight2Pos
] = 'n';
281 pieces
[c
][rook2Pos
] = 'r';
283 return pieces
["b"].join("") +
284 "/pppppppp/8/8/8/8/PPPPPPPP/" +
285 pieces
["w"].join("").toUpperCase() +
286 " w 0 1111 -"; //add turn + flags + enpassant
289 // "Parse" FEN: just return untransformed string data
292 const fenParts
= fen
.split(" ");
295 position: fenParts
[0],
297 movesCount: fenParts
[2],
301 Object
.assign(res
, {flags: fenParts
[nextIdx
++]});
303 Object
.assign(res
, {enpassant: fenParts
[nextIdx
]});
307 // Return current fen (game state)
310 return this.getBaseFen() + " " +
311 this.getTurnFen() + " " + this.movesCount
+
312 (V
.HasFlags
? (" " + this.getFlagsFen()) : "") +
313 (V
.HasEnpassant
? (" " + this.getEnpassantFen()) : "");
316 // Position part of the FEN string
320 for (let i
=0; i
<V
.size
.x
; i
++)
323 for (let j
=0; j
<V
.size
.y
; j
++)
325 if (this.board
[i
][j
] == V
.EMPTY
)
331 // Add empty squares in-between
332 position
+= emptyCount
;
335 position
+= V
.board2fen(this.board
[i
][j
]);
341 position
+= emptyCount
;
343 if (i
< V
.size
.x
- 1)
344 position
+= "/"; //separate rows
354 // Flags part of the FEN string
358 // Add castling flags
359 for (let i
of ['w','b'])
361 for (let j
=0; j
<2; j
++)
362 flags
+= (this.castleFlags
[i
][j
] ? '1' : '0');
367 // Enpassant part of the FEN string
370 const L
= this.epSquares
.length
;
371 if (!this.epSquares
[L
-1])
372 return "-"; //no en-passant
373 return V
.CoordsToSquare(this.epSquares
[L
-1]);
376 // Turn position fen into double array ["wb","wp","bk",...]
377 static GetBoard(position
)
379 const rows
= position
.split("/");
380 let board
= ArrayFun
.init(V
.size
.x
, V
.size
.y
, "");
381 for (let i
=0; i
<rows
.length
; i
++)
384 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
386 const character
= rows
[i
][indexInRow
];
387 const num
= parseInt(character
);
389 j
+= num
; //just shift j
390 else //something at position i,j
391 board
[i
][j
++] = V
.fen2board(character
);
397 // Extract (relevant) flags from fen
400 // white a-castle, h-castle, black a-castle, h-castle
401 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
404 for (let i
=0; i
<4; i
++)
405 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
411 // Fen string fully describes the game state
414 const fenParsed
= V
.ParseFen(fen
);
415 this.board
= V
.GetBoard(fenParsed
.position
);
416 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
417 this.movesCount
= parseInt(fenParsed
.movesCount
);
418 this.setOtherVariables(fen
);
421 // Scan board for kings and rooks positions
424 this.INIT_COL_KING
= {'w':-1, 'b':-1};
425 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
426 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
427 const fenRows
= V
.ParseFen(fen
).position
.split("/");
428 for (let i
=0; i
<fenRows
.length
; i
++)
430 let k
= 0; //column index on board
431 for (let j
=0; j
<fenRows
[i
].length
; j
++)
433 switch (fenRows
[i
].charAt(j
))
436 this.kingPos
['b'] = [i
,k
];
437 this.INIT_COL_KING
['b'] = k
;
440 this.kingPos
['w'] = [i
,k
];
441 this.INIT_COL_KING
['w'] = k
;
444 if (this.INIT_COL_ROOK
['b'][0] < 0)
445 this.INIT_COL_ROOK
['b'][0] = k
;
447 this.INIT_COL_ROOK
['b'][1] = k
;
450 if (this.INIT_COL_ROOK
['w'][0] < 0)
451 this.INIT_COL_ROOK
['w'][0] = k
;
453 this.INIT_COL_ROOK
['w'][1] = k
;
456 const num
= parseInt(fenRows
[i
].charAt(j
));
465 // Some additional variables from FEN (variant dependant)
466 setOtherVariables(fen
)
468 // Set flags and enpassant:
469 const parsedFen
= V
.ParseFen(fen
);
471 this.setFlags(parsedFen
.flags
);
474 const epSq
= parsedFen
.enpassant
!= "-"
475 ? V
.SquareToCoords(parsedFen
.enpassant
)
477 this.epSquares
= [ epSq
];
479 // Search for king and rooks positions:
480 this.scanKingsRooks(fen
);
483 /////////////////////
491 // Color of thing on suqare (i,j). 'undefined' if square is empty
494 return this.board
[i
][j
].charAt(0);
497 // Piece type on square (i,j). 'undefined' if square is empty
500 return this.board
[i
][j
].charAt(1);
503 // Get opponent color
504 static GetOppCol(color
)
506 return (color
=="w" ? "b" : "w");
509 // Get next color (for compatibility with 3 and 4 players games)
510 static GetNextCol(color
)
512 return V
.GetOppCol(color
);
515 // Pieces codes (for a clearer code)
516 static get PAWN() { return 'p'; }
517 static get ROOK() { return 'r'; }
518 static get KNIGHT() { return 'n'; }
519 static get BISHOP() { return 'b'; }
520 static get QUEEN() { return 'q'; }
521 static get KING() { return 'k'; }
526 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
530 static get EMPTY() { return ""; }
532 // Some pieces movements
536 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
537 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
538 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
545 // All possible moves from selected square (assumption: color is OK)
546 getPotentialMovesFrom([x
,y
])
548 switch (this.getPiece(x
,y
))
551 return this.getPotentialPawnMoves([x
,y
]);
553 return this.getPotentialRookMoves([x
,y
]);
555 return this.getPotentialKnightMoves([x
,y
]);
557 return this.getPotentialBishopMoves([x
,y
]);
559 return this.getPotentialQueenMoves([x
,y
]);
561 return this.getPotentialKingMoves([x
,y
]);
565 // Build a regular move from its initial and destination squares.
566 // tr: transformation
567 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
574 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
575 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
582 c: this.getColor(sx
,sy
),
583 p: this.getPiece(sx
,sy
)
588 // The opponent piece disappears if we take it
589 if (this.board
[ex
][ey
] != V
.EMPTY
)
595 c: this.getColor(ex
,ey
),
596 p: this.getPiece(ex
,ey
)
603 // Generic method to find possible moves of non-pawn pieces:
604 // "sliding or jumping"
605 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
607 const color
= this.getColor(x
,y
);
610 for (let step
of steps
)
614 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
616 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
617 if (oneStep
!== undefined)
622 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
623 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
628 // What are the pawn moves from square x,y ?
629 getPotentialPawnMoves([x
,y
])
631 const color
= this.turn
;
633 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
634 const shiftX
= (color
== "w" ? -1 : 1);
635 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
636 const startRank
= (color
== "w" ? sizeX
-2 : 1);
637 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
638 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
640 // NOTE: next condition is generally true (no pawn on last rank)
641 if (x
+shiftX
>= 0 && x
+shiftX
< sizeX
)
643 const finalPieces
= x
+ shiftX
== lastRank
644 ? [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
]
646 // One square forward
647 if (this.board
[x
+shiftX
][y
] == V
.EMPTY
)
649 for (let piece
of finalPieces
)
651 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
],
652 {c:pawnColor
,p:piece
}));
654 // Next condition because pawns on 1st rank can generally jump
655 if ([startRank
,firstRank
].includes(x
)
656 && this.board
[x
+2*shiftX
][y
] == V
.EMPTY
)
659 moves
.push(this.getBasicMove([x
,y
], [x
+2*shiftX
,y
]));
663 for (let shiftY
of [-1,1])
665 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
666 && this.board
[x
+shiftX
][y
+shiftY
] != V
.EMPTY
667 && this.canTake([x
,y
], [x
+shiftX
,y
+shiftY
]))
669 for (let piece
of finalPieces
)
671 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
+shiftY
],
672 {c:pawnColor
,p:piece
}));
681 const Lep
= this.epSquares
.length
;
682 const epSquare
= this.epSquares
[Lep
-1]; //always at least one element
683 if (!!epSquare
&& epSquare
.x
== x
+shiftX
&& Math
.abs(epSquare
.y
- y
) == 1)
685 let enpassantMove
= this.getBasicMove([x
,y
], [epSquare
.x
,epSquare
.y
]);
686 enpassantMove
.vanish
.push({
690 c: this.getColor(x
,epSquare
.y
)
692 moves
.push(enpassantMove
);
699 // What are the rook moves from square x,y ?
700 getPotentialRookMoves(sq
)
702 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
705 // What are the knight moves from square x,y ?
706 getPotentialKnightMoves(sq
)
708 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
711 // What are the bishop moves from square x,y ?
712 getPotentialBishopMoves(sq
)
714 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
717 // What are the queen moves from square x,y ?
718 getPotentialQueenMoves(sq
)
720 return this.getSlideNJumpMoves(sq
,
721 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
724 // What are the king moves from square x,y ?
725 getPotentialKingMoves(sq
)
727 // Initialize with normal moves
728 let moves
= this.getSlideNJumpMoves(sq
,
729 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
730 return moves
.concat(this.getCastleMoves(sq
));
733 getCastleMoves([x
,y
])
735 const c
= this.getColor(x
,y
);
736 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
737 return []; //x isn't first rank, or king has moved (shortcut)
740 const oppCol
= V
.GetOppCol(c
);
743 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
745 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
747 if (!this.castleFlags
[c
][castleSide
])
749 // If this code is reached, rooks and king are on initial position
751 // Nothing on the path of the king ?
752 // (And no checks; OK also if y==finalSquare)
753 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
754 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
756 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
757 // NOTE: next check is enough, because of chessboard constraints
758 (this.getColor(x
,i
) != c
759 || ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
761 continue castlingCheck
;
765 // Nothing on the path to the rook?
766 step
= castleSide
== 0 ? -1 : 1;
767 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
769 if (this.board
[x
][i
] != V
.EMPTY
)
770 continue castlingCheck
;
772 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
774 // Nothing on final squares, except maybe king and castling rook?
777 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
778 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
779 finalSquares
[castleSide
][i
] != rookPos
)
781 continue castlingCheck
;
785 // If this code is reached, castle is valid
786 moves
.push( new Move({
788 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
789 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
791 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
792 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
793 end: Math
.abs(y
- rookPos
) <= 2
795 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
805 // For the interface: possible moves for the current turn from square sq
806 getPossibleMovesFrom(sq
)
808 return this.filterValid( this.getPotentialMovesFrom(sq
) );
811 // TODO: promotions (into R,B,N,Q) should be filtered only once
814 if (moves
.length
== 0)
816 const color
= this.turn
;
817 return moves
.filter(m
=> {
819 const res
= !this.underCheck(color
);
825 // Search for all valid moves considering current turn
826 // (for engine and game end)
829 const color
= this.turn
;
830 const oppCol
= V
.GetOppCol(color
);
831 let potentialMoves
= [];
832 for (let i
=0; i
<V
.size
.x
; i
++)
834 for (let j
=0; j
<V
.size
.y
; j
++)
836 // Next condition "!= oppCol" to work with checkered variant
837 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
839 Array
.prototype.push
.apply(potentialMoves
,
840 this.getPotentialMovesFrom([i
,j
]));
844 return this.filterValid(potentialMoves
);
847 // Stop at the first move found
850 const color
= this.turn
;
851 const oppCol
= V
.GetOppCol(color
);
852 for (let i
=0; i
<V
.size
.x
; i
++)
854 for (let j
=0; j
<V
.size
.y
; j
++)
856 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
858 const moves
= this.getPotentialMovesFrom([i
,j
]);
859 if (moves
.length
> 0)
861 for (let k
=0; k
<moves
.length
; k
++)
863 if (this.filterValid([moves
[k
]]).length
> 0)
873 // Check if pieces of color in 'colors' are attacking (king) on square x,y
874 isAttacked(sq
, colors
)
876 return (this.isAttackedByPawn(sq
, colors
)
877 || this.isAttackedByRook(sq
, colors
)
878 || this.isAttackedByKnight(sq
, colors
)
879 || this.isAttackedByBishop(sq
, colors
)
880 || this.isAttackedByQueen(sq
, colors
)
881 || this.isAttackedByKing(sq
, colors
));
884 // Is square x,y attacked by 'colors' pawns ?
885 isAttackedByPawn([x
,y
], colors
)
887 for (let c
of colors
)
889 let pawnShift
= (c
=="w" ? 1 : -1);
890 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
892 for (let i
of [-1,1])
894 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
895 && this.getColor(x
+pawnShift
,y
+i
)==c
)
905 // Is square x,y attacked by 'colors' rooks ?
906 isAttackedByRook(sq
, colors
)
908 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
911 // Is square x,y attacked by 'colors' knights ?
912 isAttackedByKnight(sq
, colors
)
914 return this.isAttackedBySlideNJump(sq
, colors
,
915 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
918 // Is square x,y attacked by 'colors' bishops ?
919 isAttackedByBishop(sq
, colors
)
921 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
924 // Is square x,y attacked by 'colors' queens ?
925 isAttackedByQueen(sq
, colors
)
927 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
928 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
931 // Is square x,y attacked by 'colors' king(s) ?
932 isAttackedByKing(sq
, colors
)
934 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
935 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
938 // Generic method for non-pawn pieces ("sliding or jumping"):
939 // is x,y attacked by a piece of color in array 'colors' ?
940 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
942 for (let step
of steps
)
944 let rx
= x
+step
[0], ry
= y
+step
[1];
945 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
950 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
951 && colors
.includes(this.getColor(rx
,ry
)))
959 // Is color under check after his move ?
962 return this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]);
968 // Apply a move on board
969 static PlayOnBoard(board
, move)
971 for (let psq
of move.vanish
)
972 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
973 for (let psq
of move.appear
)
974 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
976 // Un-apply the played move
977 static UndoOnBoard(board
, move)
979 for (let psq
of move.appear
)
980 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
981 for (let psq
of move.vanish
)
982 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
985 // After move is played, update variables + flags
986 updateVariables(move)
988 let piece
= undefined;
990 if (move.vanish
.length
>= 1)
992 // Usual case, something is moved
993 piece
= move.vanish
[0].p
;
994 c
= move.vanish
[0].c
;
998 // Crazyhouse-like variants
999 piece
= move.appear
[0].p
;
1000 c
= move.appear
[0].c
;
1002 if (c
== "c") //if (!["w","b"].includes(c))
1004 // 'c = move.vanish[0].c' doesn't work for Checkered
1005 c
= V
.GetOppCol(this.turn
);
1007 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
1009 // Update king position + flags
1010 if (piece
== V
.KING
&& move.appear
.length
> 0)
1012 this.kingPos
[c
][0] = move.appear
[0].x
;
1013 this.kingPos
[c
][1] = move.appear
[0].y
;
1015 this.castleFlags
[c
] = [false,false];
1020 // Update castling flags if rooks are moved
1021 const oppCol
= V
.GetOppCol(c
);
1022 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
1023 if (move.start
.x
== firstRank
//our rook moves?
1024 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
1026 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
1027 this.castleFlags
[c
][flagIdx
] = false;
1029 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
1030 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
1032 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
1033 this.castleFlags
[oppCol
][flagIdx
] = false;
1038 // After move is undo-ed *and flags resetted*, un-update other variables
1039 // TODO: more symmetry, by storing flags increment in move (?!)
1040 unupdateVariables(move)
1042 // (Potentially) Reset king position
1043 const c
= this.getColor(move.start
.x
,move.start
.y
);
1044 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
1045 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1051 // if (!this.states) this.states = [];
1052 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1053 // this.states.push(stateFen);
1056 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1058 this.epSquares
.push( this.getEpSquare(move) );
1060 move.color
= this.turn
; //for interface
1061 V
.PlayOnBoard(this.board
, move);
1062 this.turn
= V
.GetOppCol(this.turn
);
1064 this.updateVariables(move);
1070 this.epSquares
.pop();
1072 this.disaggregateFlags(JSON
.parse(move.flags
));
1073 V
.UndoOnBoard(this.board
, move);
1074 this.turn
= V
.GetOppCol(this.turn
);
1076 this.unupdateVariables(move);
1079 // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1080 // if (stateFen != this.states[this.states.length-1]) debugger;
1081 // this.states.pop();
1087 // What is the score ? (Interesting if game is over)
1090 if (this.atLeastOneMove()) // game not over
1094 const color
= this.turn
;
1095 // No valid move: stalemate or checkmate?
1096 if (!this.isAttacked(this.kingPos
[color
], [V
.GetOppCol(color
)]))
1099 return (color
== "w" ? "0-1" : "1-0");
1118 // "Checkmate" (unreachable eval)
1119 static get INFINITY() { return 9999; }
1121 // At this value or above, the game is over
1122 static get THRESHOLD_MATE() { return V
.INFINITY
; }
1124 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1125 static get SEARCH_DEPTH() { return 3; }
1127 // Assumption: at least one legal move
1128 // NOTE: works also for extinction chess because depth is 3...
1131 const maxeval
= V
.INFINITY
;
1132 const color
= this.turn
;
1133 // Some variants may show a bigger moves list to the human (Switching),
1134 // thus the argument "computer" below (which is generally ignored)
1135 let moves1
= this.getAllValidMoves("computer");
1137 // Can I mate in 1 ? (for Magnetic & Extinction)
1138 for (let i
of shuffle(ArrayFun
.range(moves1
.length
)))
1140 this.play(moves1
[i
]);
1141 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
1144 const score
= this.getCurrentScore();
1145 if (["1-0","0-1"].includes(score
))
1148 this.undo(moves1
[i
]);
1153 // Rank moves using a min-max at depth 2
1154 for (let i
=0; i
<moves1
.length
; i
++)
1156 // Initial self evaluation is very low: "I'm checkmated"
1157 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
;
1158 this.play(moves1
[i
]);
1159 const score1
= this.getCurrentScore();
1160 let eval2
= undefined;
1163 // Initial enemy evaluation is very low too, for him
1164 eval2
= (color
=="w" ? 1 : -1) * maxeval
;
1165 // Second half-move:
1166 let moves2
= this.getAllValidMoves("computer");
1167 for (let j
=0; j
<moves2
.length
; j
++)
1169 this.play(moves2
[j
]);
1170 const score2
= this.getCurrentScore();
1171 const evalPos
= score2
== "*"
1172 ? this.evalPosition()
1173 : (score2
=="1/2" ? 0 : (score2
=="1-0" ? 1 : -1) * maxeval
);
1174 if ((color
== "w" && evalPos
< eval2
)
1175 || (color
=="b" && evalPos
> eval2
))
1179 this.undo(moves2
[j
]);
1183 eval2
= (score1
=="1/2" ? 0 : (score1
=="1-0" ? 1 : -1) * maxeval
);
1184 if ((color
=="w" && eval2
> moves1
[i
].eval
)
1185 || (color
=="b" && eval2
< moves1
[i
].eval
))
1187 moves1
[i
].eval
= eval2
;
1189 this.undo(moves1
[i
]);
1191 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1193 let candidates
= [0]; //indices of candidates moves
1194 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1196 let currentBest
= moves1
[sample(candidates
)];
1198 // From here, depth >= 3: may take a while, so we control time
1199 const timeStart
= Date
.now();
1201 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1202 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
1204 for (let i
=0; i
<moves1
.length
; i
++)
1206 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
1207 return currentBest
; //depth 2 at least
1208 this.play(moves1
[i
]);
1209 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1210 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
1211 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
1212 this.undo(moves1
[i
]);
1214 moves1
.sort( (a
,b
) => {
1215 return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1219 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1222 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1224 return moves1
[sample(candidates
)];
1227 alphabeta(depth
, alpha
, beta
)
1229 const maxeval
= V
.INFINITY
;
1230 const color
= this.turn
;
1231 const score
= this.getCurrentScore();
1233 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1235 return this.evalPosition();
1236 const moves
= this.getAllValidMoves("computer");
1237 let v
= color
=="w" ? -maxeval : maxeval
;
1240 for (let i
=0; i
<moves
.length
; i
++)
1242 this.play(moves
[i
]);
1243 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1244 this.undo(moves
[i
]);
1245 alpha
= Math
.max(alpha
, v
);
1247 break; //beta cutoff
1252 for (let i
=0; i
<moves
.length
; i
++)
1254 this.play(moves
[i
]);
1255 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1256 this.undo(moves
[i
]);
1257 beta
= Math
.min(beta
, v
);
1259 break; //alpha cutoff
1268 // Just count material for now
1269 for (let i
=0; i
<V
.size
.x
; i
++)
1271 for (let j
=0; j
<V
.size
.y
; j
++)
1273 if (this.board
[i
][j
] != V
.EMPTY
)
1275 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1276 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1283 /////////////////////////
1284 // MOVES + GAME NOTATION
1285 /////////////////////////
1287 // Context: just before move is played, turn hasn't changed
1288 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1291 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1292 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1294 // Translate final square
1295 const finalSquare
= V
.CoordsToSquare(move.end
);
1297 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1298 if (piece
== V
.PAWN
)
1302 if (move.vanish
.length
> move.appear
.length
)
1305 const startColumn
= V
.CoordToColumn(move.start
.y
);
1306 notation
= startColumn
+ "x" + finalSquare
;
1309 notation
= finalSquare
;
1310 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
) //promotion
1311 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1318 return piece
.toUpperCase() +
1319 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;