So, basically, I've been writing this Game of Life PHP script. My output is wack and I can't figure it out! The whole scheme consists of a 2-dimensional array called $world in which each value corresponds to a 2-state cell that can be 1 or 0(alive or dead). Each cell has 8 neighbors. The rules to compute the next state of the system are as follows:
- If you have 2-3 live neighbors(1's), you're alive the next turn.
- Otherwise you're dead.
My implementation is as follows:
(note: $j_minus
, $i_plus
, etc refers to $j-1
, etc but takes the edges into account)
for($i=0;$i<$size;$i++)
{
for($j=0;$j<$size;$j++)
{
if( ($world[$j_minus][$i] + $world[$j_plus][$i] + $world[$j][$i_minus] + $world[$j][$i_plus]+$world[$j_minus][$i_minus]+$world[$j_minus][$i_plus]+$world[$j_plus][$i_minus]+$world[$j_plus][$i_plus]) > 3 )
{
$new_world[$j][$i]=0;
}
else if( ($world[$j_minus][$i] + $world[$j_plus][$i] + $world[$j][$i_minus] + $world[$j][$i_plus]+$world[$j_minus][$i_minus]+$world[$j_minus][$i_plus]+$world[$j_plus][$i_minus]+$world[$j_plus][$i_plus])>= 2 )
{
$new_world[$j][$i]=1;
}
else {$new_world[$j][$i]=0;}
}
}
After these rules have been applied, making $new_world the new state of the system, I go to print the array to the screen with this:
for($i=0;$i<$size;$i++)
{
for($j=0;$j<$size;$j++)
{
echo $new_world[$i][$j]." ";
}
echo "</p>";
}
What I get, regardless of the initial state of $world
, is either a completely stagnant state full of lines and big blocks or an oscillation between 2-3 such states. The rules don't seem to be applying correctly!