Created
November 20, 2020 08:45
-
-
Save arbinish/bbe965df05e6589f048385ae7c350618 to your computer and use it in GitHub Desktop.
simple minesweeper operations in python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
from typing import List | |
class Board: | |
def __init__(self, length: int, width: int, bombs: int) -> List: | |
self.length = length | |
self.width = width | |
self.board = [] | |
for i in range(length): | |
self.board.append([0] * width) | |
for _ in range(bombs): | |
while True: | |
x = randint(0, length - 1) | |
y = randint(0, width - 1) | |
if self.board[x][y] == 0: | |
self.board[x][y] = 'x' | |
break | |
self.setup_hints() | |
def __repr__(self) -> str: | |
r = '' | |
for i in range(self.length): | |
r += ''.join((f'{i:^5}' for i in self.board[i])) | |
r += '\n' | |
return r | |
def setup_hints(self) -> None: | |
board = self.board | |
for row in range(self.length): | |
for col in range(self.width): | |
if board[row][col] != 'x': | |
continue | |
self.update_hints(row, col) | |
def update_hints(self, row: int, col: int) -> None: | |
self.safe_update(row, col + 1) | |
self.safe_update(row, col - 1) | |
self.safe_update(row - 1, col) | |
self.safe_update(row - 1, col - 1) | |
self.safe_update(row - 1, col + 1) | |
self.safe_update(row + 1, col) | |
self.safe_update(row + 1, col + 1) | |
self.safe_update(row + 1, col - 1) | |
def safe_update(self, row: int, col: int) -> None: | |
if row >= self.length or col >= self.width or row < 0 or col < 0: | |
return | |
if self.board[row][col] == 'x': | |
return | |
self.board[row][col] += 1 | |
def click(self, | |
row: int, | |
col: int, | |
visited: List = None, | |
cells: List = None) -> List: | |
board = self.board | |
if visited is None: | |
visited = [] | |
if cells is None: | |
cells = [] | |
if row >= self.length or col >= self.width or row < 0 or col < 0: | |
return | |
if board[row][col] == 'x': | |
return | |
cell_signature = row * 10 + col | |
if cell_signature in visited: | |
return | |
board[row][col] = f'-{board[row][col]}-' | |
cells.append((row, col)) | |
visited.append(cell_signature) | |
self.click(row, col + 1, visited, cells) | |
self.click(row, col - 1, visited, cells) | |
self.click(row - 1, col, visited, cells) | |
self.click(row - 1, col + 1, visited, cells) | |
self.click(row - 1, col - 1, visited, cells) | |
self.click(row + 1, col, visited, cells) | |
self.click(row + 1, col + 1, visited, cells) | |
self.click(row + 1, col - 1, visited, cells) | |
return cells |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment