生命游戏C++实现中邻域细胞计数函数修复咨询
修复生命游戏的neighborhood函数及逻辑问题
核心问题分析
你的代码主要有三个致命问题导致neighborhood统计错误,同时破坏了生命游戏的规则:
- 使用全局变量numSys统计邻居数,多细胞处理时会被覆盖,导致统计值混乱。
- 直接修改原地图:在遍历统计邻居的过程中修改细胞状态,后续细胞的统计会用到已经修改后的状态,完全违背生命游戏"所有细胞同步更新"的规则。
- neighborhood函数内有重复的跳过自身判断,逻辑冗余且可能引发混淆。
- 存在拼写错误、无效循环等小问题。
修复后的完整代码
#include <iostream> #include <windows.h> #include <cstdlib> using namespace std; const int mapSize = 10; int isLife = 0; void ShowMap(int map[mapSize][mapSize], int size); void Check(int map[mapSize][mapSize], int size); int neighborhood(int map[mapSize][mapSize], int x, int y); int main() { // 初始化地图,竖线图案 int map[mapSize][mapSize] = { {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} }; while(1) { ShowMap(map, mapSize); Check(map, mapSize); Sleep(1000); system("cls"); // 清屏,让动画更整洁 } } void ShowMap(int map[mapSize][mapSize], int size) { cout << endl; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { cout << (map[i][j] ? "* " : ". "); // 用*表示存活,.表示死亡,更直观 } cout << endl; } cout << "当前存活细胞数: " << isLife << endl; } void Check(int map[mapSize][mapSize], int size) { isLife = 0; int tempMap[mapSize][mapSize]; // 创建临时地图存储新状态 // 第一步:遍历所有细胞,计算新状态并存入临时地图 for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { int neighborCount = neighborhood(map, i, j); // 应用生命游戏规则 if(map[i][j] == 1) { tempMap[i][j] = (neighborCount == 2 || neighborCount == 3) ? 1 : 0; } else { tempMap[i][j] = (neighborCount == 3) ? 1 : 0; // 死亡细胞复活的条件是恰好3个邻居 } if(tempMap[i][j] == 1) { isLife++; } } } // 第二步:将临时地图的状态同步回原地图 for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { map[i][j] = tempMap[i][j]; } } } int neighborhood(int map[mapSize][mapSize], int x, int y) { int count = 0; // 用局部变量统计,避免全局变量污染 for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { // 跳过自身 if(i == 0 && j == 0) { continue; } int newX = x + i; int newY = y + j; // 检查坐标是否在地图范围内 if(newX >= 0 && newX < mapSize && newY >= 0 && newY < mapSize) { if(map[newX][newY] == 1) { count++; } } } } return count; }
关键修复点说明
- 移除全局变量numSys:改用neighborhood函数内的局部变量
count统计邻居数,函数返回该值,避免多细胞处理时的变量覆盖问题。 - 添加临时地图:所有细胞的新状态先计算并存入
tempMap,全部计算完成后再同步到原地图,保证所有细胞基于同一时刻的状态更新,符合生命游戏规则。 - 修正复活规则:死亡细胞复活的条件是恰好3个存活邻居,原代码错误写成了2或3,这是规则性错误。
- 清理冗余逻辑:删除neighborhood函数中重复的跳过自身判断,只保留
i==0 && j==0的判断。 - 修正无效循环:删除main函数中
for(int i = 0;i > mapSize; i++)这个永远不会执行的循环,避免越界风险。 - 优化显示效果:用
*和.代替0和1,让细胞状态更直观,添加清屏操作让动画流畅。 - 修正拼写错误:把Check函数中的
ifLife改为isLife。
内容的提问来源于stack exchange,提问作者TheSlash
相关产品推荐
相关产品推荐

