索引错误我只是想不通(Python)



我正试图通过python中的文本制作一款扫雷游戏。当我试图画这些小数字时,就会出现这个错误。也许我做这件事的方式效率很低,但我不明白为什么会出现这个错误。我一直试图篡改代码,但似乎什么都不起作用。有人知道为什么它不起作用吗?

import random
minenum = 12
gridsize = 10
grid = [[0] * gridsize for _ in range(gridsize)]
def setup():
global grid
global minecount
for i in range(minenum):
x = random.randrange(0,10)
y = random.randrange(0,10)
grid[y][x] = "m"
xpos = 0
ypos = 0
for n in range(10):
for z in range(10):
count = 0
try:
if grid[ypos + 1][xpos] == "m":
count += 1
except:
pass
try:
if grid[ypos + 1][xpos + 1] == "m":
count += 1
except:
pass
try:
if grid[ypos + 1][xpos - 1] == "m":
count += 1
except:
pass
try:
if grid[ypos - 1][xpos + 1] == "m":
count += 1
except:
pass
try:
if grid[ypos - 1][xpos - 1] == "m":
count += 1
except:
pass
try:
if grid[ypos - 1][xpos] == "m":
count += 1
except:
pass
try:
if grid[ypos][xpos + 1] == "m":
count += 1
except:
pass
try:
if grid[ypos][xpos - 1] == "m":
count += 1
except:
pass
grid[ypos][xpos] = count
xpos += 1
ypos += 1


def printBoard():
for i in range(10):
print(' '.join(str(v) for v in grid[i]))
setup()
printBoard()

[编辑]

这是错误:

Traceback (most recent call last):
File "main.py", line 74, in <module>
setup()
File "main.py", line 63, in setup
grid[ypos][xpos] = count
IndexError: list assignment index out of range

如果您在grid[ypos][xpos]=count之前添加一个print(count(,您将看到您有11个count实例,但grid只有10个,这就是为什么。

即使在最大值时,你也可以添加到ypos和xpos,下面是一个快速修复,但可能会更好:

print(count)
grid[ypos][xpos] = count
if xpos < gridsize - 1:
xpos += 1
if ypos < gridsize - 1:
ypos += 1

您的代码不起作用,因为当您递增ypos时从未重置xpos,所以您的索引如下(对于gridsize=4(:

0 0
1 0
2 0
3 0
4 1
5 1
6 1
7 1
8 2

而不是您输入的内容,即

0 0
1 0
2 0
3 0
0 1
1 1
2 1
3 1
0 2

无论何时进行ypos+=1 ,您都应该添加xpos=0

xpos += 1
ypos += 1
xpos = 0

您的代码也可以使用一些清理:

import random

def setup(minecount, gridsize):
grid = [[0] * gridsize for _ in range(gridsize)]
for _ in range(minecount):
x = random.randrange(0,gridsize)
y = random.randrange(0,gridsize)
grid[y][x] = "m"
for xpos in range(gridsize):
for ypos in range(gridsize):
count = 0
if ypos + 1 < 10 and grid[ypos + 1][xpos] == "m":
count += 1
if ypos + 1 < 10 and xpos +1 < 10 and grid[ypos + 1][xpos + 1] == "m":
count += 1
if ypos + 1 < 10 and xpos - 1 >= 0 and grid[ypos + 1][xpos - 1] == "m":
count += 1
if ypos - 1 >= 0 and xpos + 1 < 10 and grid[ypos - 1][xpos + 1] == "m":
count += 1
if ypos - 1 >= 0 and xpos -1 >= 10 and grid[ypos - 1][xpos - 1] == "m":
count += 1
if ypos - 1 >= 0 and grid[ypos - 1][xpos] == "m":
count += 1
if xpos + 1 < 10 and grid[ypos][xpos + 1] == "m":
count += 1
if xpos - 1 >= 0 and grid[ypos][xpos - 1] == "m":
count += 1
grid[ypos][xpos] = count
return grid


def printBoard(grid):
for i in range(10):
print(' '.join(str(v) for v in grid[i]))
minecount = 12
gridsize = 10

grid = setup(minecount, gridsize)
printBoard(grid)

甚至不需要改变逻辑,只需将幻数切换到适当的参数即可。您还覆盖了您的所有";m〃;在计算相邻炸弹时,你可能想避免这种情况。

您必须在setup((函数的末尾为xpos赋值零:

ypos += 1
xpos = 0

最新更新