我正在嘗試通過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
uj5u.com熱心網友回復:
如果您在 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
uj5u.com熱心網友回復:
您的代碼不起作用,因為您xpos在遞增時從未重置,ypos因此您的索引看起來像這樣(對于 gridsize = 4):
0 0
1 0
2 0
3 0
4 1
5 1
6 1
7 1
8 2
而不是你inteded,即
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”單元格,您可能希望避免這種情況。
uj5u.com熱心網友回復:
您必須在 setup() 函式的末尾為 xpos 分配零:
ypos = 1
xpos = 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441617.html
標籤:Python python-3.x 列表
