-
Notifications
You must be signed in to change notification settings - Fork 1
/
minesweeper_board.py
92 lines (79 loc) · 2.25 KB
/
minesweeper_board.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import random
from typing import List, Union
class UnopenedCell():
def __init__(self) -> None:
pass
class OpenedCell():
def __init__(self) -> None:
pass
class FlaggedCell():
def __init__(self) -> None:
pass
class Bomb():
BOMB = "*"
def __init__(self) -> None:
pass
def __repr__(self) -> str:
return self.BOMB
class Empty():
def __init__(self) -> None:
self.num = 0
def __repr__(self) -> str:
return str(self.num)
class Cell():
def __init__(self) -> None:
self.state: Union[UnopenedCell, OpenedCell, FlaggedCell] = UnopenedCell()
self.contain: Union[Empty, Bomb] = Empty()
def __repr__(self) -> str:
return str(self.contain)
class Board():
'''Generate board for minesweeper,
bombs parameter sets max limit, not exact amount
'''
def __init__(self, x: int, y: int, bombs: int) -> None:
self.x = x
self.y = y
self.bombs = bombs
def generate(self) -> List[List[Cell]]:
'''Generates new board.'''
self.board: List[List[Cell]] = list()
self.__generate_matrix()
self.__add_bombs()
self.__add_nums()
return self.board
def __generate_matrix(self):
'''Creating matrix, and adding Empty cells'''
for y in range(self.y):
row_arr = list()
for x in range(self.x):
row_arr.append(Cell())
self.board.append(row_arr)
def __add_bombs(self):
'''Adding bombs to board'''
for i in range(self.bombs):
self.board[random.randint(0, self.y-1)][random.randint(0, self.x-1)].contain = Bomb()
def __add_nums(self):
'''Numerating empty cells'''
region = list()
for row in range(len(self.board)):
for cell in range(len(self.board[row])):
if isinstance(self.board[row][cell].contain, Bomb):
if cell < self.x-1:
region.append(self.board[row][cell+1])
if cell > 0:
region.append(self.board[row][cell-1])
if row > 0:
region.append(self.board[row-1][cell])
if cell < self.x-1:
region.append(self.board[row-1][cell+1])
if cell > 0:
region.append(self.board[row-1][cell-1])
if row < self.y-1:
region.append(self.board[row+1][cell])
if cell < self.x-1:
region.append(self.board[row+1][cell+1])
if cell > 0:
region.append(self.board[row+1][cell-1])
for cell in region:
if isinstance(cell.contain, Empty):
cell.contain.num += 1