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

《Python编程快速上手》Conway's Game of Life代码排查与解析

康威生命游戏Python代码问题排查与逻辑解析

代码存在的问题

这段代码无法正常运行、输出不符合预期的核心原因是Python缩进错误,具体有两处会直接触发运行报错:

  • 统计左上角邻居存活状态的if判断分支下,numNeighbors += 1语句没有缩进,和if判断处于同一层级,违反Python缩进规则,直接抛出IndentationError。
  • 主循环while True行前存在多余前置空格,和上层初始化代码的缩进层级不匹配,同样会触发缩进报错。

其余代码逻辑本身符合康威生命游戏的规则设计,修正缩进后即可正常运行。

核心代码逻辑解析

代码整体采用列优先的二维列表存储网格状态,实现逻辑分为三部分:

  • 初始化阶段:定义网格宽度为60、高度为20,随机为每个格子分配初始状态,#代表存活细胞,空格代表死亡细胞。
  • 渲染阶段:每轮迭代先打印多个换行分隔前后代画面,深拷贝当前代细胞状态避免计算过程中污染原始数据,按行优先顺序遍历打印网格,输出可视化的细胞状态。
  • 演化计算阶段:
    • 用取模运算处理边界坐标,实现环形边界(网格对边相连,不存在越界问题)
    • 统计每个细胞周围8个相邻格子的存活细胞数量
    • 严格按照康威生命游戏规则更新下一代状态:存活细胞周围有2-3个邻居则存活,否则死亡;死亡细胞周围恰好3个邻居则复活,否则保持死亡
    • 每轮演化后暂停1秒,降低画面切换速度方便观察

修正后可运行代码

# Conway's Game of Life
import random, time, copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
    column = [] # Create a new column.
    for y in range(HEIGHT):
        if random.randint(0, 1) == 0:
            column.append('#') # Add a living cell.
        else:
            column.append(' ') # Add a dead cell.
    nextCells.append(column) # nextCells is a list of column lists.

while True: # Main program loop.
    print('\n\n\n\n\n') # Separate each step with newlines.
    currentCells = copy.deepcopy(nextCells)
    # Print currentCells on the screen:
    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y], end='') # Print the # or space.
        print() # Print a newline at the end of the row.
    # Calculate the next step's cells based on current step's cells:
    for x in range(WIDTH):
        for y in range(HEIGHT):
            # Get neighboring coordinates:
            # `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1
            leftCoord = (x - 1) % WIDTH
            rightCoord = (x + 1) % WIDTH
            aboveCoord = (y - 1) % HEIGHT
            belowCoord = (y + 1) % HEIGHT
            # Count number of living neighbors:
            numNeighbors = 0
            if currentCells[leftCoord][aboveCoord] == '#':
                numNeighbors += 1 # Top-left neighbor is alive.
            if currentCells[x][aboveCoord] == '#':
                numNeighbors += 1 # Top neighbor is alive.
            if currentCells[rightCoord][aboveCoord] == '#':
                numNeighbors += 1 # Top-right neighbor is alive.
            if currentCells[leftCoord][y] == '#':
                numNeighbors += 1 # Left neighbor is alive.
            if currentCells[rightCoord][y] == '#':
                numNeighbors += 1 # Right neighbor is alive.
            if currentCells[leftCoord][belowCoord] == '#':
                numNeighbors += 1 # Bottom-left neighbor is alive.
            if currentCells[x][belowCoord] == '#':
                numNeighbors += 1 # Bottom neighbor is alive.
            if currentCells[rightCoord][belowCoord] == '#':
                numNeighbors += 1 # Bottom-right neighbor is alive.
            # Set cell based on Conway's Game of Life rules:
            if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
                # Living cells with 2 or 3 neighbors stay alive:
                nextCells[x][y] = '#'
            elif currentCells[x][y] == ' ' and numNeighbors == 3:
                # Dead cells with 3 neighbors become alive:
                nextCells[x][y] = '#'
            else:
                # Everything else dies or stays dead:
                nextCells[x][y] = ' '
    time.sleep(1) # Add a 1-second pause to reduce flickering.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:45:32