game-of-life

Conway's Game of Life
git clone git://src.adamsgaard.dk/game-of-life # fast
git clone https://src.adamsgaard.dk/game-of-life.git # slow
Log | Files | Refs | README | LICENSE Back to index

main.c (2028B)


      1 #include <stdio.h>
      2 #include <unistd.h>
      3 #include <stdlib.h>
      4 #include <ctype.h>
      5 #include "utility.h"
      6 #include "rules.h"
      7 
      8 #define GOLVERSION 0.1
      9 
     10 /*#define SHOW_NEIGHBORS*/
     11 
     12 int main(int argc, char **argv)
     13 {
     14     int **cells;
     15     int **neighbors;
     16     int nx = 80;
     17     int ny = 30;
     18     int c;
     19     unsigned int it = 0;
     20     int world_is_dead = 0;
     21 
     22     while ((c = getopt(argc, argv, "hv")) != -1)
     23         switch (c)
     24     {
     25         case 'h':
     26             printf("usage: %s [OPTIONS] nx ny\n"
     27                     "where nx and ny are the grid dimensions.\n"
     28                     "-h\tDisplay help\n"
     29                     "-v\tDisplay version information\n", argv[0]);
     30             return 0;
     31             break;
     32         case 'v':
     33             printf("%s: Conway's Game of Life, version %.1f\n"
     34                     "Written by Anders Damsgaard, "
     35                     "https://github.com/anders-dc/game-of-life\n", argv[0], GOLVERSION);
     36             return 0;
     37             break;
     38         case '?':
     39             if (isprint(optopt))
     40                 fprintf(stderr, "Unknown option `-%c`.\n", optopt);
     41             else
     42                 fprintf(stderr, "Unknown option character `\\x%x`.\n", optopt);
     43             return 1;
     44 
     45         default:
     46             abort();
     47     }
     48 
     49     if (optind == argc - 2) {
     50         nx = atoi(argv[optind]);
     51         ny = atoi(argv[optind + 1]);
     52     } 
     53 
     54     printf("Grid dimensions: %dx%d\n", nx, ny);
     55 
     56     allocate_matrix(&cells, nx, ny);
     57     allocate_matrix(&neighbors, nx, ny);
     58 
     59     random_population(cells, nx, ny, 0.5);
     60 
     61     print_cell_matrix(cells, nx, ny);
     62 
     63     while (world_is_dead == 0) {
     64 
     65         world_is_dead = find_neighbor_count(cells, neighbors, nx, ny);
     66         cell_transitions(cells, neighbors, nx, ny);
     67 
     68         printf("\n%d. generation (end with Ctrl-C)\n", it);
     69 #ifdef SHOW_NEIGHBORS
     70         print_matrix("neighbors", neighbors, nx, ny);
     71 #endif
     72         print_cell_matrix(cells, nx, ny);
     73 
     74         usleep(5e5);
     75 
     76         it++;
     77     }
     78 
     79     free_matrix(&cells, nx);
     80     free_matrix(&neighbors, nx);
     81 
     82     return 0;
     83 }