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

Conway's Game of Life(康威生命游戏)Python实现细胞无法死亡求助

问题定位

你的代码存在两处核心错误:

  • 状态更新逻辑误用了相等判断符==代替赋值符=
  • time.sleep(1)的缩进位置错误,导致运行时序不符合预期

错误详情

你在更新next数组的后两个分支里,用了==(判断两个值是否相等),而没有用=(给变量赋值):

# 错误写法
elif current[x][y] == " " and neighbors == 3:
    next[x][y] == "#" # 此处为相等判断,不会修改变量值
else:
    next[x][y] == " " # 此处为相等判断,不会修改变量值

这就导致只有原本存活、且符合存活条件(邻居数为2或3)的细胞会被正确赋值为#,其余所有情况都不会修改next数组的原有值,自然就出现了活细胞永远不会被改为空格、也就是永不死亡的问题。

另外time.sleep(1)现在缩进在x轴循环内部,每处理完1列就会暂停1秒,正确应该放在所有状态更新逻辑结束后,也就是两层遍历x、y的for循环外面,每完成一代更新再暂停。
额外提示:next是Python内置函数名,不建议用作自定义变量名,避免后续调用内置函数时出现异常。

修正后完整代码

import random, time, copy

height = 10
width = 10
next_state = []

for x in range(width):
    column = []
    for y in range(height):
        if random.randint(0, 1) == 0:
            column.append(" ")
        else:
            column.append("#")
    next_state.append(column)

while True:
    print("\n\n\n\n")
    current = copy.deepcopy(next_state)

    # 打印当前世代
    for y in range(height):
        for x in range(width):
            print(current[x][y], end=" ")
        print()
    
    # 计算下一代状态
    for x in range(width):
        for y in range(height):
            leftco = (x - 1) % width
            rightco = (x + 1) % width
            botco = (y - 1) % height
            topco = (y + 1) % height

            neighbors = 0
            if current[leftco][topco] == "#":
                neighbors += 1
            if current[leftco][y] == "#":
                neighbors += 1
            if current[leftco][botco] == "#":
                neighbors += 1
            if current[x][topco] == "#":
                neighbors += 1
            if current[x][botco] == "#":
                neighbors += 1
            if current[rightco][topco] == "#":
                neighbors += 1
            if current[rightco][y] == "#":
                neighbors += 1
            if current[rightco][botco] == "#":
                neighbors += 1
                
            if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
                next_state[x][y] = "#"
            elif current[x][y] == " " and neighbors == 3:
                next_state[x][y] = "#"
            else:
                next_state[x][y] = " "
    # 每完成一代更新暂停1秒
    time.sleep(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:36:03