diff options
-rw-r--r-- | src/cgol.c | 61 |
1 files changed, 61 insertions, 0 deletions
@@ -29,6 +29,10 @@ void init_curses(); void init_game(); void fini_game(); void fini_curses(); +void tick(); +int count_live_neighbors(int i, int j); +bool get_cell(int i, int j); +void set_cell(int i, int j, bool s); void print_cell(int i, int j); void usage(const char *invocation); @@ -162,6 +166,63 @@ fini_curses() } void +tick() +{ + int i, j, n; + bool *grid_tmp; + + for (i = 0; i < height; ++i) { + for (j = 0; j < width; ++j) { + n = count_live_neighbors(i, j); + if (get_cell(i, j)) { + if (n < 2 || n > 3) { + set_cell(i, j, false); + print_cell(i, j); + } + } else { + if (n == 3) { + set_cell(i, j, true); + print_cell(i, j); + } + } + } + } + + /* Swap grids. */ + grid_tmp = grid_cur; + grid_cur = grid_next; + grid_next = grid_tmp; +} + +int +count_live_neighbors(int i, int j) +{ + return + get_cell(i - 1, j - 1) + get_cell(i - 1, j) + get_cell(i - 1, j + 1) + + get_cell(i, j - 1) + get_cell(i, j + 1) + + get_cell(i + 1, j - 1) + get_cell(i + 1, j) + get_cell(i + 1, j + 1); +} + +bool +get_cell(int i, int j) +{ + if (i < 0 || j < 0 || i >= height || j >= width) { + /* This is something of a sanity check. Anything off the finite grid + * is by definition dead. With this, count_live_neighbors() can be + * dumb. */ + return 0; + } else { + return grid_cur[i * width + j]; + } +} + +void +set_cell(int i, int j, bool s) +{ + grid_cur[i * width + j] = s; +} + +void print_cell(int i, int j) { mvprintw(1 + i, 1 + j * 2, "%c", grid_cur[i * width + j] ? 'o' : ' '); |