Search code examples
functionpython-3.xminesweeper

Python3 Number of Adjacent Mines Function


I'm currently making a function for a minesweeper clone in Python 3 that finds the number of mines around a square. The function takes in 3 parameters.

The first is a 2D list called "board", the second in an integer for the row of the square being clicked on and the third is an integer for the column of the square being clicked on. This is my current function:

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

This function works great, except that it only works for boards of a certain size. To change that, I believe I have to modify this if statement:

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

How could I fix this problem? if I could use board to find the dimensions of the board, this algorithm could work.

I appreciate the help.


Solution

  • Alright, I was right on which line I had to edit. The new line line looks like:

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

    The reason I couldn't get it to work is because I didn't add the couple of -1, giving me an error.