-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
394 lines (292 loc) · 11.5 KB
/
main.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import pygame
import time
from queue import PriorityQueue
try:
ROWS = int(input("Enter the size of grid (e.g., 25): "))
except Exception:
print('Due to invalid input recieved, the number of rows has been set as 50')
ROWS = 50
try:
algo = int(input("Enter 1 For Dijkstra's Algorithm, 2 for A* Algorithm: "))
except:
print('Due to invalid input recieved A* Algorithm will be implemented as Default.')
algo = 2
WIDTH = 800
GAP = 800//ROWS
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("Path Finding Algorithm Visualiser")
C_VISITED = (232, 252, 194)
C_BOUNDARY = (177,204,116)
WHITE = (255,255,255)
GREY = (210,210,210)
BLACK = (0,0,0)
ORANGE = (255, 127, 0)
VIOLET = (148, 0, 211)
C_FINAL_PATH = (245, 255, 144)
C_JUMPED = (223, 227, 120)
C_BOUNDARY_WEIGHT = (197, 222, 201)
class Spot:
def __init__(self, row, col, width, total_rows):
self.row = row
self.col = col
self.x = width * row
self.y = width * col
self.color = WHITE
self.neighbors = []
self.width = width
self.total_rows = total_rows
self.weight = 1
def get_pos(self):
return self.row, self.col
def is_visited(self):
return self.color == C_VISITED
def is_barrier(self):
return self.color == BLACK
def is_weighted(self):
return self.color == (238,238,238) or self.color == (235, 216, 216) or self.color == C_BOUNDARY_WEIGHT
def is_open(self):
return self.color == C_BOUNDARY
def is_start(self):
return self.color == ORANGE
def is_end(self):
return self.color == VIOLET
def reset(self):
self.color = WHITE
def make_visited(self):
if self.is_weighted():
self.color = (235, 216, 216)
else:
self.color = C_VISITED
def make_barrier(self):
self.color = BLACK
def add_weight(self):
#self.color = BLACK
self.weight = self.weight+ 10
self.color = (238,238,238)
def make_open(self):
if self.is_weighted():
self.color = C_BOUNDARY_WEIGHT
else:
self.color = C_BOUNDARY
def make_start(self):
self.color = ORANGE
def make_end(self):
self.color = VIOLET
def make_path(self):
if self.weight>1:
self.color = C_JUMPED
else:
self.color = C_FINAL_PATH
def draw(self, win):
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))
def update_neighbors(self, grid):
# Down Test
if self.row<self.total_rows-1 and not grid[self.row+1][self.col].is_barrier():
self.neighbors.append(grid[self.row+1][self.col])
# Up Test
if self.row>0 and not grid[self.row-1][self.col].is_barrier():
self.neighbors.append(grid[self.row-1][self.col])
# Left Test
if self.col>0 and not grid[self.row][self.col-1].is_barrier():
self.neighbors.append(grid[self.row][self.col-1])
# Right Test
if self.col<self.total_rows-1 and not grid[self.row][self.col+1].is_barrier():
self.neighbors.append(grid[self.row][self.col+1])
def __lt__(self, other):
return False
def h(p1, p2):
'''
This functions is used to return the manhattan distance between two points passed as arguments
'''
x1, y1 = p1
x2, y2 = p2
return abs(x2-x1)+abs(y2-y1)
def make_grid(rows, width):
'''
This Functions defined rows*rows number of Spots and adds the into a grid (a nested list) and return it.
'''
grid = []
for i in range(0, rows):
grid.append([])
for j in range(0, rows):
grid[i].append((Spot(i, j, GAP, rows)))
return grid
def draw_grid(win, rows, width):
# Draw Horizontal Lines
for i in range(rows):
pygame.draw.line(win, GREY, (0, i*GAP), (width, i*GAP))
# Draw Vertical Lines
for j in range(rows):
pygame.draw.line(win, GREY, (j*GAP, 0), (j*GAP, width))
def draw(win, grid, rows, width):
win.fill(WHITE)
for row in grid:
for spot in row:
spot.draw(win)
draw_grid(win, rows, width)
pygame.display.update()
def get_clicked_pos(pos, rows, width):
'''
Takes the ciurrent position of mouse, number of rows and width of frame and returns the index of grid element to which the mouse is pointing.
'''
x, y = pos
row = x // GAP
col = y // GAP
return row, col
def reconstruct_path(came_from, current, draw):
while current in came_from:
current = came_from[current]
current.make_path()
draw()
def a_star_algorithm(draw, grid, start, end):
pygame.display.set_caption("A* Path Finding Algorithm Visualiser")
# count variable is used in case of conflict when two values in priority queue have same priority
count = 0
# Defined a Priority Queue
open_set = PriorityQueue()
# Added start position to the Queue
open_set.put((0, count, start))
# To keep track of path
came_from = {}
# Initialising G-Score (Distance Travelled to reach that spot)
g_score = {spot: float("inf") for row in grid for spot in row}
g_score[start] = 0
# Initialising F-Score (Total Distance to be travelled from starting to end through this spot to reach destination)
f_score = {spot: float("inf") for row in grid for spot in row}
f_score[start] = h(start.get_pos(), end.get_pos())
# A set to keep track whether or not a given value exists in Priority Queue (Used a set here as PriorityQueue doest support testing presence.)
open_set_hash = {start}
while not open_set.empty():
# In case user wanys to exit while the algorith is running.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
current = open_set.get()[2]
open_set_hash.remove(current)
if current == end:
reconstruct_path(came_from, end, draw)
end.make_end()
start.make_start()
return True
for neighbor in current.neighbors:
temp_g_score = g_score[current]+neighbor.weight
# If the new gscore of neighbors of current is less than the score that was before.
if temp_g_score<g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = temp_g_score
f_score[neighbor] = temp_g_score + h(neighbor.get_pos(), end.get_pos())
if neighbor not in open_set_hash:
count+=1
open_set.put((f_score[neighbor], count, neighbor))
open_set_hash.add(neighbor)
neighbor.make_open()
draw()
if current!=start:
current.make_visited()
return False
def dijkstra_algorithm(draw, grid, start, end):
pygame.display.set_caption("Dijkstra's Path Finding Algorithm Visualiser")
# count variable is used in case of conflict when two values in priority queue have same priority
count = 0
# Defined a Priority Queue
open_set = PriorityQueue()
# Added start position to the Queue
open_set.put((0, count, start))
# To keep track of path
came_from = {}
# Initialising G-Score (Distance Travelled to reach that spot)
g_score = {spot: float("inf") for row in grid for spot in row}
g_score[start] = 0
# A set to keep track whether or not a given value exists in Priority Queue (Used a set here as PriorityQueue doest support testing presence.)
open_set_hash = {start}
while not open_set.empty():
# In case user wanys to exit while the algorith is running.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
current = open_set.get()[2]
open_set_hash.remove(current)
if current == end:
reconstruct_path(came_from, end, draw)
end.make_end()
start.make_start()
return True
for neighbor in current.neighbors:
temp_g_score = g_score[current]+neighbor.weight
# If the new gscore of neighbors of current is less than the score that was before.
if temp_g_score<g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = temp_g_score
if neighbor not in open_set_hash:
count+=1
open_set.put((g_score[neighbor], count, neighbor))
open_set_hash.add(neighbor)
neighbor.make_open()
draw()
if current!=start:
current.make_visited()
return False
def main(win, width):
#ROWS = 50#int(input("Enter the size of grid: "))
grid = make_grid(ROWS, width)
start = None
end = None
run = True
started = False
make_barriers = False
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# If algorithm has started then user can't edit grid or do anything else, other than exiting.
if started:
continue
# Left Mouse Button
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, ROWS, width)
spot = grid[row][col]
# If start is not defined and the point clicked is not equal to end the make the point as start
if not start and spot!=end:
spot.make_start()
start = spot
# If start is defined and end is not defined and the point clicked is not equal to start the make the point as end
elif not end and spot!=start:
spot.make_end()
end = spot
# if start and end have beend defined and the spot is not equal to start or end then define the spot as barrier
elif spot!=start and spot!=end:
if make_barriers:
spot.make_barrier()
else:
spot.add_weight()
#spot.make_barrier()
# Right Mouse Button
if pygame.mouse.get_pressed()[2]:
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, ROWS, width)
spot = grid[row][col]
spot.reset()
if spot == start:
start = None
elif spot == end:
end = None
# Event to trigger Algorithm
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
make_barriers = not make_barriers
if event.key == pygame.K_SPACE and not started:
for row in grid:
for spot in row:
spot.update_neighbors(grid)
if algo == 1:
dijkstra_algorithm(lambda: draw(win, grid, ROWS, width), grid, start, end)
elif algo ==2:
a_star_algorithm(lambda: draw(win, grid, ROWS, width), grid, start, end)
if event.key == pygame.K_ESCAPE:
start = None
end = None
grid = make_grid(ROWS, width)
pygame.quit()
main(WIN, 800)