#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define WIDTH 40
#define HEIGHT 20
int field[HEIGHT][WIDTH];
int next[HEIGHT][WIDTH];
void init_field() {
srand(time(NULL));
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
field[y][x] = rand() % 2;
}
}
}
int count_neighbors(int y, int x) {
int count = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dy == 0 && dx == 0) continue;
int ny = y + dy;
int nx = x + dx;
if (ny >= 0 && ny < HEIGHT && nx >= 0 && nx < WIDTH) {
count += field[ny][nx];
}
}
}
return count;
}
void update_field() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int neighbors = count_neighbors(y, x);
if (field[y][x] == 1) {
if (neighbors < 2 || neighbors > 3)
next[y][x] = 0;
else
next[y][x] = 1;
} else {
if (neighbors == 3)
next[y][x] = 1;
else
next[y][x] = 0;
}
}
}
// копируем next -> field
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
field[y][x] = next[y][x];
}
}
}
void draw_field() {
clear();
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (field[y][x])
mvprintw(y, x, "O");
else
mvprintw(y, x, ".");
}
}
refresh();
}
int main() {
initscr();
noecho();
curs_set(FALSE);
init_field();
while (1) {
draw_field();
update_field();
usleep(200000); // 0.2 сек
}
endwin();
return 0;
}