I’m trying to make a Flood-It style game, and I am having issues with the main algorithm.
The algorithm checks for every square that you already control and finds adjacent squares that have the selected color that you don’t control.
Variables:
1 – $board: the 2 dimensional array that holds the state of the board
- The squares you control in the array are = 0
- The squares you don’t control range from 1, 6 and represent different colors.
2 – $color: is the color selected by the user
3 – $size: is the square size of the playing board
4 – $rkey / $ckey : the row and column in the 2 dimensional array
The main issue is that it works for the first few squares in the starting corner, maybe 2 or 3, and then it stops taking control of new squares.
Here is an example of the game I’m trying to make: http://floodit.appspot.com/
function checkRecursive($rkey, $ckey)
{
global $board, $size, $color;
if ($board[$rkey][$ckey] == 0)
{
if ($rkey < $size-1 && $board[$rkey + 1][$ckey] == $color)
{
$board[$rkey + 1][$ckey] = 0;
checkRecursive($rkey + 1, $ckey);
}
if ($ckey < $size-1 && $board[$rkey][$ckey + 1] == $color)
{
$board[$rkey][$ckey + 1] = 0;
checkRecursive($rkey, $ckey + 1);
}
if ($rkey > 0 && $board[$rkey - 1][$ckey] == $color)
{
$board[$rkey - 1][$ckey] = 0;
checkRecursive($rkey - 1, $ckey);
}
if ($ckey > 0 && $board[$rkey][$ckey - 1] == $color)
{
$board[$rkey][$ckey - 1] = 0;
checkRecursive($rkey, $ckey - 1);
}
}
}
Reading your code, it looks like if you’re always starting at (0,0), then once the squares immediately adjacent to that cell are under player control, further checks won’t get passed them.
You’ll go:
I think maybe you need to remove the concept of “controlling” squares. All you want to do is repeatedly execute a flood fill algorithm with different colours.
I think something like this might be better, where $oldcolor is the color of your starting cell before you begin, and $newcolor is the color chosen by the user: