Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define DEAD 0
- #define ALIVE 1
- #define ROWS 10
- #define COLS 10
- int grid[ROWS][COLS];
- /* Initializes the grid with a random pattern */
- void init_grid()
- {
- for (int i = 0; i < ROWS; i++)
- {
- for (int j = 0; j < COLS; j++)
- {
- grid[i][j] = rand() % 2;
- }
- }
- }
- /* Returns the number of alive neighbors of the cell at (row, col) */
- int count_alive_neighbors(int row, int col)
- {
- int count = 0;
- for (int i = row - 1; i <= row + 1; i++)
- {
- for (int j = col - 1; j <= col + 1; j++)
- {
- if (i == row && j == col)
- {
- continue;
- }
- if (i >= 0 && i < ROWS && j >= 0 && j < COLS && grid[i][j] == ALIVE)
- {
- count++;
- }
- }
- }
- return count;
- }
- /* Updates the grid to the next generation according to the rules of the Game of Life */
- void update_grid()
- {
- int new_grid[ROWS][COLS];
- for (int i = 0; i < ROWS; i++)
- {
- for (int j = 0; j < COLS; j++)
- {
- int alive_neighbors = count_alive_neighbors(i, j);
- if (grid[i][j] == ALIVE)
- {
- /* Any live cell with two or three live neighbors survives */
- if (alive_neighbors == 2 || alive_neighbors == 3)
- {
- new_grid[i][j] = ALIVE;
- }
- else
- {
- new_grid[i][j] = DEAD;
- }
- }
- else
- {
- /* Any dead cell with three live neighbors becomes a live cell */
- if (alive_neighbors == 3)
- {
- new_grid[i][j] = ALIVE;
- }
- else
- {
- new_grid[i][j] = DEAD;
- }
- }
- }
- }
- for (int i = 0; i < ROWS; i++)
- {
- for (int j = 0; j < COLS; j++)
- {
- grid[i][j] = new_grid[i][j];
- }
- }
- }
- /* Prints the grid to the console */
- void print_grid()
- {
- for (int i= 0; i < ROWS; i++)
- {
- for (int j = 0; j < COLS; j++)
- {
- if (grid[i][j] == ALIVE)
- {
- printf("*");
- }
- else
- {
- printf(".");
- }
- }
- printf("\n");
- }
- printf("\n");
- }
- int main()
- {
- init_grid();
- for (int i = 0; i < 10; i++)
- {
- print_grid();
- update_grid();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement