feat: get FEN of current position

This commit is contained in:
Cozma Rares
2023-04-07 00:18:06 +03:00
parent 35361a5835
commit e154d9fdb2
+59 -9
View File
@@ -38,14 +38,14 @@ export type Piece = {
// prettier-ignore
export const SQUARES = Object.freeze([
'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1',
'a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2',
'a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3',
'a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4',
'a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5',
'a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6',
'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7',
'a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8',
'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7',
'a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6',
'a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5',
'a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4',
'a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3',
'a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2',
'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1',
] as const);
function isSquareValid(string: string): boolean {
@@ -362,12 +362,62 @@ export class Chess {
this._fullMoves = parseInt(fields[5]);
}
getFEN() {
let position = "";
let emptySquares = 0;
for (let i = 0; i < 64; i++) {
if (i % 8 == 0) {
if (emptySquares) position += `${emptySquares}`;
position += "/";
emptySquares = 0;
}
const piece = this.getPiece(i);
if (piece == null) {
emptySquares++;
continue;
}
if (emptySquares) position += `${emptySquares}`;
position +=
piece.color == COLOR.WHITE
? piece.type.toUpperCase()
: piece.type.toLowerCase();
emptySquares = 0;
}
let castling = "";
if (this._castling.w & MOVE_FLAGS.K_CASTLE) castling += "K";
if (this._castling.w & MOVE_FLAGS.Q_CASTLE) castling += "Q";
if (this._castling.b & MOVE_FLAGS.K_CASTLE) castling += "k";
if (this._castling.b & MOVE_FLAGS.Q_CASTLE) castling += "q";
return [
position.substring(1),
this._turn,
castling,
this._enPassant,
this._halfMoves,
this._fullMoves,
].join(" ");
}
getPiece(square: number) {
return this._board[square];
}
getMoves() {}
getMovesForSquare(square: Square) {}
getFEN() {}
makeMove() {}
isSquareAttacked() {}