public bool [,] NewGeneration ()
{
// Set up a new working grid
bool [,] newGrid = new bool [myColumns, myRows];
// Scan the current grid. For each cell in the current grid,
// get a count of the live cells surrounding it
for (int column = 0; column < myGrid.GetLength (0); column++)
{
for (int row = 0; row < myGrid.GetLength (1); row++)
{
int count = CheckStatus (column, row);
// Based on the live cells surrounding the current cell
// use the Rules of Life to determine whether the current
// cell lives or dies
if (myGrid [column, row])
{
if (count == 2 || count == 3)
newGrid [column, row] = true;
if (count < 2 || count > 3)
newGrid [column, row] = false;
}
else
{
if (count == 3)
newGrid [column, row] = true;
}
}
}
myGrid = newGrid;
return newGrid; // Update the main grid
} // method NewGeneration
NewGeneration() uses a method called CheckStatus() shown below.
private int CheckStatus (int column, int row)
{
int count = 0;
// if upper-left is alive...
if ((column - 1 >= 0 && row - 1 > 0) &&
myGrid [column - 1, row - 1] == true)
count++;
// if upper is alive...
if ((column - 1 >= 0) && myGrid [column - 1, row] == true)
count++;
// if upper-right is alive...
if ((column - 1 >= 0 && row + 1 < myRows) &&
myGrid [column - 1, row + 1] == true)
count++;
// if left is alive...
if ((row - 1 >= 0) && myGrid [column, row - 1] == true)
count++;
// if right is alive...
if ((row + 1 < myRows) && myGrid [column, row + 1] == true)
count++;
// if lower-left is alive...
if ((column + 1 < myColumns && row - 1 >= 0) &&
myGrid [column + 1, row - 1] == true)
count++;
// if lower is alive...
if ((column + 1 < myColumns) && myGrid [column + 1, row] == true)
count++;
// if lower-right is alive...
if ((column + 1 < myColumns &&
row + 1 < myRows) &&
myGrid [column + 1, row + 1] == true)
count++;
return count;
} // method CheckStatus
Here is the code for UpdateGrid():
private void UpdateGrid ()
{
var brushBlack = new SolidBrush (Color.Black);
var brushWhite = new SolidBrush (SystemColors.Control);
Graphics cellGraphics = panelGrid.CreateGraphics ();
for (int i = 0; i < grid.GetUpperBound (0); i++)
for (int j = 0; j < grid.GetUpperBound (1); j++)
{
if (grid [i,j])
brush = brushBlack;
else
brush = brushWhite;
Rectangle rect = cells [i, j];
PanelGrid_Paint (this, new PaintEventArgs (cellGraphics, rect));
}
brushBlack.Dispose ();
brushWhite.Dispose ();
}