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

标签 python grid minesweeper

我有一个看起来像这样的网格。我在网格中随机放置一个“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/

相关文章:

JAVA反对二维数组,不能设置数组中的元素,也不能调用数组中的函数

python - 如何在 OSX 10.7 上安装 psycopg2

Python:确保所有子类方法返回相同的内容

python - 从 Jupyter Notebook 退出 pdb 交互模式

CSS 网格 : how to create a "half height" row

html - 7 Bootstrap 中的列网格在 xs 处崩溃

selenium - 无法使用 Selenium Grid 访问虚拟机上的节点

java - 扫雷哈希集

c++ - 扫雷邻居数

python - Google App Engine 中的证书存储