function getBoardFEN() {
let board = Array(8).fill().map(() => Array(8).fill(''));
const pieces = document.querySelectorAll('.piece');
pieces.forEach(piece => {
try {
const classes = piece.className.split(' ');
// Find the piece type (two-character code like wp, br, wk, etc.)
const pieceType = classes.find(cls =>
cls.length === 2 &&
(cls[0] === 'w' || cls[0] === 'b') &&
'prnbqkPRNBQK'.includes(cls[1])
);
const squareClass = classes.find(cls => cls.startsWith('square-'));
if (!squareClass || !pieceType) return;
const square = squareClass.split('-')[1];
if (!square) return;
// Changed file calculation - now counting from left instead of right
const file = parseInt(square[0]) - 1; // Changed this line
const rank = parseInt(square[1]) - 1;
if (isNaN(file) || isNaN(rank) || file < 0 || file > 7 || rank < 0 || rank > 7) return;
const fenMap = {
'wp': 'P', 'bp': 'p',
'wr': 'R', 'br': 'r',
'wn': 'N', 'bn': 'n',
'wb': 'B', 'bb': 'b',
'wq': 'Q', 'bq': 'q',
'wk': 'K', 'bk': 'k'
};
board[7-rank][file] = fenMap[pieceType];
} catch (error) {
console.log('Error processing piece:', error);
}
});
let fen = '';
for (let rank = 0; rank < 8; rank++) {
let emptyCount = 0;
for (let file = 0; file < 8; file++) {
if (board[rank][file] === '') {
emptyCount++;
} else {
if (emptyCount > 0) {
fen += emptyCount;
emptyCount = 0;
}
fen += board[rank][file];
}
}
if (emptyCount > 0) {
fen += emptyCount;
}
if (rank < 7) {
fen += '/';
}
}
fen += ' w KQkq - 0 1';
return fen;
}
console.log('FEN:', getBoardFEN());