-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
219 lines (183 loc) · 7.21 KB
/
test.py
File metadata and controls
219 lines (183 loc) · 7.21 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
# Pathfinding - Part 4
# Dijkstra Search
# KidsCanCode 2017
import pygame as pg
from os import path
import heapq
vec = pg.math.Vector2
TILESIZE = 48
GRIDWIDTH = 28
GRIDHEIGHT = 15
WIDTH = TILESIZE * GRIDWIDTH
HEIGHT = TILESIZE * GRIDHEIGHT
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
FOREST = (34, 57, 10)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
DARKGRAY = (40, 40, 40)
MEDGRAY = (75, 75, 75)
LIGHTGRAY = (140, 140, 140)
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()
font_name = pg.font.match_font('hack')
def draw_text(text, size, color, x, y, align="topleft"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect(**{align: (x, y)})
screen.blit(text_surface, text_rect)
class SquareGrid:
def __init__(self, width, height):
self.width = width
self.height = height
self.walls = []
self.connections = [vec(1, 0), vec(-1, 0), vec(0, 1), vec(0, -1)]
# comment/uncomment this for diagonals:
self.connections += [vec(1, 1), vec(-1, 1), vec(1, -1), vec(-1, -1)]
def in_bounds(self, node):
return 0 <= node.x < self.width and 0 <= node.y < self.height
def passable(self, node):
return node not in self.walls
def find_neighbors(self, node):
neighbors = [node + connection for connection in self.connections]
neighbors = filter(self.in_bounds, neighbors)
neighbors = filter(self.passable, neighbors)
return neighbors
def draw(self):
for wall in self.walls:
rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
pg.draw.rect(screen, LIGHTGRAY, rect)
class WeightedGrid(SquareGrid):
def __init__(self, width, height):
super().__init__(width, height)
self.weights = {}
def cost(self, from_node, to_node):
if (vec(to_node) - vec(from_node)).length_squared() == 1:
return self.weights.get(to_node, 0) + 10
else:
return self.weights.get(to_node, 0) + 14
def draw(self):
for wall in self.walls:
rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
pg.draw.rect(screen, LIGHTGRAY, rect)
for tile in self.weights:
x, y = tile
rect = pg.Rect(x * TILESIZE + 3, y * TILESIZE + 3, TILESIZE - 3, TILESIZE - 3)
pg.draw.rect(screen, FOREST, rect)
class PriorityQueue:
def __init__(self):
self.nodes = []
def put(self, node, cost):
heapq.heappush(self.nodes, (cost, node))
def get(self):
return heapq.heappop(self.nodes)[1]
def empty(self):
return len(self.nodes) == 0
def draw_grid():
for x in range(0, WIDTH, TILESIZE):
pg.draw.line(screen, LIGHTGRAY, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, TILESIZE):
pg.draw.line(screen, LIGHTGRAY, (0, y), (WIDTH, y))
def draw_icons():
start_center = (goal.x * TILESIZE + TILESIZE / 2, goal.y * TILESIZE + TILESIZE / 2)
screen.blit(home_img, home_img.get_rect(center=start_center))
goal_center = (start.x * TILESIZE + TILESIZE / 2, start.y * TILESIZE + TILESIZE / 2)
screen.blit(cross_img, cross_img.get_rect(center=goal_center))
def vec2int(v):
return (int(v.x), int(v.y))
def dijkstra_search(graph, start, end):
frontier = PriorityQueue()
frontier.put(vec2int(start), 0)
path = {}
cost = {}
path[vec2int(start)] = None
cost[vec2int(start)] = 0
while not frontier.empty():
current = frontier.get()
if current == end:
break
for next in graph.find_neighbors(vec(current)):
next = vec2int(next)
next_cost = cost[current] + graph.cost(current, next)
if next not in cost or next_cost < cost[next]:
cost[next] = next_cost
priority = next_cost
frontier.put(next, priority)
path[next] = vec(current) - vec(next)
return path
icon_dir = path.join(path.dirname(__file__), '../icons')
home_img = pg.image.load('home.png').convert()
home_img = pg.transform.scale(home_img, (50, 50))
home_img.fill((0, 255, 0, 255), special_flags=pg.BLEND_RGBA_MULT)
cross_img = pg.image.load('cross.png').convert_alpha()
cross_img = pg.transform.scale(cross_img, (50, 50))
cross_img.fill((255, 0, 0, 255), special_flags=pg.BLEND_RGBA_MULT)
arrows = {}
arrow_img = pg.image.load('arrowRight.png').convert_alpha()
arrow_img = pg.transform.scale(arrow_img, (50, 50))
for dir in [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)]:
arrows[dir] = pg.transform.rotate(arrow_img, vec(dir).angle_to(vec(1, 0)))
g = WeightedGrid(GRIDWIDTH, GRIDHEIGHT)
walls = [(10, 7), (11, 7), (12, 7), (13, 7), (14, 7), (15, 7), (16, 7), (7, 7), (6, 7), (5, 7), (5, 5), (5, 6), (1, 6),
(2, 6), (3, 6), (5, 10), (5, 11), (5, 12), (5, 9), (5, 8), (12, 8), (12, 9), (12, 10), (12, 11), (15, 14),
(15, 13), (15, 12), (15, 11), (15, 10), (17, 7), (18, 7), (21, 7), (21, 6), (21, 5), (21, 4), (21, 3), (22, 5),
(23, 5), (24, 5), (25, 5), (18, 10), (20, 10), (19, 10), (21, 10), (22, 10), (23, 10), (14, 4), (14, 5),
(14, 6), (14, 0), (14, 1), (9, 2), (9, 1), (7, 3), (8, 3), (10, 3), (9, 3), (11, 3), (2, 5), (2, 4), (2, 3),
(2, 2), (2, 0), (2, 1), (0, 11), (1, 11), (2, 11), (21, 2), (20, 11), (20, 12), (23, 13), (23, 14), (24, 10),
(25, 10), (6, 12), (7, 12), (10, 12), (11, 12), (12, 12), (5, 3), (6, 3), (5, 4)]
for wall in walls:
g.walls.append(vec(wall))
goal = vec(14, 8)
start = vec(20, 0)
path = dijkstra_search(g, goal, start)
running = True
while running:
clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
if event.key == pg.K_m:
# dump the wall list for saving
print([(int(loc.x), int(loc.y)) for loc in g.walls])
if event.type == pg.MOUSEBUTTONDOWN:
mpos = vec(pg.mouse.get_pos()) // TILESIZE
if event.button == 1:
if mpos in g.walls:
g.walls.remove(mpos)
else:
g.walls.append(mpos)
if event.button == 2:
print(mpos)
start = mpos
if event.button == 3:
goal = mpos
path = dijkstra_search(g, goal, start)
pg.display.set_caption("{:.2f}".format(clock.get_fps()))
screen.fill(DARKGRAY)
# fill explored area
for node in path:
x, y = node
rect = pg.Rect(x * TILESIZE, y * TILESIZE, TILESIZE, TILESIZE)
pg.draw.rect(screen, MEDGRAY, rect)
draw_grid()
g.draw()
# draw path from start to goal
current = start + path[vec2int(start)]
while current != goal:
x = current.x * TILESIZE + TILESIZE / 2
y = current.y * TILESIZE + TILESIZE / 2
img = arrows[vec2int(path[(current.x, current.y)])]
r = img.get_rect(center=(x, y))
screen.blit(img, r)
# find next in path
current = current + path[vec2int(current)]
draw_icons()
pg.display.flip()