about summary refs log tree commit diff stats
path: root/p9c/scratch/life.c
diff options
context:
space:
mode:
Diffstat (limited to 'p9c/scratch/life.c')
-rw-r--r--p9c/scratch/life.c80
1 files changed, 80 insertions, 0 deletions
diff --git a/p9c/scratch/life.c b/p9c/scratch/life.c
new file mode 100644
index 0000000..07948c8
--- /dev/null
+++ b/p9c/scratch/life.c
@@ -0,0 +1,80 @@
+#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() {
+    init_grid();
+    while (1) {
+        display_grid();
+        update_grid();
+        sleep(1);
+        system("clear");
+    }
+}