-
Notifications
You must be signed in to change notification settings - Fork 5
/
puzzleNgui.py
372 lines (316 loc) · 11.6 KB
/
puzzleNgui.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import sys
import os
import enum
import pygame
from pygame.locals import *
from config.config import Config
import argparse
import torch.multiprocessing as mp
import time
import torch
from environment.PuzzleN import PuzzleN
from search.BWAS import batchedWeightedAStarSearch
from networks.getNetwork import getNetwork
class GUIState(enum.Enum):
ready = 0
startSolving = 1
solving = 2
solved = 3
fastForward = 4
rewind = 5
class GUI:
def __init__(self, game):
self.game = game
self.rowLength = self.game.rowLength
self.N = self.game.N
self.tileSize = 320 // self.rowLength
self.tileGap = 8
self.windowHeight = 480
self.windowWidth = 640
self.fps = 30
self.blank = None
self.colours = {
"black": (0, 0, 0),
"white": (255, 255, 255),
"red": (230, 127, 119),
"grey": (242, 242, 242)
}
self.bgColour = self.colours["grey"]
self.tileColour = self.colours["red"]
self.tileTextColour = self.colours["white"]
self.textColour = self.colours["black"]
self.xMargin = int(
(self.windowWidth - (self.tileSize * self.rowLength + (self.rowLength - 1)))
/ 2
)
self.yMargin = int(
(
self.windowHeight
- (self.tileSize * self.rowLength + (self.rowLength - 1))
)
/ 2
)
pygame.init()
self.fpsClock = pygame.time.Clock()
self.displaySurf = pygame.display.set_mode(
(self.windowWidth, self.windowHeight)
)
pygame.display.set_caption("Slide Puzzle")
self.fontSize = 20
self.titleFontSize = 30
self.font = pygame.font.SysFont("Consolas", self.fontSize)
self.titleFont = pygame.font.SysFont(
"Consolas", self.titleFontSize)
self.titleSurf, self.titleRect = self.makeText(
str(self.N) + " Puzzle",
self.titleFont,
self.textColour,
None,
self.xMargin,
25,
)
self.solveSurf, self.solveRect = self.makeText(
"Solve",
self.font,
self.textColour,
None,
self.windowWidth - 85,
self.windowHeight - 40,
)
self.scrambleSurf, self.scrambleRect = self.makeText(
"Scramble",
self.font,
self.textColour,
None,
self.windowWidth - 119,
self.windowHeight - 70,
)
self.rewindSurf, self.rewindRect = self.makeText(
"<<",
self.font,
self.textColour,
None,
self.windowWidth - 190,
33,
)
self.backwardSurf, self.backwardRect = self.makeText(
"<",
self.font,
self.textColour,
None,
self.windowWidth - 140,
33,
)
self.forwardSurf, self.forwardRect = self.makeText(
">",
self.font,
self.textColour,
None,
self.windowWidth - 100,
33,
)
self.fastForwardSurf, self.fastForwardRect = self.makeText(
">>",
self.font,
self.textColour,
None,
self.windowWidth - 60,
33,
)
self.state = GUIState.ready
self.moves = []
self.moveIdx = 0
def checkForQuit(self):
for event in pygame.event.get(QUIT): # get all the QUIT events
pygame.quit()
sys.exit() # terminate if any QUIT events are present
for event in pygame.event.get(KEYUP): # get all the KEYUP events
if event.key == K_ESCAPE:
pygame.quit()
sys.exit() # terminate if the KEYUP event was for the Esc key
pygame.event.post(event) # put the other KEYUP event objects back
def checkInput(self):
for event in pygame.event.get(): # event handling loop
if not (self.state == GUIState.ready or self.state == GUIState.solved):
return
if event.type == KEYUP:
# check if the user pressed a key to slide a tile
if event.key in (K_LEFT, K_a):
self.game.doAction("L")
elif event.key in (K_RIGHT, K_d):
self.game.doAction("R")
elif event.key in (K_UP, K_w):
self.game.doAction("U")
elif event.key in (K_DOWN, K_s):
self.game.doAction("D")
elif event.type == MOUSEBUTTONUP:
if self.solveRect.collidepoint(event.pos):
self.state = GUIState.startSolving
elif self.scrambleRect.collidepoint(event.pos):
self.game.state = self.game.generateScramble(500)
self.state = GUIState.ready
elif self.rewindRect.collidepoint(event.pos):
self.state = GUIState.rewind
elif self.backwardRect.collidepoint(event.pos):
self.backwardMove()
elif self.forwardRect.collidepoint(event.pos):
self.forwardMove()
elif self.fastForwardRect.collidepoint(event.pos):
self.state = GUIState.fastForward
def drawGame(self, msg):
self.displaySurf.fill(self.bgColour)
if msg:
self.textSurf, self.textRect = self.makeText(
msg,
self.font,
self.textColour,
self.bgColour,
30,
self.windowHeight - 40,
)
self.displaySurf.blit(self.textSurf, self.textRect)
for tileY in range(len(self.game.state)):
for tileX in range(len(self.game.state[0])):
if self.game.state[tileY][tileX] != 0:
self.drawTile(tileX, tileY, int(
self.game.state[tileY][tileX]))
self.displaySurf.blit(self.titleSurf, self.titleRect)
self.displaySurf.blit(self.solveSurf, self.solveRect)
self.displaySurf.blit(self.scrambleSurf, self.scrambleRect)
if self.state == GUIState.solved:
if self.moveIdx > 0:
self.displaySurf.blit(self.rewindSurf, self.rewindRect)
self.displaySurf.blit(self.backwardSurf, self.backwardRect)
if self.moveIdx < len(self.moves):
self.displaySurf.blit(self.forwardSurf, self.forwardRect)
self.displaySurf.blit(
self.fastForwardSurf, self.fastForwardRect)
def makeText(self, text, font, colour, bgColour, top, left):
# create the Surface and Rect objects for some text.
textSurf = font.render(text, True, colour, bgColour)
textRect = textSurf.get_rect()
textRect.topleft = (top, left)
return (textSurf, textRect)
def drawTile(self, tileX, tileY, number, adjX=0, adjY=0):
left, top = self.getLeftTopOfTile(tileX, tileY)
pygame.draw.rect(
self.displaySurf,
self.tileColour,
(left + adjX + self.tileGap // 2, top + adjY + 2,
self.tileSize - self.tileGap, self.tileSize - self.tileGap)
)
textSurf = self.font.render(str(number), True, self.tileTextColour)
textRect = textSurf.get_rect()
textRect.center = (
left + int(self.tileSize / 2) + adjX,
top + int(self.tileSize / 2) + adjY,
)
self.displaySurf.blit(textSurf, textRect)
def getLeftTopOfTile(self, tileX, tileY):
left = self.xMargin + (tileX * self.tileSize)
top = self.yMargin + (tileY * self.tileSize)
return (left, top)
def setMoves(self, moves):
self.moves = moves
self.moveIdx = 0
def forwardMove(self):
if self.moveIdx < len(self.moves):
self.game.doAction(self.moves[self.moveIdx])
self.moveIdx += 1
else:
self.state = GUIState.solved
def backwardMove(self):
if self.moveIdx > 0:
forwardMove = self.moves[self.moveIdx - 1]
backwardMoveDict = {"R": "L",
"U": "D",
"D": "U",
"L": "R"
}
backwardMove = backwardMoveDict[forwardMove]
self.game.doAction(backwardMove)
self.moveIdx -= 1
else:
self.state = GUIState.solved
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-n", "--network", required=True, help="Path of Saved Network", type=str
)
parser.add_argument(
"-c", "--config", required=True, help="Path of Config File", type=str
)
args = parser.parse_args()
conf = Config(args.config)
loadPath = args.network
if not os.path.isfile(loadPath):
raise ValueError("No Network Saved in this Path")
device = torch.device(0 if torch.cuda.is_available() else "cpu")
net = getNetwork(conf.puzzle, conf.networkType)(conf.puzzleSize)
net.load_state_dict(torch.load(loadPath))
net.eval()
puzzleN = PuzzleN(conf.puzzleSize)
GUI = GUI(puzzleN)
solveQueue = mp.Queue()
while True: # main game loop
# contains the message to show in the upper left corner.
if GUI.state == GUIState.startSolving:
solveProcess = mp.Process(
target=batchedWeightedAStarSearch,
args=(
puzzleN.state,
conf.depthWeight,
conf.numParallel,
puzzleN,
net,
device,
conf.maxSearchItr,
True,
solveQueue,
),
)
solveProcess.start()
GUI.state = GUIState.solving
if not solveQueue.empty():
(
moves,
numNodesGenerated,
searchItr,
isSolved,
solveTime,
) = solveQueue.get()
if isSolved:
print("Solved!")
print("Moves are %s" % "".join(moves))
print("Solve Length is %i" % len(moves))
print("Time of Solve is %.3f seconds" % solveTime)
GUI.state = GUIState.solved
GUI.setMoves(moves)
else:
print("No Solution Found")
print("Search time is %.3f seconds" % solveTime)
GUI.state = GUIState.ready
print("%i Nodes were generated" % numNodesGenerated)
print("There were %i search iterations" % searchItr)
prevTime = time.time()
if puzzleN.checkIfSolvedSingle(puzzleN.state):
msg = "Solved!"
elif GUI.state == GUIState.solving:
msg = "Solving..."
elif GUI.state != GUIState.ready:
msg = "Found a %d move solution in %.2f seconds" % (
len(moves), solveTime)
else:
msg = "Press arrow keys to slide."
GUI.drawGame(msg)
GUI.checkForQuit()
GUI.checkInput()
currTime = time.time()
if (GUI.state == GUIState.fastForward or GUI.state == GUIState.rewind) and currTime - prevTime > 0.25:
prevTime = currTime
if GUI.state == GUIState.fastForward:
GUI.forwardMove()
else:
GUI.backwardMove()
pygame.display.update()
GUI.fpsClock.tick(GUI.fps)