2D List Minesweeper Task? [Python]

Question:

I am trying to create a minesweeper where I create a function of a grid of # and - where each # is a mine and - is a mine-free spot, then return a grid where each dash is replaced by a digit indicating the mines around it .

Example Input:

[["-", "-", "-", "#", "#"],
["-", "#", "-", "-", "-"]] etc. etc.

Example Output:

[["1","1","2","#","#"],
["1","#","2","2","2"]]

(I was hoping that the grid would actually be a 5×5)

I am absolutely lost on how to do this at all so any help would be greatly appreciated.

Asked By: Iffah

||

Answers:

You can use nested for-loops to loop over every element in the 2d list, then if the element is not a mine, count how many neighbors are a mine. Just like this:

def genPuzzle(grid):
    puzzle = []
    for i in range(len(grid)):
        puzzle.append(grid[i][:])
        for j in range(len(grid[i])):
            if grid[i][j] == '#':
                continue
            neighbors = 0
            for d in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1),
                      (1, -1), (-1, 1)]:
                di, dj = i + d[0], j + d[1]
                try:
                    if di >= 0 and dj >= 0 and grid[di][dj] == '#':
                        neighbors += 1
                except IndexError:
                    pass
            puzzle[i][j] = neighbors
    return puzzle


grid = [["-", "-", "-", "#", "#"],
        ["-", "#", "-", "-", "-"]]
print(genPuzzle(grid))
Answered By: Michael M.