aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorverdant <im@verdant.ee>2026-06-28 02:53:07 +0800
committerverdant <im@verdant.ee>2026-06-28 02:53:07 +0800
commitc2cc936d8890f20378d0ffc732b7f656237d2a1e (patch)
treea1c77ba2683ef2cb49ac57e06e08d7b35852935c
parentf26de8b3d1c82e3baffb362a2d92a8155eaaeddf (diff)
downloadcgol-c2cc936d8890f20378d0ffc732b7f656237d2a1e.tar.gz
cgol-c2cc936d8890f20378d0ffc732b7f656237d2a1e.zip
Implement cell survival and neighbor detection logic
-rw-r--r--main.c65
1 files 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 <SDL2/SDL_video.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
+#include <time.h>
#include <unistd.h>
-
+#include <wctype.h>
#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);
}