Minesweeper-Style Game in Python

Python game 10 of 20

Mediumโฑ 45 min๐Ÿ“„ 77 lines of Pythonโ˜… 3 challengesโ–ถ Plays in your browser

Mine Finder is a Minesweeper-style puzzle: open every safe square on the grid without touching a mine. Each opened square shows how many mines touch it. In code, that means counting the 8 neighbours of a cell, and when a square has zero, opening all its neighbours automatically with a flood fill.

Your first square is always safe. Type a row and column like 3 4, or f 3 4 to plant a flag.

Play Mine Finder

minesweeper.py ยท real Python in your browser
Press โ–ถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (77 lines)

How to play

  • Type a row and a column (1-6), for example 2 5, to open a square.
  • Numbers say how many of the 8 squares around it hide a mine.
  • Type f and a position (f 2 5) to flag a mine. Open every safe square to win.

The complete Mine Finder code

Here is the whole program (77 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import random

SIZE, MINES = 6, 6
mines = set()
opened = set()
flags = set()


def neighbours(r, c):
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            y, x = r + dr, c + dc
            if (dr or dc) and 0 <= y < SIZE and 0 <= x < SIZE:
                yield y, x


def count(r, c):
    return sum((y, x) in mines for y, x in neighbours(r, c))


def place_mines(safe):
    cells = [(r, c) for r in range(SIZE) for c in range(SIZE) if (r, c) != safe]
    mines.update(random.sample(cells, MINES))


def open_square(r, c):
    if (r, c) in opened:
        return
    opened.add((r, c))
    if count(r, c) == 0:                 # flood fill: open the neighbours too
        for y, x in neighbours(r, c):
            open_square(y, x)


def show(reveal=False):
    print("\n    " + " ".join(str(c + 1) for c in range(SIZE)))
    for r in range(SIZE):
        row = []
        for c in range(SIZE):
            if reveal and (r, c) in mines:
                row.append("*")
            elif (r, c) in flags:
                row.append("F")
            elif (r, c) in opened:
                row.append(str(count(r, c)) if count(r, c) else " ")
            else:
                row.append("#")
        print(f" {r + 1}  " + " ".join(row))


print("MINE FINDER  -  open all the safe squares")
show()
while True:
    parts = input("Row and column (or f row col): ").lower().split()
    flag = parts[:1] == ["f"]
    if flag:
        parts = parts[1:]
    if len(parts) != 2 or not all(p.isdigit() and 1 <= int(p) <= SIZE for p in parts):
        print("Type two numbers from 1 to", SIZE)
        continue
    r, c = int(parts[0]) - 1, int(parts[1]) - 1
    if flag:
        flags ^= {(r, c)}              # flag on, or flag off again
        show()
        continue
    if not mines:
        place_mines((r, c))
    if (r, c) in mines:
        show(reveal=True)
        print("BOOM! You found a mine. Game over.")
        break
    open_square(r, c)
    flags -= opened
    show()
    if len(opened) == SIZE * SIZE - MINES:
        print("You cleared the field. You win!")
        break

How the Mine Finder game works, step by step

01Keep the state in sets

Sets of (row, col) tuples hold the mines, the opened squares and the flags. (r, c) in mines is a quick yes/no test.

mines = set()
opened = set()
flags = set()

02Find the neighbours

Two nested loops over -1, 0, 1 visit the 8 squares around a cell. We skip the cell itself and anything off the edge. yield hands back one neighbour at a time.

for dr in (-1, 0, 1):
    for dc in (-1, 0, 1):
        if (dr or dc) and 0 <= r + dr < SIZE and 0 <= c + dc < SIZE:
            yield r + dr, c + dc

03Count the mines around a square

True counts as 1 in Python, so summing (y, x) in mines over the neighbours gives the number to show.

return sum((y, x) in mines for y, x in neighbours(r, c))

04Make the first click safe

Mines are placed only after the first move, with random.sample() choosing from every cell except the one you opened.

cells = [(r, c) for r in range(SIZE) for c in range(SIZE) if (r, c) != safe]
mines.update(random.sample(cells, MINES))

05Flood fill with recursion

When a square has no mines around it, the function calls itself on each neighbour. Those can call themselves too, so a whole empty area opens at once. The if (r, c) in opened: return line stops it going round in circles.

def open_square(r, c):
    if (r, c) in opened:
        return
    opened.add((r, c))
    if count(r, c) == 0:
        for y, x in neighbours(r, c):
            open_square(y, x)

What you'll learn

  • Sets of tuples as game state
  • Generators with yield
  • Counting with sum() of booleans
  • random.sample()
  • Recursion (flood fill)

Python concepts in this game:

Mine Finder coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Count neighbouring mines

Write count(mines, r, c, size): return how many of the 8 squares around (r, c) are in the mines set. Ignore squares outside a size ร— size grid.

challenge 1 ยท edit, Run, then Check
Hint

Loop dr and dc over (-1, 0, 1) and skip dr == dc == 0.

Show a solution
def count(mines, r, c, size):
    total = 0
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            y, x = r + dr, c + dc
            if (dr or dc) and 0 <= y < size and 0 <= x < size and (y, x) in mines:
                total += 1
    return total

print(count({(0, 0), (1, 2)}, 1, 1, 4))
2/3

Draw one square

Write symbol(cell, mines, opened, n): return "#" if the cell isn't opened, "*" if it's an opened mine, " " if it's opened with n == 0, otherwise the number n as text.

challenge 2 ยท edit, Run, then Check
Hint

Check in this order: not opened, mine, zero, number. Use str(n) for the number.

Show a solution
def symbol(cell, mines, opened, n):
    if cell not in opened:
        return "#"
    if cell in mines:
        return "*"
    if n == 0:
        return " "
    return str(n)

print(repr(symbol((0, 0), set(), {(0, 0)}, 2)))
3/3

Flood fill

Write flood(grid, r, c, seen) for a grid of numbers: add (r, c) to seen, and if grid[r][c] == 0 call flood on every neighbour (8 directions, inside the grid) not already in seen.

challenge 3 ยท edit, Run, then Check
Hint

Return early when the square isn't 0. Otherwise loop over the neighbours and call flood(grid, y, x, seen).

Show a solution
def flood(grid, r, c, seen):
    seen.add((r, c))
    if grid[r][c] != 0:
        return
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            y, x = r + dr, c + dc
            if 0 <= y < len(grid) and 0 <= x < len(grid[0]) and (y, x) not in seen:
                flood(grid, y, x, seen)

g = [[0, 0, 1],
     [0, 1, 9],
     [1, 2, 2]]
s = set()
flood(g, 0, 0, s)
print(sorted(s))

Make it your own

Once your challenges pass, try one of these upgrades:

  • Add difficulty levels with bigger grids and more mines.
  • Show a timer and keep the best time.
  • Open all neighbours when you choose a number that already has enough flags.
  • Make a clickable version with turtle's onclick().

Frequently asked questions

How do you make Minesweeper in Python?

Store mines and opened squares in sets, count each square's 8 neighbours, and when a square has zero mines around it, open its neighbours with a recursive flood fill.

What is flood fill?

A function that opens a square and, if it is empty, calls itself on every neighbour. It is the same idea paint programs use for the bucket tool.

How do I make the first move safe?

Place the mines after the first move and leave that square out of the choices given to random.sample().

More games like this