我有一个函数可以将“z”数量的炸弹随机散布在 10x10 的网格中。它看起来像这样(“b”代表炸弹所在的位置。)我需要在“0”(包括对角线)旁边放置一个代表有多少炸弹的数字,我不知道该怎么做。
0 0 0 0 0 0 0 0 b 0
b 0 0 b 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 b 0 0 0
0 0 0 b 0 0 0 0 0 0
0 0 b 0 0 0 0 0 0 b
0 0 0 0 0 0 0 b 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 b 0 b 0 0 0 0
0 0 0 0 0 0 0 0 0 0
from random import*
mat1 = []
mat2 = []
def makemat(x):
for y in range(x):
list1 = []
list2 = []
for z in range(x):
list1.append(0)
list2.append("-")
mat1.append(list1)
mat2.append(list2)
makemat(5)
def printmat(mat):
for a in range(len(mat)):
for b in range(len(mat)):
print(str(mat[a][b]) + "\t",end="")
print("\t")
def addmines(z):
count = 0
while (count < z):
x = randrange(0,len(mat1))
y = randrange(0,len(mat1))
if mat1[y][x] == "b":
count -= 1
else:
mat1[y][x] = "b"
count += 1
printmat(mat1)
addmines(10)
这是我尝试放置数字的功能:
def addscores():
for x in range(len(mat1)):
for y in range(len(mat1)):
if mat1[y][x] != "b":
if mat1[y+1][x] == "b":
mat1[y][x] = 1
if mat1[y-1][x] == "b":
mat1[y][x] = 1 #...ETC
else:
mat1[y][x] == "b"
addscores()
我不断得到错误列表索引超出范围。我该如何解决这个问题?