about summary refs log blame commit diff stats
path: root/p9c/scratch/life.c
blob: e49bc6e6caa5fb83ca705a41f14b9ca302da2a43 (plain) (tree)







































































                                                                          
 
                                  

                           
                
                                          



                        
                     
     
               
 
#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);
}