+ // Check if FEN describe a position
+ static IsGoodFen(fen)
+ {
+ const fenParsed = V.ParseFen(fen);
+ // 1) Check position
+ if (!V.IsGoodPosition(fenParsed.position))
+ return false;
+ // 2) Check turn
+ if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn))
+ return false;
+ // 3) Check moves count
+ if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
+ return false;
+ // 4) Check flags
+ if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
+ return false;
+ // 5) Check enpassant
+ if (V.HasEnpassant &&
+ (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant)))
+ {
+ return false;
+ }
+ return true;
+ }
+
+ // Is position part of the FEN a priori correct?
+ static IsGoodPosition(position)
+ {
+ if (position.length == 0)
+ return false;
+ const rows = position.split("/");
+ if (rows.length != V.size.x)
+ return false;
+ for (let row of rows)
+ {
+ let sumElts = 0;
+ for (let i=0; i<row.length; i++)
+ {
+ if (V.PIECES.includes(row[i].toLowerCase()))
+ sumElts++;
+ else
+ {
+ const num = parseInt(row[i]);
+ if (isNaN(num))
+ return false;
+ sumElts += num;
+ }
+ }
+ if (sumElts != V.size.y)
+ return false;
+ }
+ return true;
+ }
+
+ // For FEN checking
+ static IsGoodTurn(turn)
+ {
+ return ["w","b"].includes(turn);
+ }
+
+ // For FEN checking
+ static IsGoodFlags(flags)
+ {
+ return !!flags.match(/^[01]{4,4}$/);
+ }
+
+ static IsGoodEnpassant(enpassant)
+ {
+ if (enpassant != "-")
+ {
+ const ep = V.SquareToCoords(fenParsed.enpassant);
+ if (isNaN(ep.x) || !V.OnBoard(ep))
+ return false;
+ }
+ return true;
+ }
+
+ // 3 --> d (column number to letter)
+ static CoordToColumn(colnum)
+ {
+ return String.fromCharCode(97 + colnum);
+ }
+
+ // d --> 3 (column letter to number)
+ static ColumnToCoord(column)
+ {
+ return column.charCodeAt(0) - 97;
+ }
+
+ // a4 --> {x:3,y:0}
+ static SquareToCoords(sq)
+ {
+ return {
+ // NOTE: column is always one char => max 26 columns
+ // row is counted from black side => subtraction
+ x: V.size.x - parseInt(sq.substr(1)),
+ y: sq[0].charCodeAt() - 97
+ };
+ }
+
+ // {x:0,y:4} --> e8
+ static CoordsToSquare(coords)
+ {
+ return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
+ }
+
+ // Aggregates flags into one object
+ aggregateFlags()
+ {
+ return this.castleFlags;
+ }
+
+ // Reverse operation
+ disaggregateFlags(flags)
+ {
+ this.castleFlags = flags;
+ }
+
+ // En-passant square, if any
+ getEpSquare(moveOrSquare)
+ {
+ if (!moveOrSquare)
+ return undefined;
+ if (typeof moveOrSquare === "string")
+ {
+ const square = moveOrSquare;
+ if (square == "-")
+ return undefined;
+ return V.SquareToCoords(square);
+ }
+ // Argument is a move:
+ const move = moveOrSquare;
+ const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
+ // TODO: next conditions are first for Atomic, and third for Checkered
+ if (move.appear.length > 0 && move.appear[0].p == V.PAWN && ["w","b"].includes(move.appear[0].c) && Math.abs(sx - ex) == 2)
+ {
+ return {
+ x: (sx + ex)/2,
+ y: sy
+ };
+ }
+ return undefined; //default
+ }
+
+ // Can thing on square1 take thing on square2
+ canTake([x1,y1], [x2,y2])
+ {
+ return this.getColor(x1,y1) !== this.getColor(x2,y2);
+ }
+
+ // Is (x,y) on the chessboard?
+ static OnBoard(x,y)
+ {
+ return (x>=0 && x<V.size.x && y>=0 && y<V.size.y);
+ }
+
+ // Used in interface: 'side' arg == player color
+ canIplay(side, [x,y])
+ {
+ return (this.turn == side && this.getColor(x,y) == side);
+ }
+
+ // On which squares is color under check ? (for interface)
+ getCheckSquares(color)
+ {
+ return this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
+ ? [JSON.parse(JSON.stringify(this.kingPos[color]))] //need to duplicate!
+ : [];
+ }
+
+ /////////////
+ // FEN UTILS
+
+ // Setup the initial random (assymetric) position
+ static GenRandInitFen()
+ {
+ let pieces = { "w": new Array(8), "b": new Array(8) };
+ // Shuffle pieces on first and last rank
+ for (let c of ["w","b"])
+ {
+ let positions = _.range(8);
+
+ // Get random squares for bishops
+ let randIndex = 2 * _.random(3);
+ const bishop1Pos = positions[randIndex];
+ // The second bishop must be on a square of different color
+ let randIndex_tmp = 2 * _.random(3) + 1;
+ const bishop2Pos = positions[randIndex_tmp];
+ // Remove chosen squares
+ positions.splice(Math.max(randIndex,randIndex_tmp), 1);
+ positions.splice(Math.min(randIndex,randIndex_tmp), 1);
+
+ // Get random squares for knights
+ randIndex = _.random(5);
+ const knight1Pos = positions[randIndex];
+ positions.splice(randIndex, 1);
+ randIndex = _.random(4);
+ const knight2Pos = positions[randIndex];
+ positions.splice(randIndex, 1);
+
+ // Get random square for queen
+ randIndex = _.random(3);
+ const queenPos = positions[randIndex];
+ positions.splice(randIndex, 1);
+
+ // Rooks and king positions are now fixed,
+ // because of the ordering rook-king-rook
+ const rook1Pos = positions[0];
+ const kingPos = positions[1];
+ const rook2Pos = positions[2];
+
+ // Finally put the shuffled pieces in the board array
+ pieces[c][rook1Pos] = 'r';
+ pieces[c][knight1Pos] = 'n';
+ pieces[c][bishop1Pos] = 'b';
+ pieces[c][queenPos] = 'q';
+ pieces[c][kingPos] = 'k';
+ pieces[c][bishop2Pos] = 'b';
+ pieces[c][knight2Pos] = 'n';
+ pieces[c][rook2Pos] = 'r';
+ }
+ return pieces["b"].join("") +
+ "/pppppppp/8/8/8/8/PPPPPPPP/" +
+ pieces["w"].join("").toUpperCase() +
+ " w 1111 -"; //add turn + flags + enpassant
+ }
+
+ // "Parse" FEN: just return untransformed string data
+ static ParseFen(fen)
+ {
+ const fenParts = fen.split(" ");
+ let res =
+ {
+ position: fenParts[0],
+ turn: fenParts[1],
+ movesCount: fenParts[2],
+ };
+ let nextIdx = 3;
+ if (V.HasFlags)
+ Object.assign(res, {flags: fenParts[nextIdx++]});
+ if (V.HasEnpassant)
+ Object.assign(res, {enpassant: fenParts[nextIdx]});
+ return res;
+ }
+
+ // Return current fen (game state)
+ getFen()
+ {
+ return this.getBaseFen() + " " +
+ this.getTurnFen() + " " + this.movesCount +
+ (V.HasFlags ? (" " + this.getFlagsFen()) : "") +
+ (V.HasEnpassant ? (" " + this.getEnpassantFen()) : "");
+ }
+
+ // Position part of the FEN string
+ getBaseFen()
+ {
+ let position = "";
+ for (let i=0; i<V.size.x; i++)
+ {
+ let emptyCount = 0;
+ for (let j=0; j<V.size.y; j++)
+ {
+ if (this.board[i][j] == V.EMPTY)
+ emptyCount++;
+ else
+ {
+ if (emptyCount > 0)
+ {
+ // Add empty squares in-between
+ position += emptyCount;
+ emptyCount = 0;
+ }
+ position += V.board2fen(this.board[i][j]);
+ }
+ }
+ if (emptyCount > 0)
+ {
+ // "Flush remainder"
+ position += emptyCount;
+ }
+ if (i < V.size.x - 1)
+ position += "/"; //separate rows
+ }
+ return position;
+ }
+
+ getTurnFen()
+ {
+ return this.turn;
+ }
+
+ // Flags part of the FEN string
+ getFlagsFen()
+ {
+ let flags = "";
+ // Add castling flags
+ for (let i of ['w','b'])
+ {
+ for (let j=0; j<2; j++)
+ flags += (this.castleFlags[i][j] ? '1' : '0');
+ }
+ return flags;
+ }
+
+ // Enpassant part of the FEN string
+ getEnpassantFen()
+ {
+ const L = this.epSquares.length;
+ if (!this.epSquares[L-1])
+ return "-"; //no en-passant
+ return V.CoordsToSquare(this.epSquares[L-1]);
+ }
+
+ // Turn position fen into double array ["wb","wp","bk",...]
+ static GetBoard(position)
+ {
+ const rows = position.split("/");
+ let board = doubleArray(V.size.x, V.size.y, "");
+ for (let i=0; i<rows.length; i++)
+ {
+ let j = 0;
+ for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
+ {
+ const character = rows[i][indexInRow];
+ const num = parseInt(character);
+ if (!isNaN(num))
+ j += num; //just shift j
+ else //something at position i,j
+ board[i][j++] = V.fen2board(character);
+ }
+ }
+ return board;
+ }
+
+ // Extract (relevant) flags from fen
+ setFlags(fenflags)
+ {
+ // white a-castle, h-castle, black a-castle, h-castle
+ this.castleFlags = {'w': [true,true], 'b': [true,true]};
+ if (!fenflags)
+ return;
+ for (let i=0; i<4; i++)
+ this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (fenflags.charAt(i) == '1');
+ }
+
+ //////////////////