Gomoku Stage 2: Solution
Learn to implement the Gomoku Player stage 2.
Now that we know how to start and continue the game, let’s implement the second stage, where we decide how and when to stop the game.
When does the game stop?
- When either player wins the game.
- When the game is drawn.
So let’s incorporate the stopping conditions in our code.
Stage 2 implementation
Extending the memory
To declare a game to be over, we need to check whether someone has won the game after each turn.
We would need a bool
variable called gameOver
, which can initially be set to false
.
We can have a variable called winner
set to -1
initially.
Checking for the winner
After displaying the updated board (revised), we can create a function that checks whether we have a winner after each turn. Let’s call it the isWin()
function.
We would need a winCount
(to see if the win count of a certain symbol has been reached), pSym
symbol (to check that particular symbol for win count), the array for the board Board[][CAPACITY]
(on which we are playing) of the dimension dim
. Finally, we would also need the row and column indices of the position (ri
and ci
).
Our function prototype would then be as follows:
bool isWin(char Board[][CAPACITY], int dim, int winCount, char pSym, int ri, int ci)
As for its implementation, we might need to check for the winCount
in all directions.
Here comes the interesting part. You’d would naturally think that to see if a player has won or not after each turn, we would need to check for the winCount
number of consecutive symbols vertically up and down, horizontally left and right, as well as left and right diagonally (in all directions).
However, that is not the case. After each turn, if we were to run a loop that checks for winCount
symbols starting from the first cell to the last cell of the grid, then we would not need to check for the symbols vertically upwards and horizontally towards the left. This is because each cell’s vertically upward and horizontally left cells would have already been checked.
Let’s see the animation below for better understanding.
Get hands-on with 1200+ tech skills courses.