93 lines
2.1 KiB
C
93 lines
2.1 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <time.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
#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;
|
||
|
}
|