Limit the complexity of the dijkstra to eight

This commit is contained in:
Yohann D'ANELLO 2020-11-11 16:02:32 +01:00
parent 0f53407b3d
commit 279ef2439d
1 changed files with 5 additions and 1 deletions

View File

@ -65,17 +65,20 @@ class Player(FightingEntity):
return True
return super().check_move(y, x, move_if_possible)
def recalculate_paths(self) -> None:
def recalculate_paths(self, max_distance: int = 8) -> None:
"""
Use Dijkstra algorithm to calculate best paths
for monsters to go to the player.
"""
queue = [(self.y, self.x)]
visited = []
distances = {(self.y, self.x): 0}
predecessors = {}
while queue:
y, x = queue.pop(0)
visited.append((y, x))
if distances[(y, x)] >= max_distance:
continue
for diff_y, diff_x in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
new_y, new_x = y + diff_y, x + diff_x
if not 0 <= new_y < self.map.height or \
@ -85,5 +88,6 @@ class Player(FightingEntity):
(new_y, new_x) in queue:
continue
predecessors[(new_y, new_x)] = (y, x)
distances[(new_y, new_x)] = distances[(y, x)] + 1
queue.append((new_y, new_x))
self.paths = predecessors