0

我正在尝试编写命令行扫雷克隆,但我的地雷生成器代码遇到了一些问题。

def genWorld(size, mines):
    world = []
    currBlock = []
    for i in range(size):
        for j in range(size):
            currBlock.append("x")
        world.append(currBlock)
        currBlock = []
    for i in range(mines):
        while True:
            row = randint(0, size)
            col = randint(0, size)
            if world[row[col]] != "M":
                break
        world[row[col]] = "M"
    printWorld(world)

当我运行它时,我收到错误:

Traceback (most recent call last):
  File "C:\Python33\minesweeper.py", line 28, in <module>
    genWorld(9, 10)
  File "C:\Python33\minesweeper.py", line 23, in genWorld
    if world[row[col]] != "M":
TypeError: 'int' object is not subscriptable

我想这意味着我以错误的方式引用列表,但我将如何正确地做到这一点?

4

3 回答 3

3

你给row一个整数值。 row[col]然后尝试访问该整数的元素,这会产生错误。我想你想要的是world[row][col]

于 2013-06-10T18:42:49.100 回答
1

您可能想要world[row][col], asworld[row]给出一个列表,然后[col]从该列表中选择一个元素。

于 2013-06-10T18:42:55.223 回答
0

我会考虑使用 dict 而不是嵌套数组:

# positions for mines
mines = set()
while len(mines) != mines:
    pos = (randint(0, size), randint(0, size))
    if not pos in mines:
        mines.add(pos)

# initialize world
world = {}
for x in range(size):
    for y in range(size):
        if (x, y) in mines:
            world[x, y] = 'M'
        else:
            world[x, y] = ' '

None您还可以使用 dict 的 get() 函数,如果没有我的函数,它将返回,但是您也可以使用 set ( if pos in mines: booom()) 以使事情变得简单。

于 2013-06-10T19:11:22.500 回答