MCPcopy Create free account
hub / github.com/Mrinank-Bhowmick/python-beginner-projects / Board

Class Board

projects/minesweeper/main.py:8–167  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6# this is so that we can just say "create a new board object", or
7# "dig here", or "render this game for this object"
8class Board:
9 def __init__(self, dim_size, num_bombs):
10 # let's keep track of these parameters. they'll be helpful later
11 self.dim_size = dim_size
12 self.num_bombs = num_bombs
13
14 # let's create the board
15 # helper function!
16 self.board = self.make_new_board() # plant the bombs
17 self.assign_values_to_board()
18
19 # initialize a set to keep track of which locations we've uncovered
20 # we'll save (row,col) tuples into this set
21 self.dug = set() # if we dig at 0, 0, then self.dug = {(0,0)}
22
23 def make_new_board(self):
24 # construct a new board based on the dim size and num bombs
25 # we should construct the list of lists here (or whatever representation you prefer,
26 # but since we have a 2-D board, list of lists is most natural)
27
28 # generate a new board
29 board = [[None for _ in range(self.dim_size)] for _ in range(self.dim_size)]
30 # this creates an array like this:
31 # [[None, None, ..., None],
32 # [None, None, ..., None],
33 # [... ],
34 # [None, None, ..., None]]
35 # we can see how this represents a board!
36
37 # plant the bombs
38 bombs_planted = 0
39 while bombs_planted < self.num_bombs:
40 loc = random.randint(
41 0, self.dim_size**2 - 1
42 ) # return a random integer N such that a <= N <= b
43 row = (
44 loc // self.dim_size
45 ) # we want the number of times dim_size goes into loc to tell us what row to look at
46 col = (
47 loc % self.dim_size
48 ) # we want the remainder to tell us what index in that row to look at
49
50 if board[row][col] == "*":
51 # this means we've actually planted a bomb there already so keep going
52 continue
53
54 board[row][col] = "*" # plant the bomb
55 bombs_planted += 1
56
57 return board
58
59 def assign_values_to_board(self):
60 # now that we have the bombs planted, let's assign a number 0-8 for all the empty spaces, which
61 # represents how many neighboring bombs there are. we can precompute these and it'll save us some
62 # effort checking what's around the board later on :)
63 for r in range(self.dim_size):
64 for c in range(self.dim_size):
65 if self.board[r][c] == "*":

Callers 1

playFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected