From c2cc936d8890f20378d0ffc732b7f656237d2a1e Mon Sep 17 00:00:00 2001 From: verdant Date: Sun, 28 Jun 2026 02:53:07 +0800 Subject: Implement cell survival and neighbor detection logic --- main.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/main.c b/main.c index 0f311dc..90159f1 100644 --- a/main.c +++ b/main.c @@ -8,8 +8,10 @@ #include #include #include +#include +#include #include - +#include #define DEFAULT_WIDTH 900 #define DEFAULT_HEIGHT 900 #define COLOR 0x9AC2B3 @@ -28,6 +30,47 @@ typedef struct SDL_info { SDL_Event *e; } SDL_info; +void life(pedi *p) { + int **rd_only_matrix = (int **)malloc(sizeof(int *) * p->width); + for (int i = 0; i < p->width; i++) { + rd_only_matrix[i] = (int *)malloc(sizeof(int) * p->height); + memcpy(rd_only_matrix[i], p->matrix[i], sizeof(int) * p->height); + } + + int dirs[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, + {0, 1}, {1, -1}, {1, 0}, {1, 1}}; + + for (int i = 0; i < p->width; i++) { + for (int j = 0; j < p->height; j++) { + int live_nei = 0; + + for (int d = 0; d < 8; d++) { + int nx = i + dirs[d][0]; + int ny = j + dirs[d][1]; + + if (nx >= 0 && nx < p->width && ny >= 0 && ny < p->height) { + if (rd_only_matrix[nx][ny] == 1) { + live_nei++; + printf("(%d, %d)\n ", nx, ny); + } + } + } + + int cur_is_alive = rd_only_matrix[i][j]; + + if (cur_is_alive == 1) { + if (live_nei < 2 || live_nei > 3) { + p->matrix[i][j] = 0; + } + } else { + if (live_nei == 3) { + p->matrix[i][j] = 1; + } + } + } + } +} + void init_cell(pedi *p, SDL_Event e) { int mouse_x, mouse_y, cell_x, cell_y = 0; @@ -45,22 +88,19 @@ void init_cell(pedi *p, SDL_Event e) { } void game_update(SDL_Window *pwindow, pedi *p) { - if (!p) { - return; - } - SDL_UpdateWindowSurface(pwindow); } void draw_cells(pedi *p, SDL_Rect *cells, SDL_Surface *s) { int m = 0; - for (int i = 0; i < p->height; i++) { - for (int j = 0; j < p->width; j++) { + for (int i = 0; i < p->width; i++) { + for (int j = 0; j < p->height; j++) { cells[m].h = 10; cells[m].w = 10; + cells[m].x = i * 10; + cells[m].y = j * 10; + if (p->matrix[i][j] == 1) { - cells[m].x = i * 10; - cells[m].y = j * 10; SDL_FillRect(s, &cells[m], COLOR); } else { SDL_FillRect(s, &cells[m], EMPTY_COLOR); @@ -118,7 +158,14 @@ int main(int argc, char **argv) { cell_lock = 0; } } + if (!cell_lock) { + life(p); + } draw_cells(p, cells, psurface); + if (!cell_lock) { + struct timespec req = {0, 300000000}; // 0秒 + 500,000,000纳秒 + nanosleep(&req, NULL); + } game_update(pwindow, p); } -- cgit v1.2.3