-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.py
More file actions
132 lines (104 loc) · 4.07 KB
/
Copy pathprogram.py
File metadata and controls
132 lines (104 loc) · 4.07 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
import pygame
import math
import sys
from algorithm import Algorithm
from grid import Grid
WIDTH = 650
WINDOW = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("Pathfinder")
class Program:
def __init__(self) -> None:
pygame.init()
self.algo = Algorithm()
self.grids = Grid()
self.driver(WINDOW, WIDTH)
def get_clicked_pos(self, pos, rows, width):
gap = width // rows
y, x = pos
row = y // gap
col = x // gap
return row, col
def driver(self, win, width):
ROWS = 50
grid = self.grids.make_grid(ROWS, width)
start = None
end = None
started = False
run = True
while run:
self.grids.draw(win, grid, ROWS, width)
for events in pygame.event.get():
if events.type == pygame.QUIT:
run = False
if started:
continue
if pygame.mouse.get_pressed()[0]: # Left Btn
pos = pygame.mouse.get_pos()
row, col = self.get_clicked_pos(pos, ROWS, width)
spot = grid[row][col]
if not start and spot != end:
start = spot
start.make_start()
elif not end and spot != start:
end = spot
end.make_end()
elif spot != start and spot != end:
spot.make_barrier()
elif pygame.mouse.get_pressed()[2]: # Right btn
pos = pygame.mouse.get_pos()
row, col = self.get_clicked_pos(pos, ROWS, width)
spot = grid[row][col]
spot.reset()
if spot == start:
start = None
elif spot == end:
end = None
if events.type == pygame.KEYDOWN:
if events.key == pygame.K_SPACE and not started:
for row in grid:
for spot in row:
spot.update_neighbor(grid)
self.algo.a_star_algorithm(
lambda: self.grids.draw(win, grid, ROWS, width),
grid,
start,
end,
)
if events.key == pygame.K_b and not started:
for row in grid:
for spot in row:
spot.update_neighbor(grid)
self.algo.bfs_algorithm(
lambda: self.grids.draw(win, grid, ROWS, width),
grid,
start,
end,
)
if events.key == pygame.K_p and not started:
for row in grid:
for spot in row:
spot.update_neighbor(grid)
self.algo.prim_algorithm(
lambda: self.grids.draw(win, grid, ROWS, width),
grid,
start,
end,
)
if events.key == pygame.K_d and not started:
for row in grid:
for spot in row:
spot.update_neighbor(grid)
self.algo.dijkstra_algorithm(
lambda: self.grids.draw(win, grid, ROWS, width),
grid,
start,
end,
)
if events.key == pygame.K_r:
start = None
end = None
grid = self.grids.make_grid(ROWS, width)
pygame.quit()
sys.exit()
if __name__ == "__main__":
program = Program()