-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.c
64 lines (53 loc) · 1.91 KB
/
life.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdlib.h>
#include <time.h>
#include <SDL2/SDL.h>
#define SIZE 128
int main(int argc, char **argv) {
srand(time(NULL));
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow("Game of Life", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SIZE*2, SIZE*2, 0);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Event event;
int x, y, neighbors;
char table1[SIZE][SIZE] = {0};
char table2[SIZE][SIZE] = {0};
char (*cur)[SIZE] = table1;
char (*new)[SIZE] = table2;
char (*tmp)[SIZE] = NULL;
for (x=0; x<SIZE*SIZE; x++)
cur[rand()%SIZE][rand()%SIZE] = 1;
while(SDL_TRUE) {
for (x=0; x<SIZE; x++)
for (y=0; y<SIZE; y++) {
neighbors = 0;
if (x>0 && y>0 && x<SIZE-1 && y<SIZE-1)
neighbors = cur[x-1][y-1] + cur[x-1][y ] + cur[x-1][y+1] +
cur[x ][y-1] + cur[x ][y+1] +
cur[x+1][y-1] + cur[x+1][y ] + cur[x+1][y+1];
if ((cur[x][y]==0 && neighbors==3) ||
((cur[x][y]==1 && (neighbors==2 || neighbors==3)))) {
new[x][y] = 1;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
else {
new[x][y] = 0;
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
}
SDL_RenderDrawPoint(renderer, x*2 , y*2 );
SDL_RenderDrawPoint(renderer, x*2+1, y*2 );
SDL_RenderDrawPoint(renderer, x*2 , y*2+1);
SDL_RenderDrawPoint(renderer, x*2+1, y*2+1);
}
tmp = cur;
cur = new;
new = tmp;
SDL_RenderPresent(renderer);
if (SDL_PollEvent(&event) && (event.type==SDL_QUIT || event.type==SDL_KEYDOWN)) break;
else SDL_Delay(25);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
exit(EXIT_SUCCESS);
}