-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathfinder.py
236 lines (195 loc) · 7.41 KB
/
pathfinder.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
import pygame
import heapq
import math
from collections import deque
# Constants
WIDTH = 800
HEIGHT = 600
GRID_SIZE = 20
BACKGROUND_COLOR = (0, 0, 0)
WALL_COLOR = (50, 50, 50)
PATH_COLOR = (255, 0, 0)
START_COLOR = (0, 255, 0)
END_COLOR = (0, 0, 255)
OPEN_COLOR = (255, 255, 255)
CLOSED_COLOR = (128, 128, 128)
TEXT_COLOR = (255, 255, 255)
class Node:
def __init__(self, row, col, width):
self.row = row
self.col = col
self.x = col * width
self.y = row * width
self.width = width
self.color = BACKGROUND_COLOR
self.neighbors = []
self.g_score = float('inf') # To keep track of g_score in A*
self.f_score = float('inf') # To keep track of f_score in A*
def get_pos(self):
return self.row, self.col
def is_closed(self):
return self.color == CLOSED_COLOR
def is_open(self):
return self.color == OPEN_COLOR
def is_wall(self):
return self.color == WALL_COLOR
def is_start(self):
return self.color == START_COLOR
def is_end(self):
return self.color == END_COLOR
def reset(self):
self.color = BACKGROUND_COLOR
def make_start(self):
self.color = START_COLOR
def make_end(self):
self.color = END_COLOR
def make_wall(self):
self.color = WALL_COLOR
def make_open(self):
self.color = OPEN_COLOR
def make_closed(self):
self.color = CLOSED_COLOR
def make_path(self):
self.color = PATH_COLOR
def draw(self, win):
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))
def update_neighbors(self, grid):
self.neighbors = []
if self.row < len(grid) - 1 and not grid[self.row + 1][self.col].is_wall(): # Down
self.neighbors.append(grid[self.row + 1][self.col])
if self.row > 0 and not grid[self.row - 1][self.col].is_wall(): # Up
self.neighbors.append(grid[self.row - 1][self.col])
if self.col < len(grid[0]) - 1 and not grid[self.row][self.col + 1].is_wall(): # Right
self.neighbors.append(grid[self.row][self.col + 1])
if self.col > 0 and not grid[self.row][self.col - 1].is_wall(): # Left
self.neighbors.append(grid[self.row][self.col - 1])
def __lt__(self, other):
return self.f_score < other.f_score
# A* algorithm
def astar_algorithm(draw, grid, start, end):
open_set = []
heapq.heappush(open_set, (0, start))
came_from = {}
g_score = {node: float("inf") for row in grid for node in row}
g_score[start] = 0
f_score = {node: float("inf") for row in grid for node in row}
f_score[start] = heuristic(start.get_pos(), end.get_pos())
while open_set:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
current = heapq.heappop(open_set)[1]
if current == end:
reconstruct_path(came_from, end, draw)
end.make_end()
start.make_start()
return True
for neighbor in current.neighbors:
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor.get_pos(), end.get_pos())
neighbor.g_score = g_score[neighbor]
neighbor.f_score = f_score[neighbor]
if neighbor not in [i[1] for i in open_set]:
heapq.heappush(open_set, (f_score[neighbor], neighbor))
neighbor.make_open()
draw()
if current != start:
current.make_closed()
return False
# BFS algorithm
def bfs_algorithm(draw, grid, start, end):
queue = deque([start])
came_from = {}
g_score = {node: float("inf") for row in grid for node in row}
g_score[start] = 0
while queue:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
current = queue.popleft()
if current == end:
reconstruct_path(came_from, end, draw)
end.make_end()
start.make_start()
return True
for neighbor in current.neighbors:
if g_score[neighbor] == float("inf"):
came_from[neighbor] = current
g_score[neighbor] = g_score[current] + 1
queue.append(neighbor)
neighbor.make_open()
draw()
if current != start:
current.make_closed()
return False
# Heuristic function for A* algorithm
def heuristic(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
return abs(x1 - x2) + abs(y1 - y2)
# Reconstruct path from end node to start node
def reconstruct_path(came_from, current, draw):
while current in came_from:
current = came_from[current]
current.make_path()
draw()
# Draw grid and nodes
def draw_grid(win, grid):
for row in grid:
for node in row:
node.draw(win)
def draw(win, grid, algorithm):
win.fill(BACKGROUND_COLOR)
draw_grid(win, grid)
pygame.display.update()
def main():
pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pathfinding Visualization")
grid = [[Node(row, col, GRID_SIZE) for col in range(WIDTH // GRID_SIZE)] for row in range(HEIGHT // GRID_SIZE)]
start = None
end = None
run = True
while run:
draw(win, grid, None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if pygame.mouse.get_pressed()[0]: # Left mouse button
pos = pygame.mouse.get_pos()
row, col = pos[1] // GRID_SIZE, pos[0] // GRID_SIZE
node = grid[row][col]
if not start and node != end:
start = node
start.make_start()
elif not end and node != start:
end = node
end.make_end()
elif node != end and node != start:
node.make_wall()
elif pygame.mouse.get_pressed()[2]: # Right mouse button
pos = pygame.mouse.get_pos()
row, col = pos[1] // GRID_SIZE, pos[0] // GRID_SIZE
node = grid[row][col]
node.reset()
if node == start:
start = None
elif node == end:
end = None
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and start and end:
for row in grid:
for node in row:
node.update_neighbors(grid)
astar_algorithm(lambda: draw(win, grid, "A*"), grid, start, end)
if event.key == pygame.K_b and start and end:
for row in grid:
for node in row:
node.update_neighbors(grid)
bfs_algorithm(lambda: draw(win, grid, "BFS"), grid, start, end)
pygame.quit()
if __name__ == "__main__":
main()