From 2cdaebd6cbb51e36682e1101f761e6e77f9d910b Mon Sep 17 00:00:00 2001 From: daniel fusser Date: Sun, 9 Oct 2022 21:44:25 +0200 Subject: [PATCH] initial commit --- gol.c | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 gol.c diff --git a/gol.c b/gol.c new file mode 100644 index 0000000..847a9fc --- /dev/null +++ b/gol.c @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include + +#define LEN_X 60 +#define LEN_Y 20 +#define PRINT_N 0 +#define CELL_CHAR "*" +#define R_FACT 10 +#define SLEEP 300 + +int generation; +int m[LEN_X][LEN_Y]; + +void clear() { printf("\e[1;1H\e[2J"); } + +void put_world() { + clear(); + printf("A GAME OF LIFE: #%i\n", generation); + putchar('+'); + for (int sep = 0; sep < LEN_X; sep++) putchar('-'); + printf("+\n"); + for (int y = 0; y < LEN_Y; y++) { + putchar('|'); + for (int x = 0; x < LEN_X; x++) + if (m[x][y] > 0) + if(PRINT_N) printf("%i", m[x][y]); + else printf("%s", CELL_CHAR); + else + putchar(' '); + printf("|\n"); + } + putchar('+'); + for (int sep = 0; sep < LEN_X; sep++) putchar('-'); + printf("+\n"); + usleep(10000 * SLEEP); +} + +void next_gen() { + int m_ngen[LEN_X][LEN_Y]; + for (int x = 0; x < LEN_X; x++) { + for (int y = 0; y < LEN_Y; y++) { + int n = 0; + if (y > 0 && m[x][y - 1] > 0) n++; // n + if (x < LEN_X && y > 0 && m[x + 1][y - 1] > 0) n++; // ne + if (x < LEN_X && m[x + 1][y] > 0) n++; // e + if (x > 0 && y < LEN_Y && m[x - 1][y + 1] > 0) n++; // se + if (y < LEN_Y && m[x][y + 1] > 0) n++; // s + if (y < LEN_Y && x < LEN_X && m[x + 1][y + 1] > 0) n++; // sw + if (x > 0 && m[x - 1][y] > 0) n++; // w + if (x > 0 && y > 0 && m[x - 1][y - 1] > 0) n++; // nw + + if (m[x][y] > 0) + m_ngen[x][y] = (n < 2 || n > 3) ? 0 : n; + else + m_ngen[x][y] = (n == 3) ? n : 0; + } + } + memcpy(m, m_ngen, sizeof(m_ngen)); +} + +void randomize(int fact) { + srand(time(NULL)); + for (int x = 0; x <= LEN_X; x++) { + for (int y = 0; y <= LEN_Y; y++) { + int r = rand() % fact; + m[x][y] = (r == 1) ? 1 : 0; + } + } +} + +void init_world() { + clear(); + + randomize(R_FACT); + + /* int maxgens = 2000; */ + generation = 1; + /* while (generation <= maxgens) { */ + while (1) { + put_world(); + next_gen(); + generation++; + } +} + +int main() { + init_world(); + return 0; +}