python-3.x - IndexError:尝试在python中为扫雷器制作网格时列表索引超出范围
问题描述
我正在尝试在 python 中制作扫雷网格。所以基本上,首先网格中只有零和 10 个炸弹(X),如果这个网格中的某个索引中有炸弹,程序应该给所有周围的索引加 1,不包括其中也有炸弹的索引。
这是我的代码:
import random
board1 = [[0] * 9 for n in range(9)]
for pos in random.sample(range(72), 10):
a = pos // 9
b = pos % 9
board1[a][b] = "X"
if a != 0 and b != 0 and board1[a-1][b-1] != "X":
board1[a - 1][b - 1] += 1
if a != 0 and board1[a-1][b] != "X":
board1[a - 1][b] += 1
if a != 0 and b != 9 and board1[a-1][b+1] != "X":
board1[a - 1][b + 1] += 1
if b != 0 and board1[a][b-1] != "X":
board1[a][b - 1] += 1
if b != 9 and board1[a][b+1] != "X":
board1[a][b + 1] += 1
if a != 9 and b != 0 and board1[a+1][b-1] != "X":
board1[a+1][b - 1] += 1
if a != 9 and board1[a+1][b] != "X":
board1[a + 1][b] += 1
if a != 9 and b != 9 and board1[a+1][b+1] != "X":
board1[a + 1][b + 1] += 1
frmt = "{:>3}"*len(board1)
for row in board1:
print(frmt.format(*row))
该代码似乎有效,但有时我会收到此错误:
if a != 0 and b != 9 and board1[a-1][b+1] != "X":
IndexError: list index out of range
该错误通常说if a != 0 and b != 9 and board1[a-1][b+1] != "X":
,但有时它可能会从其他行给出错误,例如:if b != 9 and board1[a][b+1] != "X":
。
我这几天一直在拔头发,有人可以帮忙吗?
解决方案
我认为当你的炸弹在棋盘的一端,b=9
而索引b+1
(10) 不存在时,就会发生这种情况。
b
当ora
等于 0时不会发生这种情况,因为您可以访问具有负索引的列表中的元素(最后一个为-1
),但我认为您不想要这个。
推荐阅读
- javascript - JQuery 可拖动内容 - 显示选中
- java - PowerMock expectNew 不会返回模拟实例
- python - Python 模块应该如何使用代码生成?
- javascript - 如何使用JavaScript单击删除和添加css动画属性
- python-3.x - 如何在文件中找到前五个结果的总和
- php - 使用 TCPDF 将多个具有透明度的图像分层
- python - 从子包运行 Python 测试
- liferay-7 - Liferay 7.2 Finder 不满意的参考资料
- php - 在 phpunit 测试中呈现树枝模板的问题
- javascript - Want client-side Firebase logs to show up in StackDriver, not users' browsers