+ // Diff current and old board to know which pieces have moved,
+ // and to deduce possible moves at stage 2.
+ const L = this.initfenStack.length;
+ let initBoard = V.GetBoard(this.initfenStack[L-1]);
+ let appeared = [];
+ const c = this.turn;
+ const oppCol = V.GetOppCol(c);
+ for (let i=0; i<8; i++) {
+ for (let j=0; j<8; j++) {
+ if (this.board[i][j] != initBoard[i][j]) {
+ if (this.board[i][j] != V.EMPTY) {
+ const color = this.board[i][j].charAt(0);
+ appeared.push({ c: color, x: i, y: j });
+ // Pawns capture in diagonal => the following fix.
+ // (Other way would be to redefine getPotentialPawnMoves()...)
+ if (color == oppCol) initBoard[i][j] = this.board[i][j];
+ }
+ }
+ }
+ }
+ const saveBoard = this.board;
+ this.board = initBoard;
+ const movesInit = super.getPotentialMovesFrom([x, y]);
+ this.board = saveBoard;
+ const target = appeared.find(a => a.c == oppCol);
+ let movesNow = super.getPotentialMovesFrom([x, y]).filter(m => {
+ return (
+ m.end.x == target.x &&
+ m.end.y == target.y &&
+ movesInit.some(mi => mi.end.x == m.end.x && mi.end.y == m.end.y)
+ );
+ });
+ const passTarget =
+ (x != this.kingPos[c][0] || y != this.kingPos[c][1]) ? c : oppCol;
+ movesNow.push(
+ new Move({
+ start: { x: x, y: y },
+ end: {
+ x: this.kingPos[passTarget][0],
+ y: this.kingPos[passTarget][1]
+ },
+ appear: [],
+ vanish: []
+ })
+ );
+ return movesNow;
+ }
+
+ filterValid(moves) {
+ if (moves.length == 0) return [];
+ if (moves.length == 1 && moves[0].vanish.length == 0) return moves;
+ // filterValid can be called when it's "not our turn":
+ const color = moves.find(m => m.vanish.length > 0).vanish[0].c;
+ return moves.filter(m => {
+ if (m.vanish.length == 0) return true;
+ const piece = m.vanish[0].p;
+ if (piece == V.KING) {
+ this.kingPos[color][0] = m.appear[0].x;
+ this.kingPos[color][1] = m.appear[0].y;
+ }
+ V.PlayOnBoard(this.board, m);
+ let res = !this.underCheck(color);
+ V.UndoOnBoard(this.board, m);
+ if (piece == V.KING) this.kingPos[color] = [m.start.x, m.start.y];
+ return res;
+ });
+ }
+
+ getPossibleMovesFrom([x, y]) {
+ return this.filterValid(this.getPotentialMovesFrom([x, y]));