Untitled

 avatar
unknown
plain_text
a year ago
2.5 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define WIDTH 80
#define HEIGHT 20

void initialize(int field[HEIGHT][WIDTH]) {
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            field[y][x] = 0;
        }
    }
}

void display(const int field[HEIGHT][WIDTH]) {
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            printf("%c", field[y][x] ? 'O' : ' ');
        }
        printf("\n");
    }
}

void loadFromFile(const char* filename, int field[HEIGHT][WIDTH]) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file");
        exit(1);
    }
    int x, y;
    while (fscanf(file, "%d %d", &x, &y) != EOF) {
        if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
            field[y][x] = 1;
        }
    }
    fclose(file);
}

int getNeighborCount(int x, int y, const int field[HEIGHT][WIDTH]) {
    int count = 0;
    for (int dy = -1; dy <= 1; dy++) {
        for (int dx = -1; dx <= 1; dx++) {
            if (dx == 0 && dy == 0) continue; // Skip the cell itself
            int nx = x + dx, ny = y + dy;
            // Check boundaries
            if (nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT) {
                count += field[ny][nx];
            }
        }
    }
    return count;
}

void update(int field[HEIGHT][WIDTH]) {
    int newField[HEIGHT][WIDTH];
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            int neighbors = getNeighborCount(x, y, field);
            if (field[y][x]) {
                newField[y][x] = (neighbors == 2 || neighbors == 3) ? 1 : 0;
            } else {
                newField[y][x] = (neighbors == 3) ? 1 : 0;
            }
        }
    }
    memcpy(field, newField, sizeof(newField));
}

int main() {
    int field[HEIGHT][WIDTH];
    initialize(field);

    char filename[256];
    printf("Enter the filename with the initial configuration: ");
    scanf("%255s", filename);
    loadFromFile(filename, field);

    int speed = 200000; // Default speed
    printf("Enter simulation speed in microseconds (e.g., 200000): ");
    scanf("%d", &speed);

    while (1) {
        display(field);
        update(field);
        usleep(speed); // Control the speed of evolution
        // Clear the screen (Note: system calls are generally not recommended due to portability and security issues)
        system("clear"); // Use "cls" on Windows
    }

    return 0;
}
Leave a Comment