- ////////////
- // 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);
- let bishop1Pos = positions[randIndex];
- // The second bishop must be on a square of different color
- let randIndex_tmp = 2 * _.random(3) + 1;
- let 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);
- let knight1Pos = positions[randIndex];
- positions.splice(randIndex, 1);
- randIndex = _.random(4);
- let knight2Pos = positions[randIndex];
- positions.splice(randIndex, 1);
-
- // Get random square for queen
- randIndex = _.random(3);
- let queenPos = positions[randIndex];
- positions.splice(randIndex, 1);
-
- // Rooks and king positions are now fixed, because of the ordering rook-king-rook
- let rook1Pos = positions[0];
- let kingPos = positions[1];
- let 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() +
- " 1111"; //add flags
- }
-
- // Return current fen according to pieces+colors state
- getFen()
- {
- return this.getBaseFen() + " " + this.getFlagsFen() + " " + this.turn;
- }
-
- // Position part of the FEN string
- getBaseFen()
- {
- let fen = "";
- 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
- fen += emptyCount;
- emptyCount = 0;
- }
- fen += V.board2fen(this.board[i][j]);
- }
- }
- if (emptyCount > 0)
- {
- // "Flush remainder"
- fen += emptyCount;
- }
- if (i < V.size.x - 1)
- fen += "/"; //separate rows
- }
- return fen;
- }
-
- // Flags part of the FEN string
- getFlagsFen()
- {
- let fen = "";
- // Add castling flags
- for (let i of ['w','b'])
- {
- for (let j=0; j<2; j++)
- fen += (this.castleFlags[i][j] ? '1' : '0');
- }
- return fen;
- }