blob: e49bc6e6caa5fb83ca705a41f14b9ca302da2a43 (
plain) (
blame)
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
79
80
81
82
83
84
85
86
|
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <event.h>
#define WIDTH 80
#define HEIGHT 24
int grid[WIDTH][HEIGHT];
int temp_grid[WIDTH][HEIGHT];
void init_grid() {
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
grid[x][y] = nrand(2); /* Randomly initialize cells, 0 or 1 */
}
}
}
int count_neighbors(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
int nx = (x + i + WIDTH) % WIDTH;
int ny = (y + j + HEIGHT) % HEIGHT;
count += grid[nx][ny];
}
}
return count;
}
void update_grid() {
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
int alive_neighbors = count_neighbors(x, y);
if (grid[x][y] == 1) {
if (alive_neighbors < 2 || alive_neighbors > 3) {
temp_grid[x][y] = 0; /* Cell dead */
} else {
temp_grid[x][y] = 1; /* Cell lives on! */
}
} else {
if (alive_neighbors == 3) {
temp_grid[x][y] = 1; /* Cell born */
} else {
temp_grid[x][y] = 0; /* Cell still dead */
}
}
}
}
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
grid[x][y] = temp_grid[x][y];
}
}
}
void display_grid() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (grid[x][y] == 1) {
print("*");
} else {
print(" ");
}
}
print("\n");
}
}
void main() {
int max_generations = 500;
int generation = 0;
init_grid();
while (generation < max_generations) {
display_grid();
update_grid();
sleep(1);
system("clear");
generation++;
}
exits(nil);
}
|