-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.py
More file actions
61 lines (52 loc) · 2.03 KB
/
visualizer.py
File metadata and controls
61 lines (52 loc) · 2.03 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
import pygame
import constants
from node import Node
from grid import make_grid, get_clicked_pos, draw
from a_star_algorithm import a_star_algorithm
pygame.display.set_caption("A* Algorithm Visualizer")
def main(win, rows, width):
grid = make_grid(rows, width)
start = None
end = None
run = True
while run:
draw(win, grid, rows, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Left mouse button
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, rows, width)
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 != start and node != end:
node.make_barrier()
# Right mouse button
elif pygame.mouse.get_pressed()[2]:
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, rows, width)
node = grid[row][col]
node.reset()
if node == start:
start = None
elif node == end:
end = None
# Start when spacebar is pressed
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)
a_star_algorithm(lambda: draw(win, grid, rows, width), grid, start, end)
if event.key == pygame.K_c:
start = None
end = None
grid = make_grid(rows, width)
pygame.quit()
main(constants.WIN, constants.ROWS, constants.WIDTH)