为什么我的康威生命游戏(Conway's Game of Life)更新出现错误?
提问内容
我目前正在改编electronut的《A simple Python matplotlib implementation of Conway's Game of Life》,移除numpy模块依赖以运行,仅作个人娱乐与练习用途。我认为我遇到了其他讨论康威生命游戏实现问题的帖子中描述的故障,我猜测是细胞在预期时间前就更新了,但我已经在拷贝的网格上更新细胞、且在独立的函数中完成拷贝网格的替换,不理解为什么会出现这个问题。非常感谢任何帮助,现阶段我更想知道问题的成因而非仅解决故障。我的代码如下:
# 基于electronut的《A simple Python matplotlib implementation of Conway's Game of Life》改编 import matplotlib.pyplot as plt import matplotlib.animation as animation import random as rnd # 初始化参数 cellCount = 100 ALIVE = 255 DEAD = 0 # 细胞可能的状态 states = [ALIVE, DEAD] # 生成初始网格 grid = [[rnd.choice(states) for i in range(cellCount)] for j in range(cellCount)] # 返回下一代的新网格 def nextGen(): global grid newGrid = grid.copy() for i in range(cellCount): for j in range(cellCount): # 计算存活邻居总数 total = (grid[(i-1)%cellCount][j] + grid[(i+1)%cellCount][j] + grid[i][(j-1)%cellCount] + grid[i][(j+1)%cellCount] + grid[(i-1)%cellCount][(j-1)%cellCount] + grid[(i+1)%cellCount][(j+1)%cellCount] + grid[(i+1)%cellCount][(j-1)%cellCount] + grid[(i-1)%cellCount][(j+1)%cellCount])/255 if grid[i][j] == ALIVE: if (total < 2) or (total > 3): newGrid[i][j] = DEAD else: if total == 3: newGrid[i][j] = ALIVE return newGrid # 用下一代网格更新全局网格 def update(data): global grid new = nextGen() mat.set_data(new) grid = new return [new] # matplotlib渲染逻辑 fig, ax = plt.subplots() mat = ax.matshow(grid) ani = animation.FuncAnimation(fig, update, interval=100, save_count=50) plt.show()
成因分析
核心出在二维列表的浅拷贝逻辑错误。
你代码里的grid是嵌套结构的二维列表,Python内置的列表copy()方法仅支持浅拷贝:只会复制外层的列表容器,内层存储每一行细胞状态的子列表,和原grid的子列表指向的是同一块内存地址。
这就导致你修改newGrid[i][j]的数值时,原grid对应位置的数值也会同步改变。后续循环计算其他细胞的邻居存活数时,用到的grid已经不是当前世代初始的完整状态,而是被前面的修改提前更新过的状态,自然就会出现规则执行错误的情况。
你可以自己做个简单验证:在nextGen函数中newGrid = grid.copy()这行之后加一行打印print(newGrid[0] is grid[0]),输出会是True,直接证明两行的子列表是同一个引用,修改会双向同步。
要修复问题只需要把浅拷贝改成逐行深拷贝即可,把newGrid = grid.copy()替换为newGrid = [row.copy() for row in grid],逐行拷贝内层的每一个子列表,新旧网格就完全独立,不会互相干扰。
内容的提问来源于stack exchange,提问作者ColaTownKid

