I've tried to make Game of Life in console and this is the algorithm I used to generate new generation:
void processGeneration() {
population = 0;
int neighbors;
int tempGrid[ROWS][COLS];
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
if (grid[i][j] == -1) {
continue;
}
neighbors = countNeighbors(i, j);
if (grid[i][j] == 0) {
if (neighbors == 3) {
tempGrid[i][j] = 1;
} else {
tempGrid[i][j] = 0;
}
} else if (grid[i][j] == 1) {
if (neighbors < 2 || neighbors > 3) {
tempGrid[i][j] = 0;
} else {
tempGrid[i][j] = 1;
}
}
}
}
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
if (grid[i][j] == -1) {
continue;
}
if (tempGrid[i][j] == 1) {
population++;
}
grid[i][j] = tempGrid[i][j];
}
}
}
I'm a bit uncertain if what I did was right, so could you check the algorithm? Also, grid
is the grid where I save the cells in and I just use tempGrid
to change the values and then copy them to the grid.
int countNeighbors(int row, int col) {
int neighbors = 0;
for(int i = row - 1; i < row + 2; i++) {
for(int j = col - 1; j < col + 2; j++) {
if (i == row && j == col) {
continue;
}
if (i > -1 && j > -1 && i < ROWS && j < COLS) {
neighbors += grid[i][j];
}
}
}
return neighbors;
}