-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaze.py
More file actions
330 lines (268 loc) · 8.87 KB
/
Maze.py
File metadata and controls
330 lines (268 loc) · 8.87 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
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
import sys
from collections import deque
from point import Point
from colorama import Fore, Back, Style
from priorityQueue import PriorityQueue
import turtle
import time
#color definition
tileColor = "white"
wallColor = "black"
goalColor = "green"
bfsColor = "blue"
solColor = "red"
#screen initialization
wn = turtle.Screen()
wn.bgcolor("white")
wn.title("Maze Solver")
wn.setup()
wn.screensize(2000, 2000)
# Fungsi inputMaze, dengan parameter sebuah file
# digunakan untuk memasukkan matriks sebagai representasi dari maze
# dari file eksternal dengan nama filename
# Sekaligus mencari titik awal masuk dan keluar, disimpan dalam startb, startk, finishb dan finishk
def inputMaze(filename) :
arr = []
f = open("{}.txt".format(filename),"r")
for line in f :
arr.append([int(c) for c in line.strip()])
baris = len(arr)
kolom = len(arr[0])
startr = -1
startc = -1
finishr = -1
finishc = -1
# Melakukan pencarian titik mulai dan akhir (case : kiri dan kanan)
for i in range(baris) :
if (arr[i][0] == 0) :
startr = i
startc = 0
if (arr[i][kolom-1] == 0) :
finishr = i
finishc = kolom-1
# Melakukan pencarian titik mulai dan akhir (case : atas dan bawah)
for i in range(kolom) :
if (arr[0][i] == 0) :
startr = 0
startc = i
if (arr[baris-1][i] == 0) :
finishr = baris-1
finishc = i
# Melakukan validasi apakah matriks bisa dimainkan atau tidak
if ( startr != -1 and startc != -1 and finishr != -1 and finishc != -1 ) :
valid = True
else :
valid = False
f.close()
return arr,startr,startc,finishr,finishc, valid
# Fungsi copy, dengan parameter sebuah matriks m1
# digunakan untuk melakukan DEEP COPY pada sebuah matriks
# sehingga tidak perlu membaca dari file eksternal lagi
def copy(m1) :
m2 = []
for i in range(len(m1)) :
temp = []
for j in range(len(m1[0])) :
temp.append(m1[i][j])
m2.append(temp)
return m2
#Tile block class
class Tile(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.shapesize(0.5)
self.color(tileColor)
self.penup()
self.speed(0)
#Wall block class
class Wall(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color(wallColor)
self.shapesize(0.5)
self.penup()
self.speed(0)
#goal block class
class Goal(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.shapesize(0.5)
#loses square in initialization
self.color("white")
self.penup()
self.speed(0)
#Solution block class
class Sol(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.shapesize(0.5)
#loses square in initialization
self.color("white")
self.penup()
self.speed(0)
#BFS block class
class Bfs(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.shapesize(0.5)
#loses square in initialization
self.color("white")
self.penup()
self.speed(0)
#draw maze 1 as walls
def drawMaze(array):
for y in range(len(array)):
for x in range(len(array[y])):
i = -288 + (x * 12)
j = 288 - (y * 12)
if array[y][x] == 0:
Tile.goto(i,j)
Tile.stamp()
if array[y][x] == 1:
Wall.goto(i, j)
Wall.stamp()
if array[y][x] == 2:
goal.goto(i,j)
goal.color(goalColor)
return (-288 + (len(array[0]) * 12), 288 - (len(array) * 12))
# Fungsi isFeasible, dengan parameter sebuah matriks m, int x dan int y
# digunakan untuk melakukan validasi, apakah koordinat (x,y) valid atau tidak
# DEFINISI VALID : Lebih atau sama dengan 0 , dan kurang dari panjang atau kolom matriks
def isFeasible(m,x,y) :
if ( (m[x][y]==0 or m[x][y]==2) ) :
return True
return False
# Fungsi BFS, dengan parameter maze maze, int x, int y, dan point fp
# merupakan salah satu dari dua fungsi utama dalam program ini
# Memanfaatkan sebuah type data DEQUE, dan melakukan proses Breadth-First Searching
# Jika memiliki solusi, akan me-return sebuah point p
def BFS(maze,x,y,fp) :
de = deque()
de.append(Point(x,y,None))
while ( not(len(de) == 0) ) :
p = de.popleft()
i = -288 + (p.y * 12)
j = 288 - (p.x * 12)
maze[p.x][p.y] = 3
if (p.isEqual(fp)) :
return p
if(isFeasible(maze,p.x-1,p.y)) :
nextP = Point(p.x-1,p.y,p)
de.append(nextP)
if (isFeasible(maze,p.x+1,p.y)) :
nextP = Point(p.x+1,p.y,p)
de.append(nextP)
if(isFeasible(maze,p.x,p.y+1)) :
nextP = Point(p.x,p.y+1,p)
de.append(nextP)
if(isFeasible(maze,p.x,p.y-1)) :
nextP = Point(p.x,p.y-1,p)
de.append(nextP)
#color BFS
Bfs.goto(i,j)
Bfs.color(bfsColor)
Bfs.stamp()
# Fungsi manhattanDist, dengan parameter point point_start dan point point_finish
# digunakan untuk mencari nilai h(n) pada algoritma A*
# Menggunakan manhattan distance karena hanya bisa bergerak ke empat arah
def manhattanDist(point_start,point_finish) :
return (abs(point_start.x - point_finish.x) + abs(point_start.y - point_finish.y))
# Fungsi AStar, dengan parameter maze maze, int x, int y, dan point fpoint
# merupakan salah satu dari dua fungsi utama dalam program ini
# Memanfaatkan type data Priority Queue, yang telah dibuat kelas sendiri sebelumnya
# Akan melakukan pencarian dengan algoritma AStar dengan :
# f(n) = g(n) + h(n)
# dengan g(n) adalah jarak sebenarnya sebuah titik ke titik akhir
# dan h(n) adalah jarak heuristik dari sebuah titik ke titik akhir dengan memanfaatkan manhattanDist
def AStar(maze,x,y,fpoint) :
startPoint = Point(x,y,None)
startPoint.f = startPoint.g = startPoint.h = 0
openList = PriorityQueue()
openList.insert(startPoint)
while ( not(openList.isEmpty()) ) :
current_node = openList.delete()
maze[current_node.x][current_node.y] = 3
i = -288 + (current_node.y * 12)
j = 288 - (current_node.x * 12)
#color BFS
Bfs.goto(i,j)
Bfs.color(bfsColor)
Bfs.stamp()
if (current_node.isEqual(fpoint) ) :
return current_node
children = []
for pos in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
curr_x = current_node.x + pos[0]
curr_y = current_node.y + pos[1]
if (not(isFeasible(maze,curr_x,curr_y))) :
continue
child = Point(curr_x,curr_y,current_node)
children.append(child)
for child in children :
child.g = current_node.g + 1
child.h = manhattanDist(child,fpoint)
child.f = child.g + child.h
openList.insert(child)
# Fungsi main, akan dipanggil saat program ini dijalankan
if __name__ == "__main__":
# Melakukan input nama file dari pengguna, dan memanggil fungsi inputMaze untuk
# memasukkannya ke dalam maze
file = input("Masukkan nama file : ")
maze, startrow, startcolumn, finishrow, finishcolumn, valid = inputMaze(file)
maze2 = copy(maze)
# Util yang diperlukan oleh fungsi-fungsi searching
fp = Point(finishrow, finishcolumn, None)
#Turtle object initialization
Tile = Tile()
Wall = Wall()
goal = Goal()
Sol = Sol()
Bfs = Bfs()
if (valid) :
print("Found")
#Draw Maze
drawMaze(maze)
#BFS execution
p = BFS(maze, startrow, startcolumn,fp)
#draw Solution
while (p.getParent() != None ) :
maze[p.x][p.y] = 4
i = -288 + (p.y * 12)
j = 288 - (p.x * 12)
Sol.goto(i,j)
Sol.color(solColor)
Sol.stamp()
p = p.getParent()
maze[startrow][startcolumn] = 4
i = -288 + (startcolumn * 12)
j = 288 - (startrow * 12)
Sol.goto(i,j)
Sol.color(solColor)
Sol.stamp()
#Draw Maze
drawMaze(maze2)
#A* execution
q = AStar(maze2,startrow,startcolumn,fp)
#draw Solution
while (q.getParent() != None ) :
maze[q.x][q.y] = 4
i = -288 + (q.y * 12)
j = 288 - (q.x * 12)
Sol.goto(i,j)
Sol.color(solColor)
Sol.stamp()
q = q.getParent()
maze2[startrow][startcolumn] = 4
i = -288 + (startcolumn * 12)
j = 288 - (startrow * 12)
Sol.goto(i,j)
Sol.color(solColor)
Sol.stamp()
else :
print("Not Found")
wn.mainloop()