Python 扫雷矩阵越界循环,最后一行未填充

Python minesweeper matrix out of bounds looping and last row not filling

我正在 python 中创建一个扫雷游戏,仍然没有使用任何类型的界面,仅在 ascii 中,同时尝试手动实现代码,因为我在 py i 方面没有太多经验'我在调试我的代码时有点沮丧,我有一个问题,当 "bomb(X)" 在最后一行或第一列时,它循环到另一边,如果它在最后一列,或第一列和最后一行代码根本不起作用

矩阵循环示例

 ['1' 'X' '1' '0' 'X']
 ['1' '1' '1' '0' '0']
 ['0' '0' '0' '0' '0']
 ['0' '0' '0' '0' '0']
 ['1' '1' '1' '0' '0']

矩阵最后一列错误

 ['0' '0' '0' '0' '0']
 ['0' '0' '1' '1' '1']
 ['0' '0' '1' 'X' '1']
 ['0' '0' '1' '1' '1']
 ['0' '0' '0' 'X' '0']

相关代码

数字填充算法

def popularNumeros(column,row,matrix):
    column -=1
    row -=1
    for col in range(column):
        for ro in range(row):
            if matrix[col][ro] == 'X':
                try:
                    matrix[col+1][ro+1] = checker(matrix[col+1][ro+1])#diagonal inferior direita
                    matrix[col+1][ro-1] = checker(matrix[col+1][ro-1])#diagonal inferior esquerda
                    matrix[col-1][ro-1] = checker(matrix[col-1][ro-1])#diagonal superior esquerda
                    matrix[col-1][ro+1] = checker(matrix[col-1][ro+1])#diagonal superior direita
                    matrix[col-1][ro] = checker(matrix[col-1][ro])#cima
                    matrix[col+1][ro] = checker(matrix[col+1][ro])#baixo
                    matrix[col][ro-1] = checker(matrix[col][ro-1])#esquerda
                    matrix[col][ro+1] = checker(matrix[col][ro+1])#direita
                except:
                    ro+=1

炸弹检查器

def checker(matrixItem):
    if matrixItem == 'X':
        return matrixItem

    else:
        return str(int(matrixItem)+1)

对列表进行负索引(比如 col 为 0,因此 col-1 = -1)环绕到列表末尾,返回列表中的最后一项。

索引超出列表的最后一项会引发 IndexError 异常 - IndexError: list index out of range。发生这种情况时,Python 立即跳转到 except 块,一旦完成,它就不会返回到第一次引发异常时的位置。

您需要确保您不会对 matrix 列表进行负索引,或者索引超过末尾。

您可以在 try 块中的每一行周围使用大量 if 语句,或者您可以使用 for 循环来检查周围的单元格,如下所示:

def popularNumeros(column, row, matrix):
    for col in range(column):
        for ro in range(row):
            if matrix[col][ro] == 'X':
                for offset_column in range(col-1, col+2):
                    if offset_column < 0 or offset_column >= column:
                        continue # Outside of the safe boundary - skip

                    for offset_row in range(ro-1, row+2):
                        if offset_row < 0 or offset_row >= row:
                            continue # Outside of the safe boundary - skip

                        matrix[offset_column][offset_row] = checker(matrix[offset_column][offset_row])

此外,不管怎样,您的列和行都是从后到前的。我就这样离开了。