康威生命遊戲 是細胞自動機的經典案例:二維網格上,每個細胞依據鄰居存活數(8鄰域)在下一代生死演化。本文提供基於 Windows EasyX 圖形庫的完整可視化實現,支援速度調節、暫停/單步、預設圖樣/隨機初始化、邊界環狀處理。
#include
#include
#include
#define WORLD_W 100
#define WORLD_H 100
#define CELL_SIZE 4
// 世界狀態:0=死,1=活。邊界各加1圈作哨兵,避免越界判斷
__int8 world[WORLD_H + 2][WORLD_W + 2] = {0};
IMAGE imgLive, imgDead; // 活/死細胞圖塊
Evolution()
void Evolution() {
__int8 next[WORLD_H + 2][WORLD_W + 2] = {0};
for (int y = 1; y <= WORLD_H; y++) {
for (int x = 1; x <= WORLD_W; x++) {
// 計算 8 鄰域存活數
int sum = world[y-1][x-1] + world[y-1][x] + world[y-1][x+1]
+ world[y][x-1] + world[y][x+1]
+ world[y+1][x-1] + world[y+1][x] + world[y+1][x+1];
// 生命規則
if (sum == 3) next[y][x] = 1; // 誕生
else if (sum == 2) next[y][x] = world[y][x]; // 保持
else next[y][x] = 0; // 死亡
}
}
memcpy(world, next, sizeof(world)); // 更新世代
}
PaintWorld()
void PaintWorld() {
for (int y = 1; y <= WORLD_H; y++)
for (int x = 1; x <= WORLD_W; x++)
putimage(16 + x * CELL_SIZE, 56 + y * CELL_SIZE,
world[y][x] ? &imgLive : &imgDead);
}
void Init() {
initgraph(640, 480);
srand((unsigned)time(NULL));
// 建立 4x4 像素圖塊
Resize(&imgLive, CELL_SIZE, CELL_SIZE);
SetWorkingImage(&imgLive);
setcolor(GREEN); setfillstyle(GREEN); fillellipse(0,0,3,3); // 綠圓=活
SetWorkingImage(&imgDead);
setcolor(DARKGRAY); rectangle(1,1,2,2); // 灰框=死
SetWorkingImage(NULL);
// 文字說明、預設圖樣...
SquareWorld(); // 預設方形邊框圖樣
}
int main() {
Init();
int speed = 500; // ms/幀
while (1) {
if (kbhit() || speed == 900) { // 900=單步模式
char c = getch();
if (c == ' ') c = getch(); // 空格暫停/繼續
if (c >= '0' && c <= '9') speed = ('9' - c) * 100; // 0-9調速
switch (c) {
case 's': case 'S': SquareWorld(); break; // 方形邊框
case 'r': case 'R': RandWorld(); break; // 隨機
case 27: goto END; // ESC退出
}
}
Evolution();
PaintWorld();
if (speed != 900) Sleep(speed);
}
END:
closegraph();
return 0;
}
void SquareWorld() { // 邊框存活
memset(world, 0, sizeof(world));
for (int x = 1; x <= WORLD_W; x++) world[x][1] = world[x][WORLD_H] = 1;
for (int y = 1; y <= WORLD_H; y++) world[1][y] = world[WORLD_W][y] = 1;
}
void RandWorld() { // 50% 隨機
for (int x = 1; x <= WORLD_W; x++)
for (int y = 1; y <= WORLD_H; y++)
world[x][y] = rand() % 2;
}

綠色圓點為存活細胞,灰色方框為空白。隨機初始化下可觀察到滑翔機、震盪子、發射器等經典結構自發演化。
(x+WORLD_W)%WORLD_W 實現環面拓撲。生命遊戲以極簡規則產生無窮複雜行為,是細胞自動機、複雜系統、涌現現象的完美切入點。本 EasyX 版本代碼精簡、視覺直觀,適合教學演示、算法實驗、課程設計。歡迎 Fork 擴展!