Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
2.1 kB
1
Indexable
Never
#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 load_population_from_file(int field[HEIGHT][WIDTH], const char* filename) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        perror("Ошибка при открытии файла");
        exit(EXIT_FAILURE);
    }

    char line[WIDTH + 2]; // +2 для \n и \0
    for (int y = 0; y < HEIGHT && fgets(line, sizeof(line), file) != NULL; y++) {
        for (int x = 0; x < WIDTH && line[x] != '\n' && line[x] != '\0'; x++) {
            field[y][x] = (line[x] == 'O') ? 1 : 0;
        }
    }

    fclose(file);
}

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;
            count += field[ny][nx];
        }
    }
    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);
            new_field[y][x] = (alive_neighbors == 3) || (field[y][x] && alive_neighbors == 2);
        }
    }
    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] = {0};
    load_population_from_file(field, "population.txt");

    while (1) {
        render(field);
        update(field);
        wait(0.1); // Скорость обновления поля
    }

    return 0;
}
Leave a Comment