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