Files
game-of-life/src/game_core.c
2026-05-25 17:19:17 +02:00

82 lines
2.1 KiB
C

#include "game_core.h"
#include <stdlib.h>
const int directions[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},
{0, 1}, {1, -1}, {1, 0}, {1, 1}};
const uint32_t colors[2] = {BLACK, WHITE};
Board init_board(size_t width, size_t height, int random) {
Board board = {NULL, width, height};
board.pixels = malloc(height * sizeof(uint32_t *));
for (size_t y = 0; y < height; y++) {
board.pixels[y] = malloc(width * sizeof(uint32_t));
for (size_t x = 0; x < width; x++) {
if (random)
board.pixels[y][x] = colors[rand() % 2];
else
board.pixels[y][x] = BLACK;
}
}
return board;
}
void free_board(Board board) {
for (size_t y = 0; y < board.height; y++)
free(board.pixels[y]);
free(board.pixels);
}
Board copy_board(Board board) {
Board copy = init_board(board.width, board.height, 0);
for (size_t x = 0; x < board.width; x++) {
for (size_t y = 0; y < board.height; y++) {
copy.pixels[y][x] = board.pixels[y][x];
}
}
return copy;
}
void display_board(Board board) {
for (size_t y = 0; y < board.height; y++) {
for (size_t x = 0; x < board.width; x++) {
printf("%c", board.pixels[y][x] == BLACK ? ' ' : 'X');
}
puts("");
}
}
int count_adjacent(Board board, size_t x, size_t y) {
size_t i;
int w, h;
uint8_t count = 0;
for (i = 0; i < 8; i++) {
w = x + directions[i][1];
h = y + directions[i][0];
if (!((w < 0 || w >= (int)board.width) ||
(h < 0 || h >= (int)board.height)))
if (board.pixels[h][w] == WHITE)
count++;
}
return count;
}
Board process_game(Board board) {
Board new_board = copy_board(board);
size_t x, y;
uint8_t count = 0;
for (y = 0; y < board.height; y++) {
for (x = 0; x < board.width; x++) {
count = count_adjacent(board, x, y);
if (board.pixels[y][x] == BLACK && count == 3) {
new_board.pixels[y][x] = WHITE;
} else if (board.pixels[y][x] == WHITE && count != 2 && count != 3) {
new_board.pixels[y][x] = BLACK;
}
}
}
free_board(board);
return new_board;
}