-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminesweeper.py
320 lines (245 loc) · 8.47 KB
/
minesweeper.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
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
import argparse
from common import Cell, Game
from random import randrange
import math
from draw import drawCellsBatch, drawCloseIcon, drawTimer, drawFlagCount, closeDraw, initDraw, drawCell, drawSmile, getScreenSize, refreshScreen, disableRefresh, enableRefresh
import time
import threading
from stack import Stack
from shell import killNickel, restartNickel
from koboInput import initKoboInput, closeKoboInput, addKoboInputListener, removeKoboInputListener, ListenerName
running = True
def nonRepeatingNumbers(maxNumber: int):
array: list[int] = [i for i in range(maxNumber)]
def getNumber():
nonlocal maxNumber
if maxNumber < 0:
return
random = randrange(0, maxNumber)
number = array[random]
array[random] = array[maxNumber-1]
array[maxNumber-1] = number
maxNumber -= 1
return number
return getNumber
def getCellNeighbours(game: Game, x: int, y: int) -> list[Cell]:
neighbours: list[Cell] = []
for i in range(-1, 2):
for j in range(-1, 2):
newX = i+x
newY = j+y
if (x != newX or y != newY) and newX > -1 and newY > -1 and newX < game.maxX and newY < game.maxY:
neighbours.append(game.cells[newX][newY])
return neighbours
def generateGrid(maxX: int, maxY: int) -> list[list[Cell]]:
cellList = []
for x in range(maxX):
cellList.append([])
for y in range(maxY):
cellList[x].append(Cell(x, y))
return cellList
def placeMines(game: Game, mineCount: int) -> list[Cell]:
randomNumberGenerator = nonRepeatingNumbers(game.maxX * game.maxY)
cellsWithMines: list[Cell] = []
for _ in range(mineCount):
randomNumber = randomNumberGenerator()
if randomNumber is None:
continue
x = math.floor(randomNumber % game.maxX)
y = math.floor(randomNumber / game.maxX)
game.cells[x][y].isMine = True
cellsWithMines.append(game.cells[x][y])
return cellsWithMines
def placeNumbers(game: Game, cellsWithMines: list[Cell]):
for cell in cellsWithMines:
neighbours = getCellNeighbours(game, cell.x, cell.y)
for neighbourCell in neighbours:
neighbourCell.number += 1
def moveMine(game: Game, cell: Cell):
moved = False
for y in range(game.maxY):
for x in range(game.maxX):
if game.cells[x][y].isMine:
continue
game.cells[x][y].isMine = True
neighbours = getCellNeighbours(game, x, y)
for neighbour in neighbours:
neighbour.number += 1
moved = True
break
if moved:
break
cell.isMine = False
neighbours = getCellNeighbours(game, cell.x, cell.y)
for neighbour in neighbours:
neighbour.number -= 1
def openMultiple(game: Game, cell: Cell):
myStack = Stack()
cell.isOpen = True
myStack.push(cell)
cellsToDraw: list[Cell] = []
while myStack.size() > 0:
poppedCell = myStack.pop()
neighbours = getCellNeighbours(game, poppedCell.x, poppedCell.y)
for neighbour in neighbours:
if not neighbour.isFlagged and not neighbour.isOpen:
neighbour.isOpen = True
game.nonMineCellsOpened += 1
if neighbour.number == 0:
myStack.push(neighbour)
cellsToDraw.append(neighbour)
drawCellsBatch(game, cellsToDraw)
def endGame(game: Game, won: bool):
game.gameOver = True
if not won:
game.hitMine = True
for row in game.cells:
for cell in row:
cell.isOpen = True
else:
for row in game.cells:
for cell in row:
if cell.isOpen:
continue
cell.isFlagged = True
timeDiff = (time.time() * 1000) - game.startTime
drawBoard(game)
drawTimer(math.floor(timeDiff / 1000))
drawFlagCount(0)
def checkWin(game: Game):
if game.nonMineCellsOpened < (game.maxX * game.maxY) - game.minesCount:
return
endGame(game, True)
def flagCell(game: Game, cell: Cell):
if cell.isFlagged:
cell.isFlagged = False
game.flagsPlaced -= 1
else:
if not cell.isOpen:
cell.isFlagged = True
game.flagsPlaced += 1
drawCell(game, cell)
drawFlagCount(game.minesCount - game.flagsPlaced)
def openCell(game: Game, cell: Cell):
if game.clicks == 0:
if cell.isMine:
moveMine(game, cell)
openCell(game, cell)
return
game.startTime = int(time.time() * 1000)
if not cell.isFlagged and not cell.isOpen:
if cell.isMine:
cell.isOpen = True
endGame(game, False)
else:
if cell.number == 0:
openMultiple(game, cell)
else:
cell.isOpen = True
game.nonMineCellsOpened += 1
game.clicks += 1
drawCell(game, cell)
checkWin(game)
def createGame(x: int, y: int, mines: int):
currentGame = Game(generateGrid(x, y), x, y, mines)
cellsWithMines = placeMines(
currentGame, currentGame.minesCount)
placeNumbers(currentGame, cellsWithMines)
return currentGame
def drawBoard(game: Game):
enableRefresh()
drawSmile(game)
drawTimer(0)
drawFlagCount(game.minesCount)
drawCloseIcon()
disableRefresh()
refreshScreen()
cellsToDraw: list[Cell] = []
for cell1 in game.cells:
for cell2 in cell1:
cellsToDraw.append(cell2)
drawCellsBatch(game, cellsToDraw)
def getCellTouched(game: Game, touchX: int, touchY: int):
for rows in game.cells:
for cell in rows:
x = cell.screenX
y = cell.screenY
x2 = x + cell.size
y2 = y + cell.size
if x <= touchX <= x2 and y <= touchY <= y2:
return cell
def isSmileTouched(game: Game, touchX: int, touchY: int):
x1, x2, y1, y2 = game.smileRect
if x1 <= touchX <= x2 and y1 <= touchY <= y2:
return True
return False
def isCloseTouched(touchX: int, touchY: int):
if 0 <= touchX <= 120 and 0 <= touchY < 120:
return True
return False
def handleTap(game: Game, touchX: int, touchY: int):
global running
closeTouched = isCloseTouched(touchX, touchY)
if closeTouched:
running = False
return
smileTouched = isSmileTouched(game, touchX, touchY)
if smileTouched:
removeListeners(game)
newGame = createGame(game.maxX, game.maxY, game.minesCount)
t = threading.Thread(target=drawBoard, args=(newGame,))
t.start()
addListeners(newGame)
return
if game.gameOver:
return
touchedCell = getCellTouched(game, touchX, touchY)
if touchedCell is None:
return
openCell(game, touchedCell)
def handleHoldEnd(game: Game, touchX: int, touchY: int):
if game.gameOver:
return
touchedCell = getCellTouched(game, touchX, touchY)
if touchedCell is None:
return
flagCell(game, touchedCell)
def addListeners(game: Game):
tapListener = addKoboInputListener(ListenerName.onTap, lambda x,
y: handleTap(game, x, y))
holdEndListener = addKoboInputListener(ListenerName.onHoldEnd, lambda x,
y, _: handleHoldEnd(game, x, y))
game.tapListener = tapListener
game.holdEndListener = holdEndListener
def removeListeners(game: Game):
if game.tapListener is not None:
removeKoboInputListener(ListenerName.onTap, game.tapListener)
if game.holdEndListener is not None:
removeKoboInputListener(ListenerName.onHoldEnd, game.holdEndListener)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-x', dest='x', type=int, help='Number of rows')
parser.add_argument('-y', dest='y', type=int, help='Number of columns')
parser.add_argument('-mines', dest='mines',
type=int, help='Number of mines')
args = parser.parse_args()
x = args.x or 9
y = args.y or 9
mines = args.mines or 10
if mines >= x * y:
mines = (x*y) - 1
killNickel()
initDraw()
screenWidth, _ = getScreenSize()
initKoboInput(screenWidth, grabInput=False)
currentGame = createGame(x, y, mines)
drawBoard(currentGame)
addListeners(currentGame)
while running:
continue
closeKoboInput()
closeDraw()
restartNickel()
print("Goodbye")
if __name__ == "__main__":
main()