I'm trying to implement Game of Life in C. I'm certain I programmed the rules of the game correctly, but the cells do not update correctly when running the program. In the beginning of main
, I hard-coded a glider onto the map, but it doesn't 'glide' southwest like it's supposed to. I think the source of the problem might be in the update()
function, but I can't find it myself.
(This isn't homework, this is just a personal project.)
#include <stdio.h>
#include <string.h>
#define MAX_Y 10 /* height */
#define MAX_X 30 /* width */
int neighbors(int grid[MAX_Y][MAX_X], int x, int y) {
int dx, dy, dstx, dsty;
int n = 0;
for (dy = -1; dy < 2; ++dy) {
for (dx = -1; dx < 2; ++dx) {
dsty = y + dy;
dstx = x + dx;
if (dsty > 0 && dsty < MAX_Y && dstx > 0 && dstx < MAX_X) {
n += !!grid[dsty][dstx]; /* use !! so that non-zero values eval to 1 */
}
}
}
/* (n > 0) ? printf("Point (%d,%d) has %d neighbors!\n", x, y, n) : 0; */
return n;
}
int **update(int grid[MAX_Y][MAX_X]) {
int new[MAX_Y][MAX_X];
memset(new, 0, sizeof new);
int i, j, n;
for (i = 0; i < MAX_Y; ++i) {
for (j = 0; j < MAX_X; ++j) {
n = neighbors(grid, i, j);
/* alive, 2 or 3 neighbors -> alive!
* dead, 3 neighbors -> alive!
* anything else -> dead :(
*/
if (grid[i][j] && (n == 2 || n == 3))
new[i][j] = 1;
else if (!grid[i][j] && n == 3)
new[i][j] = 1;
else
new[i][j] = 0;
}
}
return new;
}
void draw(int grid[MAX_Y][MAX_X]) {
int i, j;
for (i = 0; i < MAX_Y; ++i) {
for (j = 0; j < MAX_X; ++j) {
putchar((grid[i][j]) ? '#' : '.');
/* printf("|%2d", grid[i][j]); */
}
putchar('\n');
}
}
int main(void) {
int map[MAX_Y][MAX_X];
memset(map, 0, sizeof map);
map[2][2] = 1;
map[3][2] = 1;
map[4][2] = 1;
map[4][3] = 1;
map[3][4] = 1;
printf( " Game of Life v1.0\n"
"Press ENTER to step.\n");
for (;;) {
draw(map);
memcpy(map, update(map), sizeof map);
getchar();
}
}