Use Dijkstra algorithm to describe monster paths

This commit is contained in:
Yohann D'ANELLO
2020-11-11 15:25:50 +01:00
parent 2f3a03dbf7
commit d08ff7061f
2 changed files with 34 additions and 13 deletions

View File

@ -1,4 +1,5 @@
from random import randint
from typing import Dict, Tuple
from ..interfaces import FightingEntity
@ -14,6 +15,7 @@ class Player(FightingEntity):
level: int = 1
current_xp: int = 0
max_xp: int = 10
paths: Dict[Tuple[int, int], Tuple[int, int]]
def move(self, y: int, x: int) -> None:
"""
@ -22,6 +24,7 @@ class Player(FightingEntity):
super().move(y, x)
self.map.currenty = y
self.map.currentx = x
self.recalculate_paths()
def level_up(self) -> None:
"""
@ -61,3 +64,26 @@ class Player(FightingEntity):
self.add_xp(randint(3, 7))
return True
return super().check_move(y, x, move_if_possible)
def recalculate_paths(self) -> None:
"""
Use Dijkstra algorithm to calculate best paths
for monsters to go to the player.
"""
queue = [(self.y, self.x)]
visited = []
predecessors = {}
while queue:
y, x = queue.pop(0)
visited.append((y, x))
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 \
not 0 <= new_x < self.map.width or \
not self.map.tiles[y][x].can_walk() or \
(new_y, new_x) in visited or \
(new_y, new_x) in queue:
continue
predecessors[(new_y, new_x)] = (y, x)
queue.append((new_y, new_x))
self.paths = predecessors