Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /* Applies the rules of Life to the grid. */
- void updateGrid();
- /* Prints out a representation of the grid using binary digits. */
- void printGrid();
- #define GRID_SIZE 10
- #define ITERATIONS 10
- /* Conway's Game of Life as a C exercise.
- TODO: Allow command line arguments specifying the grid size and number of iterations.
- */
- int main(int argc, char **argv)
- {
- int grid[GRID_SIZE][GRID_SIZE] = {
- {0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
- {1, 0, 1, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 1, 1, 1, 0, 1, 0, 0},
- {0, 1, 0, 1, 0, 0, 0, 0, 1, 0},
- {0, 0, 0, 0, 0, 1, 1, 0, 0, 0},
- {0, 0, 0, 0, 1, 0, 0, 1, 0, 0},
- {1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 1, 1, 1, 0, 1, 1, 1, 0}
- };
- printGrid(grid);
- printf("---\n");
- int i = 0;
- while (i < ITERATIONS)
- {
- updateGrid(&grid);
- i++;
- }
- printGrid(grid);
- return 0;
- }
- void updateGrid(int gridn[][GRID_SIZE])
- {
- int i = 1, j = 1, n = 0;
- int alive = 0;
- int grid[GRID_SIZE][GRID_SIZE];
- memcpy(grid, gridn, sizeof(int) * GRID_SIZE * GRID_SIZE);
- while (i < GRID_SIZE)
- {
- while (j < GRID_SIZE)
- {
- if (grid[i-1][j-1] == 1) n++;
- if (grid[i-1][j] == 1) n++;
- if (grid[i-1][j+1] == 1) n++;
- if (grid[i][j-1] == 1) n++;
- if (grid[i][j] == 1) alive = 1;
- if (grid[i][j+1] == 1) n++;
- if (grid[i+1][j-1] == 1) n++;
- if (grid[i+1][j] == 1) n++;
- if (grid[i+1][j+1] == 1) n++;
- // n is now the number of live neighbours of the current cell.
- if (!alive && n == 3)
- { // Reproduce!
- gridn[i][j] = 1;
- }
- else if (alive && n != 2 && n != 3)
- { // Overcrowding or no opportunity for reproduction. :<
- gridn[i][j] = 0;
- }
- n = 0;
- alive = 0;
- j++;
- }
- j = 1;
- i++;
- }
- }
- void printGrid(int grid[][GRID_SIZE])
- {
- int i = 0, j = 0;
- while (i < GRID_SIZE)
- {
- while (j < GRID_SIZE)
- {
- printf("%d", grid[i][j]);
- j++;
- }
- printf("\n");
- j = 0;
- i++;
- }
- }
Add Comment
Please, Sign In to add comment