Chess Web Programming: Part Nine: Chessground
Exploring Lichess ChessgroundIn this tutorial, we’ll build a simple and interactive chess application using React, Chessground.js, and Chess.js. Chessground.js, developed by the creators of Lichess, a renowned online chess platform, is a powerful library designed to render a sleek and customizable chessboard. It offers a range of features such as draggable pieces, square highlighting, arrow drawing, board flipping, and coordinate display, making it suitable for casual play, chess training, or advanced game analysis. As the engine behind Lichess's board interface, Chessground is lightweight, fast, and seamlessly integrates into modern web applications.
To handle move validation and game logic, we’ll use Chess.js, a robust library that enforces the rules of chess. Chess.js validates moves, manages game states, and handles special rules like castling, en passant, and pawn promotion, ensuring a realistic and rule-compliant gameplay experience.
We’ll also use Vite, a modern build tool, to set up and run the project. Vite’s speed and ease of use make it an excellent choice for building and testing React applications, especially for dynamic projects like this chessboard application.
By the end of this tutorial, you’ll have a fully functional chessboard that validates moves, enforces chess rules, and ensures invalid moves snap back to their original positions. This project not only provides a complete chess-playing experience but also lays the groundwork for exploring advanced Chessground features, such as move suggestions, real-time annotations, or integration with a chess engine for analysis. Let’s dive in!
Note: Before starting this tutorial, ensure that npm (Node Package Manager) is installed on your system. npm comes bundled with Node.js, so you can install Node.js to get npm. Visit the Node.js official website and download the latest LTS (Long-Term Support) version for your operating system.
Note: In my previous blogs, I used create-react-app to set up React projects and react-chessboard to implement the chessboard interface. This is what I used for chessboardmagic.com. However, for this blog, I decided to explore new tools by using Chessground.js for its advanced board customization and features, and Vite for its modern, fast, and efficient development setup.
Setting Up the Project
To get started, we’ll set up a React project using Vite, a modern build tool known for its speed and simplicity. This section will guide you through creating a new project, installing the necessary dependencies, and preparing the environment for building a chess application. With just a few commands, you’ll have a fully configured project ready to integrate Chessground.js for the chessboard interface and Chess.js for move validation and game logic. Let’s dive in!
Step 1: Create a New React Project
Start by creating a new Vite project using the following command:
npm create vite@latest
Note: If you’re new to using the terminal or command prompt, running a command means typing the exact text provided into your terminal and pressing Enter. The terminal is a text-based interface that lets you interact with your computer. Here’s how to open it:
- Windows: Press
Win + R
, typecmd
, and hit Enter to open the Command Prompt. Alternatively, search for "Terminal" in the Start menu.- macOS: Press
Command + Space
, typeTerminal
, and hit **Enter`.- Linux: Open your applications menu and search for "Terminal."
When prompted:
- Enter
chessground-app
as the project name. - Select
React
as the framework. - Choose
JavaScript
as the variant.
Next, navigate to the project directory and install the dependencies:
cd chessground-app
npm install
Step 2: Run the Development Server
Before adding any custom functionality, let’s ensure the project is set up correctly and running. Start the development server with:
npm run dev
This command starts the Vite development server, which hosts your application locally. After running the command, you’ll see an output similar to this:
VITE v6.0.3 ready in 399 ms
Local: http://localhost:5173/
Network: use --host to expose
press h + enter to show help
Open your browser and go to the URL provided (e.g., http://localhost:5173
). You should see the default Vite React screen, which confirms the setup is successful.
With the development server running, any changes you make to the code will automatically update in the browser. Let’s move on to preparing the CSS files for Chessground.
Preparing Chessground CSS Files
Chessground.js provides a visually appealing chessboard, but its appearance depends on specific CSS files for styling the board and rendering chess pieces. These files are not automatically included in your project and must be manually added to ensure everything looks and functions as expected. In this section, we’ll locate the required CSS files in the Chessground library, copy them into our project, and include them in our HTML file. By the end of this step, your project will be ready to render a beautifully styled chessboard.
Step 1: Locate Chessground CSS Files
Chessground’s visual appearance relies on three CSS files:
chessground.base.css
chessground.brown.css
(the board theme)chessground.cburnett.css
(the piece sprites)
These files are located in node_modules/chessground/assets/
.
Step 2: Copy CSS Files to the Public Folder
To make these files accessible, copy them to the public/css
folder of your project. You can use either the command-line method or manually copy and paste the files:
- Command-Line Method:
mkdir -p public/css
cp node_modules/chessground/assets/chessground.base.css public/css/
cp node_modules/chessground/assets/chessground.brown.css public/css/
cp node_modules/chessground/assets/chessground.cburnett.css public/css/
- Manual Copy-Paste Method:
- Open
node_modules/chessground/assets/
in your file explorer. - Copy the files:
chessground.base.css
chessground.brown.css
chessground.cburnett.css
- Paste them into the
public/css
folder in your project directory.
- Open
Step 3: Add CSS Links to index.html
Once the CSS files are in place, update your index.html
file to include them:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<!-- Chessground CSS -->
<link rel="stylesheet" href="/css/chessground.base.css" />
<link rel="stylesheet" href="/css/chessground.brown.css" />
<link rel="stylesheet" href="/css/chessground.cburnett.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chessground Chess Application</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
With the Chessground CSS files copied and linked in your index.html
, your project is now ready to render a fully styled chessboard. These files ensure that the board and pieces display correctly and provide the foundation for customizing the appearance of your application.
Building the Chess Application
With the project setup complete and the necessary CSS files in place, it’s time to bring the chessboard to life. In this section, we’ll use Chessground.js to create an interactive chessboard and integrate Chess.js to validate moves and manage the game’s logic. We’ll also implement features like snapping back pieces after invalid moves and updating the board dynamically after valid ones. By the end of this step, you’ll have a fully functional chessboard that enforces chess rules and handles gameplay interactions seamlessly.
Step 1: Install Chessground.js and Chess.js
Install the required libraries for the chessboard and move validation:
npm install chessground chess.js
Step 2: Updated the src/App.jsx
Replace the contents of src/App.jsx
with the following code. This creates a chessboard with move validation and snap-back for invalid moves:
import { useEffect, useRef, useState } from "react";
import { Chess } from "chess.js"; // Import Chess.js for move validation
import { Chessground } from "chessground"; // Import Chessground for the board
const App = () => {
const [chess] = useState(new Chess()); // Initialize Chess.js
const boardRef = useRef(null); // Reference for the Chessground container
const groundRef = useRef(null); // Store Chessground instance
useEffect(() => {
// Initialize Chessground
groundRef.current = Chessground(boardRef.current, {
fen: chess.fen(), // Start position in FEN format
draggable: {
enabled: true, // Enable dragging pieces
},
movable: {
events: {
// Triggered after a piece is moved
after: (from, to) => {
console.log(`Attempting move: ${from} -> ${to}`);
try {
const move = chess.move({
from,
to,
promotion: "q", // Assume pawn promotion to queen
});
if (move) {
console.log("Move valid:", move);
// Update board to the new position
groundRef.current.set({ fen: chess.fen() });
}
} catch (error) {
console.error(error.message);
// Reset board to the last valid position
groundRef.current.set({ fen: chess.fen() });
}
},
},
},
});
// Clean up Chessground instance on component unmount
return () => {
groundRef.current.destroy();
};
}, [chess]);
return (
<div>
<h1>Chessground Chess Application</h1>
<div
ref={boardRef}
style={{
width: "400px", // Set board width
height: "400px", // Set board height
margin: "0 auto", // Center board
border: "1px solid #ccc", // Add a border
}}
></div>
</div>
);
};
export default App;
Code explanation:
- Imports
The code imports React hooks (useEffect
,useRef
,useState
) to handle component lifecycle, state management, and references. It also imports Chess.js for validating moves and managing chess logic, and Chessground.js for rendering the interactive chessboard.- State and References
- The
chess
state initializes a Chess.js instance to manage the chess game's rules and logic.boardRef
provides a reference to the container where the Chessground chessboard will be rendered.groundRef
stores the Chessground instance to allow interaction with the chessboard programmatically.
- useEffect Hook
This hook initializes the Chessground instance when the component mounts and cleans it up when the component unmounts.
- Chessground Initialization:
- Uses
boardRef
to render the chessboard in the referenced DOM element.- Sets the initial board position using the FEN string from the Chess.js instance.
- Enables dragging pieces via the
draggable.enabled
property.- Movable Configuration:
- The
movable.events.after
function is triggered after a piece is moved. It:
- Logs the attempted move.
- Validates the move using Chess.js. If the move is valid, it updates the Chess.js state and the Chessground board.
- If the move is invalid, it resets the Chessground board to the last valid state using the current FEN from Chess.js.
- Cleanup:
- Destroys the Chessground instance when the component is unmounted to free up resources.
- Rendering
Thereturn
statement renders:
- A heading for the application.
- A
div
container styled as a chessboard, where Chessground renders the board. TheboardRef
reference connects this container to the Chessground instance.
Visit http://localhost:5173
in your browser. You’ll see a chessboard where you can move pieces. Moves will snap back if they are invalid, and valid moves will update the board state dynamically.
Summary
By following this tutorial, you’ve created a React-based chess application using Chessground.js for the interactive chessboard and Chess.js for game logic and move validation. You now have a fully functional chessboard that ensures legal play and handles invalid moves gracefully. But there’s so much more to explore! Chessground offers features like drawing arrows and highlighting squares, flipping the board dynamically, enabling coordinates, and more. You could even extend this application by integrating chess puzzles, AI opponents, or multiplayer functionality. The possibilities are endless—happy coding!
If you have any questions or need clarification on any step, please feel free to post them in the comments, and I’ll be happy to help!
Learn More
- Vite Vite is a modern build tool optimized for speed and developer experience. It offers instant server startup, fast hot module replacement, and optimized builds, making it an excellent choice for React and other front-end projects.
- React React is a popular JavaScript library for building user interfaces. It allows you to create reusable components and manage complex application states efficiently, making it ideal for interactive applications like this chessboard.
- Chessground.js Chessground.js, developed by Lichess, is a lightweight and highly customizable library for rendering interactive chessboards. It’s packed with features like draggable pieces, highlighting, flipping the board, and more, making it perfect for chess-related projects.
- Chess.js Chess.js is a robust library for chess move validation and game logic. It enforces the rules of chess, supports special moves like castling and en passant, and allows you to track the game state and manage moves dynamically.
- Node.js Node.js is a JavaScript runtime that allows you to run JavaScript on the server. It includes npm (Node Package Manager), which we used to install and manage project dependencies.
These tools and libraries combine to provide a powerful foundation for building interactive chess applications and much more!