In the last blog post, you set up the prerequisites and file structure of the project.
Now let's start implementing the logic of the game.
Rules Of The Game#
Four-in-a-row is a two-player game played on a 6 (rows) x 7 (columns) rack board, where the objective is to be the first player to form a vertical, horizontal or vertical line with four of your tokens.
The player who meets the objective first, wins. If the board is filled and there is no winner, the game ends in a draw.
Each token a player puts down a column falls to the lowest available space within a column.
Preparing To Implement The Logic#
Now that you'll know the rules, you'll now write down relevant constant values that you'll be using throughout this project.
Now add the following to the file you've just created:
; ; ; ; ;
Setting Up The State Machine#
Now you will create a state machine which represents a four-in-a-row game.
/src and add the following to it:
These lines reference the constants you wrote in
src/constants/index.js, making them available to use in
FourInARowGame.js. It also creates a class called
To get the game going, you'll need to be aware of the following:
- The current game's status - To know whether the game has ended or not and if it has ended, how it ended
- The current turn - To figure out which player's token to put down when a move is next played
- The starting colour player token - To determine who starts the game
- The state of the board - To know which tokens have been placed on the board
Let's add these fields to your
Regarding the starting colour, there isn't any rule about which colour should start but you'll set it to
Next up is the
status. Since the game has just started, you'll set the value of
currentTurn to the value of
startingColor and set the value of
Initialising The Board Field#
Now, for the
The first step is creating a static method in the
FourInARowGame class that creates an empty board for you:
Uint8Array was used instead of
Number data type by default, which stores 64-bit floating point numbers. You will only be using 3 possible numbers in each board position so
Uint8 makes more sense which is the smallest numeric data type that your range of possible numbers fits in.
This saves memory considering that there are 42 positions in a board.
Now you can finish off initialising the
You are now ready to implement the logic that runs when a player makes a move.
You'll do this in the next post! See you then! 👋