Untitled
unknown
plain_text
2 years ago
1.9 kB
7
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WIDTH 80
#define HEIGHT 25
void clear_terminal() {
printf("\033[H\033[J");
}
void wait(float seconds) {
usleep((int)(seconds * 1000000));
}
void init_field(int field[HEIGHT][WIDTH]) {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
field[y][x] = rand() % 2;
}
}
}
void render(int field[HEIGHT][WIDTH]) {
clear_terminal();
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
printf("%c", field[y][x] ? '*' : ' ');
}
printf("\n");
}
}
int count_neighbors(int field[HEIGHT][WIDTH], int x, int y) {
int count = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + WIDTH) % WIDTH;
int ny = (y + dy + HEIGHT) % HEIGHT;
if (field[ny][nx]) count++;
}
}
return count;
}
void update(int field[HEIGHT][WIDTH]) {
int new_field[HEIGHT][WIDTH];
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int alive_neighbors = count_neighbors(field, x, y);
if (field[y][x]) {
new_field[y][x] = (alive_neighbors == 2 || alive_neighbors == 3);
} else {
new_field[y][x] = (alive_neighbors == 3);
}
}
}
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
field[y][x] = new_field[y][x];
}
}
}
int main() {
int field[HEIGHT][WIDTH];
srand(time(NULL));
init_field(field);
while (1) {
render(field);
update(field);
wait(0.1); // Скорость обновления поля
}
return 0;
}
Editor is loading...
Leave a Comment