Conway's Game of Life Python实现邻居计数异常问题求助
康威生命游戏代码问题修复方案
你遇到的异常活细胞问题由三个核心错误导致,修复方案如下:
核心问题列表
- 同步更新规则错误:康威生命游戏要求所有细胞的状态更新完全基于上一轮结束后的全局状态,你当前代码中每计算完一个细胞的新状态就直接修改原网格,后续细胞统计邻居时会用到同轮刚更新的状态,导致计数完全不符合预期。
- 列表引用赋值错误:
start函数中oldWorld = world、newWorld = world属于引用赋值,两个变量实际指向同一个网格对象,修改任意一个都会同步影响另一个,没有实现新旧网格的隔离。 - 条件判断优先级错误:
birthsAndDeaths函数中elif(neighboursCount == 2 or neighboursCount == 3 and newWorld[row][column] == ALIVE)存在逻辑优先级问题,Python中and优先级高于or,该行代码实际等价于elif(neighboursCount == 2 or (neighboursCount == 3 and newWorld[row][column] == ALIVE)),也就是只要邻居数为2,不管细胞原本是死是活都会判定为存活,完全违反生命游戏规则。
修复代码
1. 先导入拷贝模块实现深拷贝
import copy
2. 修复核心逻辑代码
# 修正后的规则判断函数 def birthsAndDeaths(current_state, neighboursCount): if current_state == ALIVE: # 活细胞邻居数为2或3时存活,否则死亡 return ALIVE if neighboursCount in (2,3) else DEAD else: # 死细胞邻居数恰好为3时复活 return ALIVE if neighboursCount ==3 else DEAD # 修正后的轮次切换函数 def turnChanger(turn, oldWorld): turn = turn + 1 # 基于上一轮网格深拷贝得到新网格,所有计算基准为上一轮的oldWorld newWorld = copy.deepcopy(oldWorld) row = 0 while (row < SIZE): column = 0 while (column < SIZE): # 所有邻居计数都用上一轮的oldWorld,不要使用正在修改的newWorld neighboursCount = checkNeighbours(oldWorld, row, column) newWorld[row][column] = birthsAndDeaths(oldWorld[row][column], neighboursCount) column = column + 1 row = row + 1 return turn, newWorld # 修正后的启动函数 def start(): choice = selection() world = worldChooser(choice) turn = 0 oldWorld = copy.deepcopy(world) turn, newWorld = turnChanger(turn, oldWorld) display(turn, oldWorld, newWorld) return newWorld start()
3. 原有checkNeighbours邻居计数函数逻辑无需修改,只要传入上一轮的旧网格即可正确统计
内容的提问来源于stack exchange,提问作者joffer
相关产品推荐
相关产品推荐

