-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
326 lines (274 loc) · 11.5 KB
/
classes.py
File metadata and controls
326 lines (274 loc) · 11.5 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
from helpers import validate_coordinates, every, flat, print_colored
from constants import COORDINATES_TRANSITIONS, VALUE_COLORS
import random
"""
Game:
board_size: (int, int)
mines: int
board: (listof (listof Cell))
playing: boolean - True when the game starts
start_playing: boolean - True when the player clicks for the first time, helps generates the board
Cell:
row: int
column: int
val: [0:8] | "M" | None (None when game not started, "M" for mine , (0-8) for the number value)
is_flagged: boolean
is_covered: boolean
"""
class Game:
def __init__(self, rows, columns, mines):
self.board_size = (rows, columns)
self.mines = mines
self.board = []
self.playing = True
self.start_playing = False # True when he starts clicking
for row in range(rows):
self.board.append([]) # a new row
for column in range(columns):
self.board[-1].append(
Cell(row, column)
) # a new element in the last row
def start_game(self):
while self.playing:
self.draw_board()
row, column, option = self.handle_input()
cell = self.board[row][column]
if cell.is_flagged and option == "c":
option = (
"f" # change the flagged value to c if the it's already flagged
)
if option == "c":
self.click_cell(row, column)
self.chord(row, column)
elif option == "f":
self.flag_cell(row, column) # Either flag or unflag
# void -> boolean
# return true if all the cells that have numbers have been uncovered
def check_win(self):
def check_cell(cell):
return (type(cell.val) == int and not cell.is_covered) or type(
cell.val
) != int
return every(check_cell, flat(self.board))
def game_lose(self):
self.playing = False
self.draw_board()
print("You lost!")
# void -> int, int, 'c' or 'f'
def handle_input(self):
is_valid_input = False
while not is_valid_input:
command = input("Command: ").lower().strip().split(" ")
option = "c"
# Check for the length of the command
if len(command) not in [2, 3]:
print("Invalid Command")
continue
# Check if rows, and columns are numbers
try:
row, column = map(lambda val: int(val) - 1, command[:2])
if not validate_coordinates(row, column, self.board_size):
print("Invalid Coordinates")
continue
if len(command) == 3:
option = "f" if command[2] == "f" else "c"
if not self.start_playing:
print("You cannot flag on the first move!")
continue
is_valid_input = True
except:
print("Invalid Command")
return row, column, option
# (int, int) -> void
# click the current cell with the given row, and conlumn coordinates.
# if covered, if not mine, just reveal it with the surrounding. If mine, declare game_lose, if
# if not convered, if the surrounding flags number matches with the number, click the rest cells
def click_cell(self, row, column):
# recursion to check and uncover all cells with zero value & their adjacent cells.
def zero_chain(neighbors):
for cell in neighbors:
row = cell.row
column = cell.column
if cell.is_covered and not cell.is_flagged:
match cell.val:
case 0:
cell.is_covered = False
zero_chain(self.neighboring_cells(row, column))
case _:
cell.is_covered = False
if not self.start_playing:
self.generate_board(row, column)
self.start_playing = True
if self.board[row][column].val != None and self.board[row][column].is_covered:
self.board[row][column].is_covered = False
# checks cell value
match self.board[row][column].val:
case "M":
self.game_lose()
case 0:
neighbors = self.neighboring_cells(row, column)
zero_chain(neighbors)
if self.check_win():
self.draw_board()
print("You won!!")
self.playing = False
# (int, int) -> void
# The cell must be covered, toggle the flag on the cell
def flag_cell(self, row, column):
if self.board[row][column].is_covered == True:
self.board[row][column].is_flagged = not self.board[row][column].is_flagged
# (int, int) -> (listof Cell)
# return a list of the surrounding cells of the given cell
# use validate_coordinates
def neighboring_cells(self, row, column):
neighbors = []
# Looping through the 8 neighboring cells positions with respect to current cell
# Format = (row, column)
for dx, dy in COORDINATES_TRANSITIONS:
neighbor_row = row + dx
neighbor_column = column + dy
# Checking if the position represents a valid index in the board
# This check is mainly useful for the cells present on the edges of the board
if validate_coordinates(neighbor_row, neighbor_column, self.board_size):
neighbors.append(self.board[neighbor_row][neighbor_column])
return neighbors
# (int, int) -> int
# Return the count of neighboring mines
def count_neighboring_mines(self, row, column):
return len(
list(
filter(
lambda cell: cell.val == "M", self.neighboring_cells(row, column)
)
)
)
## (int, int) -> int
# Return the count of neighboring flags
def count_neighboring_flags(self, row, column):
return len(
list(
filter(
lambda cell: cell.is_flagged, self.neighboring_cells(row, column)
)
)
)
# int, int -> Boolean
# return true if the number assigned to the cell and the number isn't zero has the same number of surrounding flags
def check_chordable(self, row, column):
cell = self.board[row][column]
return (
type(cell.val) == int
and cell.val != 0
and cell.val == self.count_neighboring_flags(row, column)
)
# int, int -> void
# If the cell clicked has the same number of flagged around as the number on it, uncover the remaining cells
def chord(self, row, column):
if self.check_chordable(row, column):
neighboring_cells = self.neighboring_cells(row, column)
neighboring_cells_uncovered = filter(
lambda cell: cell.is_covered and not cell.is_flagged, neighboring_cells
)
for cell in neighboring_cells_uncovered:
self.click_cell(cell.row, cell.column)
# (int, int) -> void
# given the coordinates of the cell clicked first, create a board that must have the given cell with a non-mine value, then call click_cell to start the game
# fill in the mines randomly, then fill in the number depending on the mines
def generate_board(self, row, column):
rows, columns = self.board_size
mine_positions = []
# Generate a number of mines with random positions based on the chosen difficulity
while len(mine_positions) < self.mines:
# Generate a random position for the mine
mine_row_index = random.randint(0, rows - 1)
mine_column_index = random.randint(0, columns - 1)
# Make sure that the mine position wasn't generated before
# Also, make sure that the mine position doesn't match the user's first move
# Assign the value "M" to the cell with this position
if (mine_row_index, mine_column_index) not in mine_positions and (
mine_row_index,
mine_column_index,
) != (row, column):
self.board[mine_row_index][mine_column_index].val = "M"
mine_positions.append((mine_row_index, mine_column_index))
# Assign the values of each cell on the board
# If its not a Mine -> Assign it the number of neighboring mines
for row_index in range(len(self.board)):
for column_index in range(len(self.board[row_index])):
if (row_index, column_index) not in mine_positions:
self.board[row_index][
column_index
].val = self.count_neighboring_mines(row_index, column_index)
# void -> void
# create a grid-looking board of the current board
# (0-8) -> the number, X for not opened cells, F for flagged cells, B for mines when losing the game
def draw_board(self):
rows, columns = self.board_size
# Print First Row
print(" ", end="")
for column in range(columns):
print(f"{(column + 1):^4}", end="")
print()
# print each row
for row in range(rows):
# Print Upper Border
print("----" * (columns + 1))
print(f"{(row + 1):^4}", end="")
# Print The Row
for column in range(columns):
# Print the horizontal border for the first column
if column == 0:
print("|", end="")
# Print the value of the cell
if (
type(self.board[row][column].val) == int
and self.board[row][column].val != 0
and not (self.board[row][column].is_covered)
):
colored_cell = print_colored(
(self.board[row][column]),
VALUE_COLORS[self.board[row][column].val],
)
print(f" {colored_cell} ", end="")
else:
print(f" {self.board[row][column]} ", end="")
# Print Horizontal Border
print("|", end="")
print()
# Print Bottom Border
print("----" * (columns + 1))
# () -> int
# return the number of cells where is_covered=False and not a mine
def get_revealed_cells(self):
count = 0
for cell in flat(self.board):
if cell.is_covered == False and cell.val != "M":
count += 1
return count
class Cell:
def __init__(self, row, column, is_flagged=False, val=None, is_covered=True):
self.row = row
self.column = column
self.is_flagged = is_flagged
self.is_covered = is_covered
self.val = (
val # None when game not started, "M" for mine , (0-8) for the number value
)
def __str__(self):
if self.is_flagged:
return "F"
if not self.is_covered and self.val == "M":
return "M"
if self.val == 0 and self.is_covered == False:
return " "
if self.is_covered or self.val is None:
return "X"
return str(self.val)
def __dict__(self):
return {
"row": self.row,
"column": self.column,
"is_flagged": self.is_flagged,
"is_covered": self.is_covered,
"val": self.val,
}