Change all the 25's in your program to SIZE and put this after your includes:
const int SIZE = 25;
Don't make your grids global. Define them in main and pass them to your functions. Then you'll only need one "initGrid" function, for instance.
You don't need to check if a living cell has less than 2 neighbors or more than 3 neighbors because these checks are simply the opposite of checking if it is 2 or 3, i.e., if a living cell does not have 2 or 3 neighbors it dies.Code:#include <cstring> // for memset() and memcpy()
const int SIZE = 25;
typedef char GRID[SIZE][SIZE];
int main() {
Grid grid, nextGrid;
initGrid(grid);
initGrid(nextGrid); // actually, you shouldn't do this here! (see below)
...
void initGrid(Grid g) {
memset(g, '-', SIZE * SIZE);
}
void copyGrid(Grid dest, Grid src) {
memcpy(dest, src, SIZE * SIZE);
}
Actually, you shouldn't have these checks in functions. In particular, it's not very smart to be calling gridCheck multiple times when it could just be called once.
And gridCheck is not properly guarding against array overrun. You have to check for every x or y that you add or subtract 1 to/from.
In Game you need to clear nextGrid every time (just after while(true) ). That will start it off in the state "all cells dead". So you just need to turn on the live cells. I.e., write to nextGrid all living cells that are still living and all dead cells that have just come to life.Code:if (x > 0 && grid[x-1][y] == '0') ++count;
if (x < SIZE-1 && grid[x+1][y] == '0') ++count;
if ( y > 0 && grid[x] [y-1] == '0') ++count;
if ( y < SIZE-1 && grid[x] [y+1] == '0') ++count;
if (x > 0 && y > 0 && grid[x-1][y-1] == '0') ++count;
if (x > 0 && y < SIZE-1 && grid[x-1][y+1] == '0') ++count;
if (x < SIZE-1 && y > 0 && grid[x+1][y-1] == '0') ++count;
if (x < SIZE-1 && y < SIZE-1 && grid[x+1][y+1] == '0') ++count;
EDIT: To the admins: what's wrong with the code blocks? It seems to be double-blocking the code and it is not (for me at least) properly copy/pastable.