I am trying to create the Game of Life with different classes, and I have gotten into trouble.
I want to check if there's an alive individual in the box with index row, col.
Here's my code so far:
public class LifeBoard {
private int rows;
private int cols;
private int generation;
/**Creates a playing field with rows as rows and cols as columns.
The counter for generations is 1.*/
public LifeBoard(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.generation = 1;
}
/**Checks if there's a living individual in the box row, col*/
public boolean get(int row, int col) {
if(this.board[row][col] == null){
return false;
} else {
return true;
}
}
}
I don't know what to do. How do I check this?
It depends on how you've modeled the game. This code assumes a boolean[][]
grid.
There are up to 8 cells that surround a cell. Since we have to check for the boundaries of the grid, there might not be 8 cells surrounding every cell.
public synchronized void cycleGrid() {
this.generationCount++;
for (int i = 0; i < GRID_WIDTH; i++) {
for (int j = 0; j < GRID_WIDTH; j++) {
int count = countCells(i, j);
if (count == 3) grid[i][j] = true;
if (grid[i][j] && count < 2) grid[i][j] = false;
if (grid[i][j] && count > 3) grid[i][j] = false;
}
}
}
private int countCells(int i, int j) {
int count = 0;
int iminus = i - 1;
int jminus = j - 1;
int iplus = i + 1;
int jplus = j + 1;
if (iminus >= 0) {
if (jminus >= 0) {
if (grid[iminus][jminus]) count++;
}
if (grid[iminus][j]) count++;
if (jplus < GRID_WIDTH) {
if (grid[iminus][jplus]) count++;
}
}
if (jminus >= 0) {
if (grid[i][jminus]) count++;
}
if (jplus < GRID_WIDTH) {
if (grid[i][jplus]) count++;
}
if (iplus < GRID_WIDTH) {
if (jminus >= 0) {
if (grid[iplus][jminus]) count++;
}
if (grid[iplus][j]) count++;
if (jplus < GRID_WIDTH) {
if (grid[iplus][jplus]) count++;
}
}
return count;
}
Take a look at my article, John Conway’s Game of Life in Java Swing, for more hints.
Two things from what I have understood.
You haven't set things to NULL and you are making a check for it which wouldn't work.
You can set a check for !=NULL to return true and see if that helps.