gpt4 book ai didi

python - 在扫雷器的网格中放置 1's around "b"

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:01 24 4
gpt4 key购买 nike

我有一个看起来像这样的网格。我在网格中随机放置一个“b”,并将数字 1 放在字母“b”的周围。这似乎在任何地方都有效,除非应该将 1 放在底行和一直向右的列中。例如,它看起来像这样

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 b
0 0 0 0 0 0 0 0 0 0

它应该是什么样子

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 1 b
0 0 0 0 0 0 0 0 1 1

这是我正在使用的代码,我不明白为什么没有将这些 1 放在那里。

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(10)


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
addmines(1)




def addscores():
for x in range(len(mat1)):
for y in range(len(mat1)):
if ((y < len(mat1)-1) and (x < len(mat1)-1)) and ((y >= 0) and (x >= 0))):
if mat1[y+1][x] == "b":
mat1[y][x] = 1
if mat1[y-1][x] == "b":
mat1[y][x] = 1
if mat1[y][x+1] == "b":
mat1[y][x] = 1
if mat1[y][x-1] == "b":
mat1[y][x] = 1
if mat1[y+1][x+1] == "b":
mat1[y][x] = 1
if mat1[y+1][x-1] == "b":
mat1[y][x] = 1
if mat1[y-1][x+1] == "b":
mat1[y][x] = 1
if mat1[y-1][x-1] == "b":
mat1[y][x] = 1
printmat(mat1)
addscores()

最佳答案

您的嵌套循环检查每个方 block ,看它是否应该有一个 1。但是,在您的第一个 if addscores() 中的条款,您省略了位于正方形边缘的每个正方形。解决这个问题的一个好方法是省略 if条款,而是添加一个函数来检查自动检查边界的正方形。例如:

def checksqu(y, x):
if y < 0 or y >= len(mat1) or x < 0 or x >= len(mat1):
return False
return mat1[y][x] == 'b'

然后代替if mat1[y - 1][x - 1]: , 你可以做 if checksqu(y - 1, x - 1): (等等)。

关于python - 在扫雷器的网格中放置 1's around "b",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13426258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com