-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
266 lines (203 loc) · 7.68 KB
/
main.py
File metadata and controls
266 lines (203 loc) · 7.68 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
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
# This Python file uses the following encoding: utf-8
import sys
from queue import PriorityQueue
from package.Puzzle import NPuzzle
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import *
from PyQt6 import uic, QtWidgets
import package.ui.resource_rc as resource_rc
# Important:
# You need to run the following command to generate the ui_form.py file
# pyside6-uic form.ui -o ui_form.py, or
# pyside2-uic form.ui -o ui_form.py
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
uic.loadUi("designer/form.ui", self)
self.setWindowTitle("N-Puzzle")
self.setFixedSize(880, 760)
self.stackedWidget:QStackedWidget
self.nPzl= NPuzzle(9)
self.goal = self.nPzl.getGoal()
self.puzzle = self.nPzl.getPuzzle()
self.mode = self.nPzl.getN()
self.running = False
self.Btns = [self.__dict__[f"puzzle_{i+1}"]
for i in range(self.nPzl.getN())]
self._8_initial_styles = [self.__dict__[f"puzzle_{i+1}"].styleSheet()
for i in range(9)]
self._15_initial_styles = [self.__dict__[f"puzzle_{i+1}"].styleSheet()
for i in range(9, 25)]
self.styles = self._8_initial_styles
self.lastPeace = self.Btns[-1].styleSheet()
def movePuzzle(self) -> None:
""" Move the a piece of a puzzle you received with the sender
Returns:
None
"""
target = self.sender()
target_num = int(target.objectName().split('_')[1])
if self.mode == 16:
target_num -=9
if self.running:
if self.isClickMoved(target_num):
self.swapStyleSheet(target_num)
self.swapZero(target_num)
self.updatePuzzle()
self.nPzl.setMoves()
self.label.setText(str(self.nPzl.getMoves()))
if self.clear():
self.Btns[-1].setStyleSheet(self.lastPeace)
self.running = False
def isClickMoved(self, target_num) -> bool:
""" Move the tile you received with the sender
Returns:
bool: The result of logical operation
"""
zero_idx = self.puzzle.index(0)
target_idx = self.puzzle.index(self.puzzle[target_num-1])
n = self.nPzl.getn()
return (abs(zero_idx - target_idx) == n or
target_idx//n == zero_idx//n and abs(zero_idx - target_idx) == 1)
def swapStyleSheet(self, target_num) -> None:
""" Move the tile you received with the sender
Args:
target_num (int): Number of the puzzle received by sender.
Returns:
None
"""
zero_idx = self.puzzle.index(0)
target_idx = self.puzzle.index(self.puzzle[target_num-1])
temp = self.Btns[target_idx].styleSheet()
self.Btns[target_idx].setStyleSheet("")
self.Btns[zero_idx].setStyleSheet(temp)
def swapZero(self, target_num) -> None:
""" Move the tile you received with the sender
Args:
target_num (int): Number of the puzzle received by sender.
Returns:
None
"""
zero_idx = self.puzzle.index(0)
target_idx = self.puzzle.index(self.puzzle[target_num-1])
distance = abs(zero_idx - target_idx)
if distance == 1:
if zero_idx > target_idx:
self.puzzle = self.nPzl.moveLeft()
else:
self.puzzle = self.nPzl.moveRight()
elif distance == self.nPzl.getn():
if zero_idx > target_idx:
self.puzzle = self.nPzl.moveUp()
else:
self.puzzle = self.nPzl.moveDown()
def updatePuzzle(self, other=None) -> None:
""" Receive goal, puzzle, mode from self.nPzl and put it
Returns:
None
"""
if other==None:
self.goal = self.nPzl.getGoal()
self.mode = self.nPzl.getN()
self.puzzle = self.nPzl.getPuzzle()
else:
self.goal = other.getGoal()
self.mode = other.getN()
self.puzzle = other.getPuzzle()
def shuffle(self) -> None:
""" Shuffle the puzzle according to self.puzzle
Returns:
None
"""
self.running = True
self.puzzle = self.nPzl.createSolvablePuzzle()
for i in range(len(self.Btns)):
self.Btns[i].setStyleSheet(
self.styles[self.goal.index(self.puzzle[i])]
)
self.Btns[self.puzzle.index(0)].setStyleSheet("")
self.label.setText("0")
def clear(self) -> bool:
""" Returns whether the game is cleared or not
Returns:
bool: The result of logical operation
"""
return self.running == True and self.goal == self.puzzle
def whatMode(self, N):
""" Select mode according to the value of 'N'
Args:
None
"""
if N == 9:
self.stackedWidget.setCurrentWidget(self.page)
self.styles = self._8_initial_styles
for i in range(self.mode):
self.Btns.append(self.__dict__[f"puzzle_{i+1}"])
elif N == 16:
self.stackedWidget.setCurrentWidget(self.page_2)
self.styles = self._15_initial_styles
for i in range(self.mode):
self.Btns.append(self.__dict__[f"puzzle_{i+1+9}"])
def changeMode(self):
""" Change mode according to the value of 'N'
Args:
None
"""
target = self.sender()
N = int(target.objectName().split('_')[1])+1
self.nPzl.updatePuzzle(N)
self.updatePuzzle()
self.Btns = []
self.whatMode(N)
self.lastPeace = self.Btns[-1].styleSheet()
for i in range(len(self.Btns)):
self.Btns[i].setStyleSheet(self.styles[i])
self.running = False
def solve(self, initial_board):
"""
returns a list of moves from 'initial_board' to goal state
calculated using A* algorithm
"""
queue = PriorityQueue()
queue.put(initial_board.to_pq_entry(0))
i = 1
cnt = 1
while not queue.empty():
board = queue.get()[2]
cnt +=1
if not board.is_goal():
for neighbour in board.neighbours():
if neighbour != board.previous:
queue.put(neighbour.to_pq_entry(i))
i += 1
else:
return board.get_previous_states()
return None
def ai(self):
moves = self.solve(self.nPzl)
for i in range(len(moves)):
self.updatePuzzle(moves[i])
self.ai_swapStyleSheet()
self.label.setText(str(moves[i].getMoves()))
# moves[i].display()
# print(moves[i].get_f())
self.reset()
if self.clear():
self.Btns[-1].setStyleSheet(self.lastPeace)
self.running = False
def ai_swapStyleSheet(self):
for i in range(len(self.styles)):
self.Btns[i].setStyleSheet(
self.styles[self.goal.index(self.puzzle[i])]
)
self.Btns[self.puzzle.index(0)].setStyleSheet("")
def reset(self):
loop = QEventLoop()
QTimer.singleShot(100, loop.quit)
loop.exec()
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec()