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

如何避免Python实现康威生命游戏时列表越界访问?

解决康威生命游戏边界邻接单元格越界问题

你的核心问题是直接访问x-1、x+1、y-1、y+1时,未判断这些坐标是否在网格合法范围内(0 ≤ 横坐标 < WIDTH,0 ≤ 纵坐标 < HEIGHT),导致索引越界报错。以下是两种实用的解决思路:

方法一:逐个判断邻接坐标合法性

在访问每个邻接单元格前,先检查坐标是否在网格范围内,仅统计合法坐标的单元格状态:

for x in range(WIDTH):
    for y in range(HEIGHT):
        living_neighbors = 0  # 内层循环初始化,避免累计上一个单元格的统计值
        
        # 左上邻接
        if x - 1 >= 0 and y - 1 >= 0:
            if currentCells[x-1][y-1] == '#':
                living_neighbors += 1
        # 正上邻接
        if y - 1 >= 0:
            if currentCells[x][y-1] == '#':
                living_neighbors += 1
        # 右上邻接
        if x + 1 < WIDTH and y - 1 >= 0:
            if currentCells[x+1][y-1] == '#':
                living_neighbors += 1
        # 左邻接
        if x - 1 >= 0:
            if currentCells[x-1][y] == '#':
                living_neighbors += 1
        # 右邻接
        if x + 1 < WIDTH:
            if currentCells[x+1][y] == '#':
                living_neighbors += 1
        # 左下邻接
        if x - 1 >= 0 and y + 1 < HEIGHT:
            if currentCells[x-1][y+1] == '#':
                living_neighbors += 1
        # 正下邻接
        if y + 1 < HEIGHT:
            if currentCells[x][y+1] == '#':
                living_neighbors += 1
        # 右下邻接
        if x + 1 < WIDTH and y + 1 < HEIGHT:
            if currentCells[x+1][y+1] == '#':
                living_neighbors += 1
        
        # 此处添加根据 living_neighbors 更新 nextCells 的逻辑

方法二:预定义偏移量循环遍历(更简洁)

先定义8个邻接方向的坐标偏移量,再循环遍历每个偏移量并判断合法性,避免重复编写判断逻辑:

# 定义8个邻接方向的坐标偏移量
neighbor_offsets = [(-1, -1), (0, -1), (1, -1),
                    (-1, 0),          (1, 0),
                    (-1, 1),  (0, 1), (1, 1)]

for x in range(WIDTH):
    for y in range(HEIGHT):
        living_neighbors = 0
        
        for dx, dy in neighbor_offsets:
            nx = x + dx
            ny = y + dy
            # 检查邻接坐标是否在网格范围内
            if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
                if currentCells[nx][ny] == '#':
                    living_neighbors += 1
        
        # 此处添加根据 living_neighbors 更新 nextCells 的逻辑

额外注意事项

  • 变量名遵循Python规范,用小写字母加下划线(如living_neighbors),提升代码可读性。
  • living_neighbors必须放在内层循环(y的循环)中初始化,否则会累计之前单元格的统计值,导致计算错误(你原代码将其放在外层循环外,这是另一个潜在问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:13:27