在实现如康威生命游戏这类基于网格的算法时,访问边界单元格的邻居极易引发索引越界错误;本文介绍两种高效、健壮的解决方案:条件短路判断与坐标偏移循环,确保只访问合法范围内的邻域单元格。
在二维网格(如 currentCells,一个列表的列表)中统计某单元格周围 8 个邻居的状态时,直接计算 x±1、y±1 并立即索引访问,会导致边界处(如左上角 x=0, y=0)尝试读取 currentCells[-1][-1] 或 currentCells[WIDTH][HEIGHT] 等非法位置,从而抛出 IndexError。根本解决思路是:在访问前显式校验坐标合法性,而非依赖异常处理。
for x in range(WIDTH):
for y in range(HEIGHT):
living_neighbors = 0
# 遍历所有 8 个相对偏移量(排除 (0, 0) 自身)
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue # 跳过当前单元格本身
nx, ny = x + dx, y + dy # 计算邻居坐标
# 安全检查:确保邻居在有效范围内
if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
if currentCells[nx][ny] == '#':
living_neighbors += 1
# 此处根据 living_neighbors 应用 Game of Life 规则更新 nextCells[x][y]? 关键点: WIDTH = len(currentCells)(行数,即 x 方向长度) HEIGHT = len(currentCells[0])(列数,即 y 方向长度),假设为矩形网格;若非矩形,需用 len(currentCells[x]) 动态获取每行宽度。 条件 0
若坚持逐变量赋值风格,可借助 and 的短路特性避免越界访问:
aboveLeft = (x > 0 and y > 0) and currentCells[x-1][y-1] above = (y > 0) and currentCells[x][y-1] aboveRight= (x < WIDTH-1 and y > 0) and currentCells[x+1][y-1] left = (x > 0) and currentCells[x-1][y] right = (x < WIDTH-1) and currentCells[x+1][y] bottomLeft= (x > 0 and y < HEIGHT-1) and currentCells[x-1][y+1] bottom = (y < HEIGHT-1) and currentCells[x][y+1] bottomRight=(x < WIDTH-1 and y < HEIGHT-1) and currentCells[x+1][y+1] # 统计存活邻居(注意:短路表达式结果可能是 bool 或 str,需统一处理) for cell in [aboveLeft, above, aboveRight, left, right, bottomLeft, bottom, bottomRight]: if cell == '#': # 只有当坐标合法且值为 '#' 时 cell 才是字符串;否则为 False living_neighbors += 1
⚠️ 注意:该写法虽可行,但可读性差、易出错(例如误将 False 当作 ' ' 处理),且不便于扩展(如改为 24 邻域)。强烈建议优先采用方案一。
通过上述任一方法,你的康威生命游戏即可稳健运行于任意尺寸网格,彻底告别 IndexError: list index out of range。