I'm trying to build a path-finder(specifically using Dijkstra's algorithm) representation. when printing the path result onto the screen, it all happens to fast. so fast in fact, that the path seems to be printed in one shot.
I've tried adding the following line after each print:
milliseconds = 500
pygame.time.delay(milliseconds)
which according to the documentation (https://www.pygame.org/docs/ref/time.html#pygame.time.delay) should simply pause the game:
pygame.time.delay()
pause the program for an amount of time
delay(milliseconds) -> time
but this just makes the Window collapse. is there another way to do this?
p.s. I haven't added the entire code, because it composes of several packages and files, but the algorithm is being called from the main loop (that runs the graphics) if that of any help
edit:
i would like to clarify my question: the main loop calls other methods. one of which generates the minimum path. how can I make sure that printing the path is timed, even when its generated outside the main loop?
i've tried to add a clock, but that still doesn't seem to work. I think it will be best if I provide the main loop and the algorithm as reference:
def __init__(self, ...):
self.fps = FPS
self.clock = pygame.time.Clock()
self.run_button = pygame.Rect(WIDTH - BUTTON_WIDTH, 0, BUTTON_WIDTH,
BUTTON_HEIGHT) # button that runs dijkstra
...
def run_visuals(self):
"""
runs the visuals in a loop
"""
run = True
self.draw_grid()
pygame.draw.rect(self.window, GREY, self.run_button) # run button
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if self.run_button.collidepoint(x, y):
dijkstra(self.graph, self.source_node, self.window, self.dest_node,self.clock)
self.add_bad_nodes_with_mouse()
self.draw_nodes("bad")
pygame.display.update()
def dijkstra(graph, source, window, dest,clock):
source.set_dist_from_source(0)
Q = build_min_heap(graph) # O(V)
while Q: # O(V)
clock.tick(FPS)
u = heapq.heappop(Q) # pops the min val based on dist from source (get value and remove from heap) O(logV)
if u == dest:
break
neighbors_of_u = graph.get_neighbors()[u.name]
for v in neighbors_of_u: # O(E)
# drawing neighbors:
block = get_block_from_node(v)
block.draw_block(window, VISITED_COLOR)
# checking min path:
weight_u_v = graph.get_edge_weight(u.name, v.name)
v_dist = v.dist_from_source
u_dist = u.dist_from_source
if v_dist > u_dist + weight_u_v:
v.set_dist_from_source(u_dist + weight_u_v)
v.set_prev(u)
heapq.heappush(Q, v) # O(logV)
print_path(window, source, dest)