My project uses autotiles and animated pieces, hence some code may seem a bit overkill for your use case.
You can support us through Patreon or get access to the final version of the code on GitHub
1. Drawing the board
First you will need to setup a autotiler in order to draw the board and have those nice and crispy edges. I used BetterTerrain to have more control of the TileMap and the Tiny Swords asset pack.
Then start populating the TileMap with respective cells
You can also center the TileMap by doing
2. Defining chess pieces
2.1. Defining Piece Constants
What I did here is that I first created a Constrants.gd preload file that I used to store information about chess pieces and also general stuff that should not change in-game.
You can then store information inside of it such as the sprites that will be used for each individual piece such as
2.2. Creating a Piece Template
We can then create a Unit.tscn class that we’ll use as a template to create chess pieces. The structure should look something like this
Unit (Node2D) # root of the scene
|__ Sprites (Node2D) # in charge of applying changes on sprite components
|__ LeftArm (Sprite2D)
|__ Body (Sprite2D)
|__ Head (Sprite2D)
|__ RightArm (Sprite2D)
|__ AnimationPlayer (AnimationPlayer)
Then we add some code to the Unit node
2.3. Changing Colors using Shaders
You may have seen that I’m calling the Sprites node with a extra variable called Constants.PALETTES. That’s because I swap the palettes of a sprite at run-time to make blue pieces and red pieces.
I’ve added the following shader to the Sprites node and told all it’s children to use the parent material
You can then change the colors programmatically inside the Sprites node by doing
3. FEN and board setup
FEN (or Forsyth–Edwards Notation) is a way to encode the state of a chess board using letters for pieces (p or P for black and white Pawns, n or N for black and white Knights) and numbers for empty spaces.
Thus, you can encode for example the initial state of a chess board by writing
Then you just need to split by / and parse the substrings to setup the board. Easy!
You can even use this notations to add a re-play system to your games.