gol.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdint.h>
  4. #define UNIVERSE_SIZE_Y 12
  5. #define UNIVERSE_SIZE_X 24
  6. #define GLOBAL /**/
  7. #define ALIVE 1
  8. #define DEAD 0
  9. GLOBAL int8_t UNIVERSE[UNIVERSE_SIZE_Y][UNIVERSE_SIZE_X];
  10. int count_neighbours(int x, int y);
  11. void fill_universe(void);
  12. void print_universe(void);
  13. void next_generation(void);
  14. int main(int argc, char *argv[]){
  15. uint64_t gen = 1;
  16. fill_universe();
  17. //configuration
  18. UNIVERSE[4][5] = ALIVE;
  19. UNIVERSE[3][6] = ALIVE;
  20. UNIVERSE[4][6] = ALIVE;
  21. UNIVERSE[4][7] = ALIVE;
  22. print_universe();
  23. while (1){
  24. printf("Generation %li\n", gen);
  25. getchar();
  26. next_generation();
  27. gen++;
  28. print_universe();
  29. }
  30. return 0;
  31. }
  32. void next_generation(void){
  33. int8_t buffer[UNIVERSE_SIZE_Y][UNIVERSE_SIZE_X];
  34. int y, x, neighbours;
  35. for (y=0; y != UNIVERSE_SIZE_Y; y++)
  36. for (x=0; x != UNIVERSE_SIZE_X; x++)
  37. buffer[y][x] = DEAD;
  38. for (y=0; y != UNIVERSE_SIZE_Y; y++)
  39. for (x=0; x != UNIVERSE_SIZE_X; x++){
  40. neighbours = count_neighbours(y,x);
  41. if ((UNIVERSE[y][x] && neighbours == 2) || (UNIVERSE[y][x] && neighbours == 3))
  42. buffer[y][x] = ALIVE;
  43. else if ((UNIVERSE[y][x] && neighbours < 2) || (UNIVERSE[y][x] && neighbours > 3))
  44. buffer[y][x] = DEAD;
  45. if (!UNIVERSE[y][x] && neighbours == 3)
  46. buffer[y][x] = ALIVE;
  47. }
  48. for (y=0; y != UNIVERSE_SIZE_Y; y++)
  49. for (x=0; x != UNIVERSE_SIZE_X; x++)
  50. UNIVERSE[y][x] = buffer[y][x];
  51. }
  52. int count_neighbours(int y, int x){
  53. int i, j;
  54. int neighbours = 0;
  55. for (i=y-1;i<=y+1;i++)
  56. for (j=x-1;j<=x+1;j++){
  57. if (i < 0 || i >= UNIVERSE_SIZE_Y) continue;
  58. else if (j < 0 || j >= UNIVERSE_SIZE_X) continue;
  59. else if (UNIVERSE[i][j] == ALIVE) neighbours++;
  60. }
  61. if (UNIVERSE[y][x] == ALIVE) neighbours--;
  62. return neighbours;
  63. }
  64. void print_universe(void){
  65. int x,y;
  66. for (y=0; y != UNIVERSE_SIZE_Y; y++){
  67. for (x=0; x != UNIVERSE_SIZE_X; x++)
  68. printf("%i",UNIVERSE[y][x]);
  69. putchar('\n');
  70. }
  71. putchar('\n');
  72. }
  73. void fill_universe(void){
  74. int x,y;
  75. for (y=0; y != UNIVERSE_SIZE_Y; y++)
  76. for (x=0; x != UNIVERSE_SIZE_X; x++)
  77. UNIVERSE[y][x] = DEAD;
  78. }