首页 > 解决方案 > 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":

我这几天一直在拔头发,有人可以帮忙吗?

标签: python-3.x

解决方案


我认为当你的炸弹在棋盘的一端,b=9而索引b+1(10) 不存在时,就会发生这种情况。

b当ora等​​于 0时不会发生这种情况,因为您可以访问具有负索引的列表中的元素(最后一个为-1),但我认为您不想要这个。


推荐阅读