// We are using ES6 imports so this needs to be inside script type="module" -
// this is handled automatically in CodePen.
import { Chessboard } from "https://cdn.jsdelivr.net/npm/cm-chessboard@3/src/cm-chessboard/Chessboard.js";
// Note we have also loaded the following module which creates the Chess global.
// https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.11.0/chess.min.js
// Set up a 'game' in FEN.
const game = new Chess("8/8/8/8/8/8/8/1N6 w - - 0 1");
// Some moves in PGN.
const moves = "b1-c3,c3-a2,a2-c1,c1-b3,b3-a1,a1-c2,c2-a3,a3-b2".split(",");
// Select DOM element as a target.
const el = document.querySelector("#board");
// Set the sprites to use for pieces (the default doesn't work when loading from a CDN).
const url =
"https://cdn.jsdelivr.net/npm/cm-chessboard@3/assets/images/chessboard-sprite-staunty.svg";
// Create the board.
const board = new Chessboard(el, {
sprite: { url },
// Move more slowly (default 300ms).
animationDuration: 1000
});
// Log a move into the DOM.
function logMove(move) {
document.querySelector("#moves").innerHTML += ` ${move.slice(-2)}`;
}
// Mark a move on the board.
function markMove(move) {
board.addMarker(move.slice(-2));
}
// This function is declared asynchronous so we can use 'await'.
async function play() {
// Log the initial position;
document.querySelector("#moves").innerHTML = moves[0].substring(0, 2);
// Set up the board then mark the initial position.
await board.setPosition(game.fen());
board.addMarker(moves[0].substring(0, 2));
// Iterate through the moves.
for (let i = 0; i < moves.length; ++i) {
const move = moves[i];
logMove(move);
// Try to execute the move.
if (!game.move(move, { sloppy: true })) {
// Log an illegal move and stop playing.
document.querySelector("#moves").innerHTML += " Illegal move";
break;
}
// The move was successful so execute the move on the board and mark the square.
// Note that setPosition() returns a Promise that is resolved when the move is
// complete, so wait for it before continuing.
await board.setPosition(game.fen());
markMove(move);
// Reset the game from the displayed board otherwise it will be black's turn!
game.load(board.getPosition() + " w - - 0 1");
}
}
// Wait for a bit before we start moving things around.
const timer = setTimeout(play, 2000);