Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define WIDTH 30
- #define HEIGHT 20
- int
- count_neighbour(int **grid, size_t h, size_t w)
- {
- int c = 0;
- int i, j;
- for (i = -1; i < 2; i++) {
- for (j = -1; j < 2; j++) {
- if ((i == 0 && j == 0) || (h == 0 && i == -1)
- || (w == 0 && j == -1) || (h == HEIGHT-1 && i == 1)
- || (w == WIDTH-1 && j == 1))
- continue;
- c += (grid[h+i][w+j] == 1 || grid[h+i][w+j] == 2);
- }
- }
- return c;
- }
- void
- progress(int **grid)
- {
- size_t h, w;
- int c;
- for (h = 0; h < HEIGHT; h++) {
- for (w = 0; w < WIDTH; w++) {
- c = count_neighbour(grid, h, w);
- if (grid[h][w] == 0 && c == 3)
- grid[h][w] = 3;
- else if (grid[h][w] == 1 && !(c == 2 || c == 3))
- grid[h][w] = 2;
- }
- }
- for (h = 0; h < HEIGHT; h++)
- for (w = 0; w < WIDTH; w++)
- grid[h][w] &= 1;
- }
- void
- print_grid(int **grid)
- {
- size_t h, w;
- for (h = 0; h < HEIGHT; h++) {
- for (w = 0; w < WIDTH; w++)
- printf("%c", (grid[h][w] ? 'o' : ' '));
- printf("\n");
- }
- printf("------------------------------\n");
- }
- int
- main(void)
- {
- int **grid = malloc(sizeof(int) * HEIGHT);
- for (int i = 0; i < HEIGHT; i++) {
- grid[i] = malloc(sizeof(int) * WIDTH);
- for (int j = 0; j < WIDTH; j++)
- grid[i][j] = arc4random_uniform(2);
- }
- print_grid(grid);
- for (;;) {
- getchar();
- progress(grid);
- print_grid(grid);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement