Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Game: minesweeper #22

Open
grantjenks opened this issue Mar 15, 2019 · 0 comments
Open

Add Game: minesweeper #22

grantjenks opened this issue Mar 15, 2019 · 0 comments

Comments

@grantjenks
Copy link
Owner

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.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant