Public
Edited
Jun 18, 2023
Insert cell
Insert cell
renderChessboard("r1b1k1nr/pp3ppp/2n1p3/1B1p4/Q2P1B2/4P3/P3qKPPP/q5NR w kq - 0 11")
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
renderChessboard = {
function renderChessboard(fen) {
const ranks = fen.split(' ')[0].split('/');

const board = document.createElement('table');
board.className = 'chessboard';

for (let rankIndex = 0; rankIndex < 8; rankIndex++) {
const rank = ranks[rankIndex];
const rankRow = document.createElement('tr');

let fileIndex = 0;
for (let charIndex = 0; charIndex < rank.length; charIndex++) {
const char = rank[charIndex];
if (isNaN(parseInt(char, 10))) {
const square = document.createElement('td');
square.className = (fileIndex + rankIndex) % 2 === 0 ? 'light' : 'dark';
square.innerHTML = getPieceSymbol(char);
rankRow.appendChild(square);
fileIndex++;
} else {
const emptySquares = parseInt(char, 10);
for (let i = 0; i < emptySquares; i++) {
const square = document.createElement('td');
square.className = (fileIndex + rankIndex) % 2 === 0 ? 'light' : 'dark';
rankRow.appendChild(square);
fileIndex++;
}
}
}

board.appendChild(rankRow);
}

return board;
}

function getPieceSymbol(piece) {
switch (piece) {
case 'r': return '&#9820;'; // Black Rook
case 'n': return '&#9822;'; // Black Knight
case 'b': return '&#9821;'; // Black Bishop
case 'q': return '&#9819;'; // Black Queen
case 'k': return '&#9818;'; // Black King
case 'p': return '&#9823;'; // Black Pawn
case 'R': return '&#9814;'; // White Rook
case 'N': return '&#9816;'; // White Knight
case 'B': return '&#9815;'; // White Bishop
case 'Q': return '&#9813;'; // White Queen
case 'K': return '&#9812;'; // White King
case 'P': return '&#9817;'; // White Pawn
default: return '';
}
}

return renderChessboard
}
Insert cell
htl.html`<style>

.chessboard {
width: auto;
border-collapse: collapse;
margin: 0 auto;
}

.chessboard td {
width: 15px;
height: 15px;
text-align: center;
padding: 1px;
}

.light {
background-color: #f0d9b5;
}

.dark {
background-color: #b58863;
}

</style>`
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more