In the previous episode, we have seen how to write the main loop,
allowing the players to take their turns and play.
Only missing
was the stopping condition.
Thus, we still need to write
something here so that the loop will stop
either once a player has won or once the grid is full.
For now, we will focus on
the case where we expect the loop to stop
because one of the two players has won.
To that end, we will simply introduce
a new function called "est_ce_gagne" (TN: means "is_it_won").
We will call this functions as follows.
We will store the result of the "est_ce_gagne" function
inside a variable called "gagne" (TN: means "won" or "wins").
This bool-type variable
"gagne" will receive
the return value of the function "est_ce_gagne".
As argument, the "est_ce_gagne" function
will receive the grid,
and the color of the player
who has just played.
Also, we will need to declare our "gagne" variable.
Since we will need to use it
as the stopping condition, we need to declare "gagne" outiside the loop,
that is, somewhere around here. Now, we can use
the "gagne" variable in our stopping condition.
This will simply be
written like this.
We will repeat the loop
as long as the player has not won.
We now need to write this "est_ce_gagne" function; this will probably
be the trickiest part of our program.
So, how should
we proceed?
Actually, there are several ways to write this "est_ce_gagne" function.
The strategy we are offering is the following:
We will run through the grid row by row
and column by column
until we encounter a disk which color
is the color of the player who has just played.
Let us say, for example, that the red player has just played.
This newly-dropped disk is here.
Now, we will start from this disk
and look over the grid in several directions,
horizontally, vertically and diagonally.
Thus, we will count the
same-colored disks,
starting from this one here.
If, for example, we consider this direction here,
we can count
1, 2, 3, 4 red disks;
the red player has thus won.
If, on the other hand, we have looked over the whole grid
without counting at least 4 disks,
we know that the player has not won.
By the way, we do not have to consider
all the directions.
Actually, we will only have to count the disks in 4 directions.
For example, we will choose
the Northeast,
the East,