-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminesweeper.py
More file actions
151 lines (134 loc) · 4.03 KB
/
minesweeper.py
File metadata and controls
151 lines (134 loc) · 4.03 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
# Console Minesweeper with board size and bomb rate adjustment support
import random
import math
### VARIABLES
rows = 10
cols = 10
bombDensity = 0.1
bombs = int(rows*cols*bombDensity)
# bombs = int(math.sqrt(rows*cols))
################
field = [["-" for x in range(cols)] for y in range(rows)]
bombmap = [["-" for x in range(cols)] for y in range(rows)]
def fillBombs():
while sum(row.count("*") for row in bombmap) < bombs:
bombmap[random.randint(0,rows-1)][random.randint(0,cols-1)] = "*"
fillBombs()
def getSpaces(max, text):
text = str(text)
spacesAmount = max-len(text)
spaces = ''
for i in range(spacesAmount):
spaces += ' '
return spaces
def getSurrounding(row,col):
surrounding = []
for colOffset in [-1,0,1]:
for rowOffset in [-1,0,1]:
newRow = row+rowOffset
newCol = col+colOffset
if colOffset==rowOffset==0 or 0 > newRow or 0 > newCol or newRow >= rows or newCol >= cols: # prevent 0 0 offset and out of bounds bomb checks
continue
surrounding.append([newRow,newCol])
return surrounding
def countSurroundingBombs(row,col):
count = 0
for i in getSurrounding(row,col):
if bombmap[i[0]][i[1]] == "*":
count += 1
if count == 0:
return " "
else:
return str(count)
def flag(row,col):
if field[row][col] == "-":
field[row][col] = "F"
def uncover(row,col):
# Iterative flood fill to avoid recursion limit
stack = [(row,col)]
while stack:
r, c = stack.pop()
if field[r][c] != "-":
continue
if bombmap[r][c] == "*":
return True # BOMB UNCOVERED
surroundingBombs = countSurroundingBombs(r, c)
field[r][c] = surroundingBombs
if surroundingBombs == " ":
for nr, nc in getSurrounding(r, c):
if field[nr][nc] == "-":
stack.append((nr, nc))
return False
def printField(showBombs=False):
if showBombs:
# Deep copy of field
fieldDisplay = [row[:] for row in field]
for row in range(rows):
for col in range(cols):
if bombmap[row][col] == "*":
fieldDisplay[row][col] = "*"
else:
fieldDisplay = field
maxDigitsRow = 0
for row in range(rows):
length = len(str(row))
if length > maxDigitsRow:
maxDigitsRow = length
maxDigitsCol = 0
for col in range(cols):
length = len(str(col))
if length > maxDigitsCol:
maxDigitsCol = length
topLegend = getSpaces(maxDigitsRow+2,"")
for col in range(cols): # add numbers top legend
topLegend += str(col+1) + getSpaces(maxDigitsCol+1,col+1)
print(topLegend)
for row in range(rows):
indent = getSpaces(maxDigitsRow+2,row+1)
# print(indentAmount)
readableRow = str(row+1)+indent
for col in range(cols):
readableRow += fieldDisplay[row][col] + getSpaces(maxDigitsCol,"")
print(readableRow)
def checkWin():
for row in range(rows):
for col in range(cols):
if str(field[row][col]) == "-":
return False
return True
printField(False)
moveCounter = 0
while True:
while True:
try:
chosenCol = int(input("Choose a column:"))-1
chosenRow = int(input("Choose a row:"))-1
if field[chosenRow][chosenCol] in ["-","F"]:
break
else:
raise
except:
print("Choose a different position!")
continue
while True:
action = input("Choose an action -> Hit: 'x', Flag: 'f'").lower()
if action in ["x","f"]:
break
else:
continue
if action == "f":
field[chosenRow][chosenCol] = "F"
printField(False)
print("Flagged.")
if action == "x":
if uncover(chosenRow,chosenCol):
printField(True)
print("BOOM. You died!")
exit()
else:
printField(False)
print("Phew. No bomb.")
moveCounter += 1
if checkWin():
print(f"You win! Tries: {moveCounter}. Configuration: {rows} x {cols} with a bomb density of {bombDensity} ({bombs} bombs).")
exit()