73 lines
2.0 KiB
Python
73 lines
2.0 KiB
Python
from __future__ import annotations
|
|
|
|
import heapq
|
|
from collections.abc import Iterable, Iterator
|
|
|
|
from engine.map_gen import GameMap
|
|
|
|
Position = tuple[int, int]
|
|
|
|
|
|
def manhattan_distance(start: Position, goal: Position) -> int:
|
|
return abs(start[0] - goal[0]) + abs(start[1] - goal[1])
|
|
|
|
|
|
def _neighbors(position: Position) -> Iterator[Position]:
|
|
x, y = position
|
|
yield x, y - 1
|
|
yield x - 1, y
|
|
yield x + 1, y
|
|
yield x, y + 1
|
|
|
|
|
|
def _reconstruct_path(
|
|
came_from: dict[Position, Position], start: Position, goal: Position
|
|
) -> list[Position]:
|
|
path: list[Position] = []
|
|
current = goal
|
|
while current != start:
|
|
path.append(current)
|
|
current = came_from[current]
|
|
path.reverse()
|
|
return path
|
|
|
|
|
|
def find_path(
|
|
game_map: GameMap,
|
|
start: Position,
|
|
goal: Position,
|
|
occupied: Iterable[Position] = (),
|
|
) -> list[Position]:
|
|
"""Return cardinal steps after start through goal, or an empty list if unreachable."""
|
|
if start == goal or not game_map.is_floor(*start) or not game_map.is_floor(*goal):
|
|
return []
|
|
|
|
blocked = set(occupied)
|
|
blocked.discard(start)
|
|
frontier: list[tuple[int, int, Position]] = [
|
|
(manhattan_distance(start, goal), 0, start)
|
|
]
|
|
came_from: dict[Position, Position] = {}
|
|
costs = {start: 0}
|
|
|
|
while frontier:
|
|
_, cost, current = heapq.heappop(frontier)
|
|
if cost != costs.get(current):
|
|
continue
|
|
if current == goal:
|
|
return _reconstruct_path(came_from, start, goal)
|
|
|
|
for neighbor in _neighbors(current):
|
|
if neighbor in blocked or not game_map.is_floor(*neighbor):
|
|
continue
|
|
new_cost = cost + 1
|
|
known_cost = costs.get(neighbor)
|
|
if known_cost is not None and new_cost >= known_cost:
|
|
continue
|
|
costs[neighbor] = new_cost
|
|
came_from[neighbor] = current
|
|
priority = new_cost + manhattan_distance(neighbor, goal)
|
|
heapq.heappush(frontier, (priority, new_cost, neighbor))
|
|
|
|
return []
|