You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现康威生命游戏生成错误结构,求函数修正方案

康威生命游戏nextGen函数问题修复

问题核心

你的nextGen函数直接在原始矩阵上修改细胞状态,导致后续细胞的邻居统计使用了已经更新的值,违反了生命游戏“所有细胞同时完成状态更新”的规则,这就是输入横向三个活细胞时输出不符合预期的原因。

错误根源

代码中cells = matrice是引用赋值,而非创建新数组。修改cells[i,j]的同时也会改变原始的matrice,后续遍历到的细胞会读取到前面已经修改后的状态,导致邻居计数错误。

修复方案

创建原始矩阵的深拷贝作为新状态容器,所有状态计算基于原始矩阵,修改操作仅作用于拷贝的数组:

import numpy as np

def nextGen(matrice):
    # 创建原始矩阵的深拷贝,避免修改原数据
    cells = matrice.copy()
    size = np.shape(matrice)
    for i in range(1, size[0]-1):
        for j in range(1, size[1]-1):
            alive = matrice[i][j] > 0
            neighbours = 0    
            # 基于原始矩阵统计邻居数量
            neighbours += matrice[i-1,j+1]
            neighbours += matrice[i-1,j] 
            neighbours += matrice[i-1,j-1]
            neighbours += matrice[i,j+1] 
            neighbours += matrice[i,j-1]
            neighbours += matrice[i+1,j+1]
            neighbours += matrice[i+1,j] 
            neighbours += matrice[i+1,j-1]
            
            # 根据规则更新拷贝数组的状态
            if alive:
                if neighbours not in (2, 3):
                    cells[i,j] = 0
            else:
                if neighbours == 3:
                    cells[i,j] = 1
                    
    return cells

关键修改说明

  • 用matrice.copy()替换cells = matrice,确保新数组与原始数组完全独立
  • 所有邻居统计操作基于原始的matrice,保证每个细胞的状态判断都使用初始的全局状态
  • 状态更新仅作用于拷贝的cells数组,实现所有细胞的同步更新

现在测试输入横向三个活细胞的场景时,每个细胞的邻居计数都会基于初始状态计算,最终会生成预期的纵向三个活细胞结构。

内容的提问来源于stack exchange,提问作者EvilDumplings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:55:19