xxxxxxxxxx
88
let fenString = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
let squareSize;
let board = [];
// since we can use the fill/stroke options to change color, lets just use the black symbols becuase they're lready filled
const pieceSymbols = {
'r': '♜', 'n': '♞', 'b': '♝', 'q': '♛', 'k': '♚', 'p': ' ♟︎',
'R': '♜', 'N': '♞', 'B': '♝', 'Q': '♛', 'K': '♚', 'P': ' ♟︎'
};
const OldpieceSymbols = {
'r': '♜', 'n': '♞', 'b': '♝', 'q': '♛', 'k': '♚', 'p': ' ♟︎',
'R': '♖', 'N': '♘', 'B': '♗', 'Q': '♕', 'K': '♔', 'P': '♙'
};
let chessFontMerida
function preload() {
// https://github.com/xeyownt/chess_merida_unicode/blob/master/chess_merida_unicode.ttf
chessFontMerida = loadFont('chess_merida_unicode.ttf');
}
function setup() {
// Create a description element above the canvas
createElement('h2', 'Chess Board Visualization');
createCanvas(400, 400).parent('canvasContainer'); // Ensure the canvas is a child of a specific element if needed
textFont(chessFontMerida)
squareSize = width / 8;
parseFEN(fenString);
}
function draw() {
background(255);
drawBoard();
}
function drawBoard() {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
let x = i * squareSize;
let y = j * squareSize;
if ((i + j) % 2 == 0) {
fill(238,238,210); // Light color
} else {
fill(118,150,86); // Dark color
}
rect(x, y, squareSize, squareSize);
// Draw pieces with more pronounced styles
let piece = board[j][i];
if (piece) {
// Determine piece color (black or white)
let isWhite = piece === piece.toUpperCase();
// 'fill'
fill(isWhite ? 255 : 0);
// outline
// strokeWeight(2); // outline thickness
stroke(isWhite ? 0 : 255); // outline color
textSize(40);
textAlign(CENTER, CENTER);
const piece_as_font = pieceSymbols[piece]
text(piece_as_font, x + squareSize / 2, y + squareSize / 2);
}
}
}
}
function parseFEN(fen) {
board = Array(8).fill().map(() => Array(8).fill(null)); // Reset board
let rows = fen.split(" ")[0].split("/");
for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
let row = rows[rowIndex];
let colIndex = 0;
for (let charIndex = 0; charIndex < row.length; charIndex++) {
if (isNaN(row[charIndex])) { // If it's a piece
board[rowIndex][colIndex] = row[charIndex]
colIndex++;
} else { // If it's a number
colIndex += parseInt(row[charIndex], 10);
}
}
}
}