-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.c
78 lines (64 loc) · 1.33 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "output.h"
#define _DEFAULT_SOURCE /* for usleep */
#include <unistd.h> /* usleep */
#include <time.h> /* time */
#include <stdlib.h> /* rand, srand */
void step(void);
int neighbors(int x, int y, char old[Y][X]);
char field[Y][X];
int main()
{
init();
srand(time(NULL));
for(int i = 0; i < Y; i++)
for(int j = 0; j < X; j++)
field[i][j] = (rand()%ONEIN==0)?ALIVE:DEAD;
//field[i][j] = DEAD;
/* glider */
/*
field[2][2] = ALIVE;
field[2][3] = ALIVE;
field[2][4] = ALIVE;
field[3][4] = ALIVE;
field[4][2] = ALIVE;
*/
/* main loop */
while(1) {
if(process_input() == MSG_EXIT)
break;
output(field);
step();
usleep(DELAY*1000);
}
cleanup();
return 0;
}
void step()
{
char old[Y][X];
for(int i = 0; i < Y; i++)
for(int j = 0; j < X; j++)
old[i][j]=field[i][j];
for(int i = 0; i < Y; i++) {
for(int j = 0; j < X; j++) {
int neigh = neighbors(i,j,old);
if(old[i][j]==DEAD) { /* dead cell */
if(neigh==3)
field[i][j] = ALIVE;
} else { /* live cell */
if(neigh != 2 && neigh != 3)
field[i][j] = DEAD;
}
}
}
}
/* FIYME maybe make old global */
int neighbors(int x, int y, char old[Y][X])
{
int ret = old[x][y]==ALIVE?-1:0;
for(int i = -1; i < 2; i++)
for(int j = -1; j < 2; j++)
if(old[(x+i+Y)%Y][(y+j+X)%X]==ALIVE)
ret++;
return ret;
}