-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
307 lines (251 loc) Β· 13.8 KB
/
main.py
File metadata and controls
307 lines (251 loc) Β· 13.8 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
import asyncio
import sys
import pygame
from settings import *
from box import Box
from button import Button
from queue import PriorityQueue
pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
priority_queue = PriorityQueue() #Dijkstra and A*
queue = [] #BFS
stack = [] #DFS
path = []
def get_font(size):
return pygame.font.Font("assets/font.ttf", size)
def initialize_grid(rows, col):
for i in range(rows):
tmp = []
for j in range(col):
tmp.append(Box(i, j))
GRID.append(tmp)
for i in range(ROWS):
for j in range(COLUMNS):
GRID[i][j]._set_neighbors()
def heuristic(a, b):
x1, y1 = a.x, a.y
x2, y2 = b.x, b.y
return (abs(x1 - x2) + abs(y1 - y2))
async def algorithm_menu_screen(first_run=True, grid_cleared=False):
running = True
button_height, button_spacing = 100, 50
while running:
screen.fill((50, 50, 50))
MENU_MOUSE_POS = pygame.mouse.get_pos()
MENU_TEXT = get_font(35).render("Choose an Algorithm", True, "#b68f40")
MENU_RECT = MENU_TEXT.get_rect(center=(WINDOW_WIDTH // 2, 50))
DIJKSTRA_BUTTON = Button(image=pygame.image.load("assets/buttonBG.png"),
pos=(WINDOW_WIDTH // 2, 150),
text_input="DIJKSTRA", font=get_font(40),
base_color="#d7fcd4", hovering_color="White")
ASTAR_BUTTON = Button(image=pygame.image.load("assets/buttonBG.png"),
pos=(WINDOW_WIDTH // 2, 150 + button_height + button_spacing),
text_input="A* Search", font=get_font(40),
base_color="#d7fcd4", hovering_color="White")
BFS_BUTTON = Button(image=pygame.image.load("assets/buttonBG.png"),
pos=(WINDOW_WIDTH // 2, 150 + 2 * (button_height + button_spacing)),
text_input="BFS", font=get_font(40),
base_color="#d7fcd4", hovering_color="White")
DFS_BUTTON = Button(image=pygame.image.load("assets/buttonBG.png"),
pos=(WINDOW_WIDTH // 2, 150 + 3 * (button_height + button_spacing)),
text_input="DFS", font=get_font(40),
base_color="#d7fcd4", hovering_color="White")
screen.blit(MENU_TEXT, MENU_RECT)
for button in [DIJKSTRA_BUTTON, ASTAR_BUTTON, BFS_BUTTON, DFS_BUTTON]:
button.changeColor(MENU_MOUSE_POS)
button.update(screen)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if DIJKSTRA_BUTTON.checkForInput(MENU_MOUSE_POS):
await main("Dijkstra", first_run, grid_cleared)
if ASTAR_BUTTON.checkForInput(MENU_MOUSE_POS):
await main("A-star", first_run, grid_cleared)
if BFS_BUTTON.checkForInput(MENU_MOUSE_POS):
await main("BFS", first_run, grid_cleared)
if DFS_BUTTON.checkForInput(MENU_MOUSE_POS):
await main("DFS", first_run, grid_cleared)
pygame.display.update()
await asyncio.sleep(0)
async def main(typeOfAlgo, first_run, is_cleared=False): #grid screen
global priority_queue, queue, heap, stack, path, is_starting_set, is_target_set, start_cell, target_cell, algorithm_to_run, grid_cleared
algorithm_to_run = typeOfAlgo
print(algorithm_to_run)
if first_run or is_cleared:
is_starting_set = False
is_target_set = False
running = True
begin_search = False
searching = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEMOTION: #allows user to draw out the walls.
x, y = pygame.mouse.get_pos()
i = x // BOX_WIDTH
j = y // BOX_HEIGHT
if event.buttons[2] and not GRID[i][j].isStart and not GRID[i][j].isTarget:
wall_cell = GRID[i][j]
wall_cell.isWall = True
elif event.type == pygame.MOUSEBUTTONDOWN: #allows the user to choose the starting position.
x, y = pygame.mouse.get_pos()
i = x // BOX_WIDTH
j = y // BOX_HEIGHT
if event.button == 1:
if not is_starting_set:
start_cell = GRID[i][j]
start_cell.isStart = True
start_cell.isWall = False
is_starting_set = True
elif not is_target_set and is_starting_set and GRID[i][j] != start_cell:
target_cell = GRID[i][j]
target_cell.isTarget = True
target_cell.isWall = False
is_target_set = True
grid_cleared = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_c: #clear the current state of the grid
GRID.clear()
initialize_grid(ROWS, COLUMNS)
is_starting_set = False
is_target_set = False
begin_search = False
searching = True
grid_cleared = True
path.clear()
priority_queue = PriorityQueue()
queue.clear()
stack.clear()
if event.key == pygame.K_ESCAPE:
#still preserve the starting and target positions and the walls
for i in range(ROWS):
for j in range(COLUMNS):
cell = GRID[i][j]
if cell.isVisited:
cell.isVisited = False
if cell.isQueued:
cell.isQueued = False
if cell.prior is not None:
cell.prior = None
if cell.distance != float("inf"):
cell.distance = float("inf")
path.clear()
priority_queue = PriorityQueue()
queue.clear()
stack.clear()
is_starting_set = True
is_target_set = True
await algorithm_menu_screen(False, grid_cleared)
if event.key == pygame.K_RETURN and is_starting_set and is_target_set: #to ensure algorithm will run with a start and end
begin_search = True
if begin_search:
if algorithm_to_run == "Dijkstra":
print("Running Dijkstra")
if priority_queue.empty() and searching:
priority_queue.put((0, start_cell))
start_cell.distance = 0
start_cell.isQueued = True
if not priority_queue.empty() and searching:
# Step 2: Process nodes in the priority queue
current_distance, current_box = priority_queue.get()
if not current_box.isVisited: # Skip if already visited
current_box.isVisited = True # Mark as visited
if current_box.isTarget:
searching = False
while current_box.prior is not None:
path.append(current_box.prior)
current_box = current_box.prior
for neighbor, edge_weight in current_box.neighbors:
if not neighbor.isVisited and not neighbor.isWall:
tentative_distance = current_distance + edge_weight
if tentative_distance < neighbor.distance:
neighbor.distance = tentative_distance
neighbor.prior = current_box
priority_queue.put((tentative_distance, neighbor))
neighbor.isQueued = True # Mark as queued
elif algorithm_to_run == "A-star":
print("Running A-star")
if priority_queue.empty() and searching:
priority_queue.put((0, start_cell))
start_cell.distance = 0
start_cell.isQueued = True
if not priority_queue.empty() and searching:
current_distance, current_box = priority_queue.get()
if not current_box.isVisited:
current_box.isVisited = True
if current_box.isTarget:
searching = False
while current_box.prior is not None:
path.append(current_box.prior)
current_box = current_box.prior
for neighbor, edge_weight in current_box.neighbors:
if not neighbor.isVisited and not neighbor.isWall:
tentative_distance = current_distance + edge_weight + heuristic(neighbor, target_cell)
if tentative_distance < neighbor.distance:
neighbor.distance = tentative_distance
neighbor.prior = current_box
priority_queue.put((tentative_distance, neighbor))
neighbor.isQueued = True
elif algorithm_to_run == "BFS":
print("Running BFS")
if not queue and searching:
queue.append(start_cell)
start_cell.isQueued = True
if queue and searching:
current_box = queue.pop(0)
current_box.isVisited = True
if current_box.isTarget:
searching = False
while current_box.prior != start_cell:
path.append(current_box.prior)
current_box = current_box.prior
else:
for neighbor, _ in current_box.neighbors:
if not neighbor.isQueued and not neighbor.isWall:
neighbor.isQueued = True
neighbor.prior = current_box
queue.append(neighbor)
elif algorithm_to_run == "DFS":
if not stack and searching:
stack.append(start_cell)
start_cell.isQueued = True
if stack and searching:
current_box = stack.pop()
if not current_box.isVisited:
current_box.isVisited = True
if current_box.isTarget:
searching = False
while current_box.prior != start_cell:
path.append(current_box.prior)
current_box = current_box.prior
else:
for neighbor, _ in current_box.neighbors:
if not neighbor.isVisited and not neighbor.isWall:
neighbor.isQueued = True
neighbor.prior = current_box
stack.append(neighbor)
screen.fill((0, 0, 0))
for i in range(ROWS):
for j in range(COLUMNS):
cell = GRID[i][j]
cell.draw_box(screen, (50, 50, 50))
if cell.isQueued:
cell.draw_box(screen, "yellow")
if cell.isVisited:
cell.draw_box(screen, "green")
if cell in path:
cell.draw_box(screen, "cyan")
if cell.isWall:
cell.draw_box(screen, "black")
if cell.isTarget:
cell.draw_box(screen, "red")
if cell.isStart:
cell.draw_box(screen, "blue")
pygame.display.flip()
await asyncio.sleep(0)
initialize_grid(ROWS, COLUMNS)
asyncio.run(algorithm_menu_screen())