Python3相邻矿山功能数量

Python3 Number of Adjacent Mines Function

我目前正在为 Python 3 中的扫雷克隆制作一个函数,用于计算一个正方形周围的地雷数量。该函数接受 3 个参数。

第一个是名为 "board" 的二维列表,第二个是被点击方块行的整数,第三个是被点击方块列的整数。这是我当前的功能:

def numMines(board, row, col):
mine_count = 0
    # For every every space around the square, including itself
    for r in range(-1, 2, 1):
        for c in range(-1, 2, 1):
            # If the square exist on the board
            if row+r >= 0 and col+c >= 0 and row+r <= 2 and col+c <=2:
                # If the square contains a mine
                if board[row+r][col+c][1] == "*":
                    #Raise the mine count
                    mine_count = mine_count + 1
# If the original square contains a mine
if board[row][col][1] == "*":
    # Lower the mine count by 1, because the square itself having a mine shouldn't be counted
    mine_count = mine_count - 1
return mine_count

这个功能很好用,只是它只适用于一定尺寸的板子。要改变它,我相信我必须修改这个 if 语句:

if row+r >= 0 and col+c >= 0 and row+r <= 2 and col+c <=2:

我该如何解决这个问题?如果我可以使用 board 来找到电路板的尺寸,这个算法就可以工作。

感谢您的帮助。

好的,我在需要编辑的那一行是正确的。新的一行看起来像:

if row+r >= 0 and col+c >= 0 and row+r <= len(board)-1 and col+c <= len(board[row])- 1:

我无法让它工作的原因是因为我没有添加两个-1,给了我一个错误。