-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAstar-Algorithm.py
More file actions
342 lines (236 loc) · 10.6 KB
/
Astar-Algorithm.py
File metadata and controls
342 lines (236 loc) · 10.6 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
331
332
333
334
335
336
337
338
339
340
341
342
from tkinter import *
from functools import partial
from time import sleep
def center_gui(root):
# Gets the requested values of the height and widht.
windowWidth = root.winfo_reqwidth()
windowHeight = root.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(root.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(root.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
root.geometry("+{}+{}".format(positionRight, positionDown))
def pop_up_window(app):
"""
Displays the start up window with the instructions.
When the pop up is displayed the buttons at the backround
are disabled
"""
def start_button_action():
app.enable_buttons()
win.destroy()
win = Toplevel()
win.wm_title("Welcome")
Label(win, text="Step 1: Select starting point",
font=("Calibri", 13), pady=5, padx=10).pack()
Label(win, text="Step 2: Select end point", font=(
"Calibri", 13), pady=5, padx=10).pack()
Label(win, text="Step 3: Select Obstacles", font=(
"Calibri", 13), pady=5, padx=10).pack()
Label(win, text="Click and hover.Then click again to stop", padx=25).pack()
Label(win, text="Step 4: Press Enter to start",
font=("Calibri", 13), pady=5, padx=10).pack()
Label(win, text="Step 5: Press R to restart",
font=("Calibri", 13), pady=5, padx=10).pack()
Button(win, text="Start", command=start_button_action,
).pack()
win.update_idletasks()
center_gui(win)
class App:
def __init__(self, master):
self.master = master
master.wm_title("A* Algorithm")
self.buttons = []
self.start = []
self.goal = []
self.obstacles = []
self.mode = 0
for i in range(25):
self.buttons.append([])
for j in range(25):
# Initiliaze buttons
button = Button(master, width=2, height=1,
command=partial(self.button_operation, i, j), state="disabled")
self.buttons[i].append(button)
# This event is used for the obstacle setting
self.buttons[i][j].bind('<Enter>', partial(
self.add_obstacle, i, j))
self.buttons[i][j].grid(row=i, column=j)
master.update_idletasks()
center_gui(master)
pop_up_window(self)
def enable_buttons(self):
for i in range(25):
for j in range(25):
self.buttons[i][j].configure(state="normal")
def disable_buttons(self):
for i in range(25):
for j in range(25):
self.buttons[i][j].configure(state="disable")
# Every time a button is clicked this function is triggered
# This function is responsible for controling the flow of the program
def button_operation(self, row, column):
"""
According to the value of 'mode' this fuction
sets the value of start and end. Also by changing
the value of mode it controls when we can set obstacles and
when we can start the algorithm
"""
# Set start mode
if self.mode == 0:
self.start.append(row)
self.start.append(column)
self.mode = 1
self.buttons[row][column].configure(bg='green')
# Set end mode
elif self.mode == 1:
self.goal.append(row)
self.goal.append(column)
self.mode = 2
self.buttons[row][column].configure(bg='red')
elif self.mode == 2:
# Set to set obstacles mode => By hovering over buttons
self.mode = 3
else:
# When the mode = 2 the user cant set obstacles by hovering and the algorithm can start
self.mode = 2
def add_obstacle(self, row, column, event):
# Checks if we are in the obstacle setting mode
if self.mode == 3:
obstacle_node = []
obstacle_node.append(row)
obstacle_node.append(column)
self.obstacles.append(obstacle_node[:])
self.buttons[row][column].configure(bg='black')
def heuristic(self, node1, node2):
result = abs(node1[0] - node2[0]) + abs(node1[1]-node2[1])
return result
def find_neighbors(self, current, obstacles):
neighbors = []
# With current[:] I create a new list and I dont use the pointer to the original list otherwise the end result whould have same lists
right_neighbor = current[:]
right_neighbor[1] = current[1] + 1
if 0 <= right_neighbor[1] < 25 and right_neighbor not in self.obstacles:
neighbors.append(right_neighbor)
left_neighbor = current[:]
left_neighbor[1] = current[1] - 1
if 0 <= left_neighbor[1] < 25 and left_neighbor not in self.obstacles:
neighbors.append(left_neighbor)
up_neighbor = current[:]
up_neighbor[0] = current[0] + 1
if 0 <= up_neighbor[0] < 25 and up_neighbor not in self.obstacles:
neighbors.append(up_neighbor)
down_neighbor = current[:]
down_neighbor[0] = current[0] - 1
if 0 <= down_neighbor[0] < 25 and down_neighbor not in self.obstacles:
neighbors.append(down_neighbor)
down_right_neighbor = current[:]
down_right_neighbor[0] = current[0] + 1
down_right_neighbor[1] = current[1] + 1
if 0 <= down_right_neighbor[0] < 25 and 0 <= down_right_neighbor[1] < 25 and down_right_neighbor not in self.obstacles:
neighbors.append(down_right_neighbor)
up_right_neighbor = current[:]
up_right_neighbor[0] = current[0] - 1
up_right_neighbor[1] = current[1] + 1
if 0 <= up_right_neighbor[0] < 25 and 0 <= up_right_neighbor[1] < 25 and up_right_neighbor not in self.obstacles:
neighbors.append(up_right_neighbor)
up_left_neighbor = current[:]
up_left_neighbor[0] = current[0] - 1
up_left_neighbor[1] = current[1] - 1
if 0 <= up_left_neighbor[0] < 25 and 0 <= up_left_neighbor[1] < 25 and up_left_neighbor not in self.obstacles:
neighbors.append(up_left_neighbor)
down_left_neighbor = current[:]
down_left_neighbor[0] = current[0] + 1
down_left_neighbor[1] = current[1] - 1
if 0 <= down_left_neighbor[0] < 25 and 0 <= down_left_neighbor[1] < 25 and down_left_neighbor not in self.obstacles:
neighbors.append(down_left_neighbor)
return neighbors
def sort_open_set(self, open_set, f_score):
# The index of the list is the same as the index in the open set
# and the value of the index is the f_score of it
index_to_fscore = []
for node in open_set:
f_score_of_node = f_score[node[0]][node[1]]
index_to_fscore.append(f_score_of_node)
sorted_copy = index_to_fscore.copy()
sorted_copy.sort()
sorted_open_set = []
for value in sorted_copy:
min = index_to_fscore.index(value)
sorted_open_set.append(open_set[min])
# We mark that we have transfered this value to the sorted array
index_to_fscore[min] = float('inf')
return sorted_open_set
def reconstruct_path(self, cameFrom, current):
total_path = []
while current != self.start:
self.buttons[current[0]][current[1]].configure(bg='red')
total_path.append(current[:])
current = cameFrom[current[0]][current[1]]
def a_star_algorithm(self, start, goal):
open_set = [start]
g_score = []
f_score = []
came_from = []
# Initialiazation of g_score and came_from
for i in range(25):
f_score.append([])
g_score.append([])
came_from.append([])
for j in range(25):
temp = float('inf')
came_from[i].append([])
g_score[i].append(temp) # set it to infinity
f_score[i].append(temp) # set it to infinity
g_score[start[0]][start[1]] = 0
f_score[start[0]][start[1]] = self.heuristic(start, goal)
while len(open_set) > 0:
self.master.update_idletasks()
sleep(0.02)
open_set = self.sort_open_set(open_set, f_score)
current = open_set[0]
current_row = current[0]
current_column = current[1]
if current == goal:
return self.reconstruct_path(came_from, current)
open_set.remove(current)
neighbors = self.find_neighbors(current, [])
for node in neighbors:
node_row = node[0]
node_column = node[1]
# The weight of every edge is 1
tentative_gScore = g_score[current_row][current_column] + 1
if tentative_gScore < g_score[node_row][node_column]:
came_from[node_row][node_column].append(current_row)
came_from[node_row][node_column].append(
current_column)
g_score[node_row][node_column] = tentative_gScore
f_score[node_row][node_column] = g_score[node_row][node_column] + \
self.heuristic(node, self.goal)
if node not in open_set:
self.buttons[node[0]][node[1]].configure(bg='blue')
open_set.append(node[:])
print("fail!")
def find_path(self, event):
# Checks if we are in the correct mode to start the algorithm
if self.mode == 2:
self.a_star_algorithm(self.start, self.goal)
self.disable_buttons()
def reset(self, event):
if self.mode == 2:
self.start = []
self.goal = []
self.obstacles = []
self.mode = 0
for i in range(25):
for j in range(25):
self.buttons[i][j].configure(bg='SystemButtonFace')
self.enable_buttons()
if __name__ == '__main__':
root = Tk()
app = App(root)
# Starts the algorithm when we press enter
root.bind('<Return>', app.find_path)
# Resets when we press 'R'
root.bind('r', app.reset)
root.mainloop()