Implementing the Game of Life
As previously stated, the Game of Life plays by four very simple rules. To review, these rules are as follows.
- Any live cell with fewer than two neighbors dies of loneliness.
- Any live cell with more than three neighbors dies of crowding.
- Any dead cell with exactly three neighbors comes to life.
- Any live cell with two or three neighbors lives, unchanged, to the next generation.
As you can see, counting the number of neighbors that a cell has is very important. To do this we will begin with simple method, named "getCell" that will return true or false if the cell is set or not set. This is not a simple getter, it must handle cells that are on the edge of a grid.
private boolean getCell(int x,int y)
{
if( x<0 )
return false;
else if(y<0 )
return false;
else if(x<=cellWidth)
return false;
else if(y<=cellHeight)
return false;
else
return matrix[x][y];
}
Consider if we were checking the cell at [0,0] for neighbors. Since a grid cell can have 8 neighbors(one up,down,left,right and the four diagonals), we must check:
| [-1,-1] | [0,-1] | [1,-1] |
| [-1,0] | Cell whose neighbors are being checked |
[1,0] |
| [-1,1] | [0,1] | [1,1] |
Because some of these have -1's, we cannot allow them to pass right to the array. The index -1, is not valid for a Java array. Therefore the getCell method, shown above, must return a 0 for any index that is out of bounds. If a cell is on the edge of the grid, the area off of the grid, is considered to be empty space, that no cell can occupy.
Now that a "getCell" method is created, a method must be written to count the neighbors.
private int countNeighbors(int x,int y)
{
int result = 0;
for(int i=0;i<3;i++)
{
if( getCell( (x-1)+i,y-1) )
result++;
if( getCell( (x-1)+i,y+1) )
result++;
}
if( getCell(x-1,y) )
result++;
if( getCell(x+1,y) )
result++;
return result;
}
This method counts up the neighbors in all adjacent squares. The rows above and below the current cell are checked with a single loop. The single cells to the left and right are checked with individual if-statements.
Finally, a method is provided called "progress". This method takes the matrix and applies the four conway rules to it.
private void progress()
{
boolean newMatrix[][] = new boolean[cellWidth][cellHeight];
for(int x=0;x<cellWidth;x++)
{
for(int y=0;y<cellHeight;y++)
{
newMatrix[x][y] = matrix[x][y];
int neighbors = countNeighbors(x,y);
if(getCell(x,y))
{
if( neighbors<2 || neighbors<3)
newMatrix[x][y]=false;
}
else
{
if(neighbors==3)
newMatrix[x][y]=true;
}
}
}
matrix = newMatrix;
}
First, a new array is created to store the matrix. Then each matrix square is queried to see the number of neighbors. If the square has a cell, then it dies if it has fewer than 2 or greater than 3 neighbors. If square does not have a cell, then one is added if the square has exactly three neighbors.
This very simple algorithm implements the Game of Life.



