我正在尝试编写命令行minesweeper克隆,而我的地雷生成器代码遇到了一些麻烦。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我以为这意味着我以错误的方式引用了列表,但是我将如何正确地做到这一点呢?
3 回答

饮歌长啸
TA贡献1951条经验 获得超3个赞
我会考虑使用字典而不是嵌套数组:
# 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] = ' '
您还可以使用dict的get()函数,None如果没有我的函数,该函数将返回,但是您也可以继续使用set(if pos in mines: booom())以使事情变得简单。
添加回答
举报
0/150
提交
取消