Skip to content

Add Game: minesweeper #22

@grantjenks

Description

@grantjenks

See: https://en.wikipedia.org/wiki/Minesweeper_(video_game)

Prototype:

"""Minesweeper Game

Just playing around. The code below is not well tested.

"""

import random
import collections

random.seed(1)

size = 5
bombs = collections.defaultdict(int)
counts = collections.defaultdict(int)
display = collections.defaultdict(lambda: 'X')
neighbors = sorted(set((i, j) for i in range(size) for j in range(size)) - {(0, 0)})

# Initialize

for x in range(size):
    for y in range(size):
        bombs[x, y] = 0
        counts[x, y] = 0
        display[x, y] = '?'

# Set bombs

for _ in range(3):
    x = random.randrange(size)
    y = random.randrange(size)
    bombs[x, y] = 1

# Calculate counts

for x in range(size):
    for y in range(size):
        total = 0
        for i in [-1, 0, 1]:
            for j in [-1, 0, 1]:
                total += bombs[x + i, y + j]
        counts[x, y] = total

def show(grid):
    for x in range(size):
        for y in range(size):
            print(grid[x, y], end=', ')
        print()

print('Bombs:')
show(bombs)

print('Counts:')
show(counts)

alive = True

def reveal(x, y):
    """Update display and return True/False for alive status.

    """
    if bombs[x, y]:
        return False

    display[x, y] = counts[x, y]

    if counts[x, y]:
        return True

    zeros = [ (x, y) ]

    while zeros:
        x, y = zeros.pop()

        if not ((0 <= x < size) and (0 <= y < size)):
            continue

        if counts[x, y] == 0:
            display[x, y] = 0

        for i in (-1, 0, 1):
            for j in (-1, 0, 1):
                if i == j == 0:
                    continue
                offset_x = x + i
                offset_y = y + j
                seen = display[offset_x, offset_y] != '?'
                if counts[offset_x, offset_y] == 0 and not seen:
                    zeros.append( (offset_x, offset_y) )

    return True

while alive:
    show(display)
    x = int(input('row: '))
    y = int(input('column: '))

    alive = reveal(x, y)

    if not alive or not any(spot == '?' for spot in display.values()):
        break

if alive:
    print('Congratulations! You win.')
else:
    print('Sorry, you failed.')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions