-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminesweeper.py
More file actions
202 lines (151 loc) · 6.48 KB
/
minesweeper.py
File metadata and controls
202 lines (151 loc) · 6.48 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
__author__ = 'Nick Dajda'
from tkinter import *
from tkinter import ttk
from random import random
from functools import partial
class MineField:
"""Manages a map of the field. Where mines are, which spaces have been discovered and flagged.
Convention for field array:
'.' = no mines, has not been stepped upon or marked
0-8 = Had been stepped on. Value is number of adjacent squares containing mines
'x' = mine
"""
def __init__(self, content, width=10, height=10, mines=10):
self.width = width
self.height = height
self.mines = mines
self.content = content
self.cellcolors = {'0': 'black', '1': 'blue', '2': 'purple', '3': 'orange', '4': 'red', '5': 'brown',
'6': 'yellow', 'F': 'dark green', 'X': 'red'}
for key, value in self.cellcolors.items():
ttk.Style().configure(value + ".TButton", foreground=value)
# Layout is: field[row][col]
self.field = [['.' for x in range(self.width)] for x in range(self.height)]
# Set the mines
assert (self.mines < self.width * self.height), "Too many mines for field to accommodate"
# Populate mines
mines_sown = 0
row = col = 0
chance = float(self.mines) / (self.width * self.height)
while mines_sown < self.mines:
# Roll the die
if random() < chance:
if self.field[row][col] is not 'x':
self.field[row][col] = 'x'
mines_sown += 1
col += 1
if self.width == col:
col = 0
row += 1
if self.height == row:
row = 0
# Create the squares
self.minefieldbuttons = []
# row, col layout
for y in range(height):
new = []
for x in range(width):
new.append(ttk.Button(content, width=3))
self.minefieldbuttons.append(new)
for y in range(height):
for x in range(width):
self.minefieldbuttons[y][x].grid(column=x, row=y, sticky=(N, S, E, W), padx=0, pady=0)
self.minefieldbuttons[y][x].bind("<Button-1>", partial(self.step, y, x))
self.minefieldbuttons[y][x].bind("<Button-3>", partial(self.mark, y, x))
def print_field(self):
for row in range(self.height):
text = ""
for col in range(self.width):
text = text + str(self.field[row][col])
print(text)
def step(self, row, col, event):
"Here goes..."
if 'x' == self.field[row][col]:
print("You hit a mine!")
self.exposebutton(row, col, "X")
self.show_mines()
#
# Game over!
#
# Show remaining mines
return True
if '.' == self.field[row][col]:
self.field[row][col] = self.count_neighbouring_mines(row, col)
self.exposebutton(row, col)
if 0 == self.field[row][col]:
self.explore_further(row, col)
self.print_field()
# Every square trodden?
remaining_spaces = 0
for y in range(self.height):
for x in range(self.width):
if ('.' == self.field[y][x]) or ('x' == self.field[y][x]):
remaining_spaces += 1
print ("Remaining spaces: %d" % remaining_spaces)
if remaining_spaces == self.mines:
print("You win!")
self.show_mines()
return False
def show_mines(self):
for y in range(self.height):
for x in range(self.width):
if ('x' == self.field[y][x]):
self.exposebutton(row=y, col=x, value="X")
def mark(self, row, col, event):
if ('.' == self.field[row][col]) or ('x' == self.field[row][col]):
if self.minefieldbuttons[row][col]["text"] == "":
self.exposebutton(row, col, 'F')
else:
self.minefieldbuttons[row][col].config(text="")
def count_neighbouring_mines(self, row, col):
mine_count = 0
mine_count += self.mine_in_cell(row - 1, col - 1)
mine_count += self.mine_in_cell(row - 1, col)
mine_count += self.mine_in_cell(row - 1, col + 1)
mine_count += self.mine_in_cell(row, col - 1)
mine_count += self.mine_in_cell(row, col + 1)
mine_count += self.mine_in_cell(row + 1, col - 1)
mine_count += self.mine_in_cell(row + 1, col)
mine_count += self.mine_in_cell(row + 1, col + 1)
return mine_count
def mine_in_cell(self, row, col):
"Mainly an error checking function to see if row and col are valid"
if (row < 0) or (row >= self.height) or (col < 0) or (col >= self.width):
return 0
if 'x' == self.field[row][col]:
return 1
return 0
def explore_further(self, row, col):
assert(0 == self.field[row][col]), "Can only explore from cells already marked as 0"
if row > 0:
self.map_area(row-1, col)
if row < (self.height-1):
self.map_area(row+1, col)
if col > 0:
self.map_area(row, col-1)
if col < (self.width-1):
self.map_area(row, col+1)
def map_area(self, row, col):
assert (((row < 0) or (row >= self.height) or (col < 0) or (col >= self.width)) is False), \
"Can only explore cells within the grid (row=%d, col=%d, self.height=%d, self.width=%d)" \
% (row, col, self.height, self.width)
# Already explored cell
if self.field[row][col] != '.':
return
self.field[row][col] = self.count_neighbouring_mines(row, col)
self.exposebutton(row, col)
#self.minefieldbuttons[row][col].config(text=str(self.field[row][col]), style="emptysquare.TButton")
if 0 == self.field[row][col]:
self.explore_further(row, col)
def exposebutton(self, row, col, value=""):
if value == "":
value = str(self.field[row][col])
styletext = self.cellcolors[value] + ".TButton"
self.minefieldbuttons[row][col].config(text=value, style=styletext)
if __name__ == '__main__':
root = Tk()
content = ttk.Frame(root, padding=(3,3,12,12))
frame = ttk.Frame(content, borderwidth=2, relief="sunken")
content.grid(column=0, row=0, sticky=(N, S, E, W))
mf = MineField(content, width=10, height=10, mines=10)
root.mainloop()