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

2024-10-01 19:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个扫雷游戏,仍然没有使用任何类型的接口,只使用ascii,同时尝试手工实现代码,因为我在py方面没有太多的经验,我在调试代码时遇到了一些挫折,我有一个问题,当“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)

Tags: 代码inforrodefcheckercolumn矩阵
1条回答
网友
1楼 · 发布于 2024-10-01 19:31:23

索引到一个列表(比如当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])

另外,为了更大的价值,您可以将列和行从后面放到前面。我就这样离开了

相关问题 更多 >

    热门问题