88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
"""Grid A* pathfinding with Manhattan heuristic.
|
|
|
|
Returns shortest 4-connected paths over a game map's walkable tiles.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import heapq
|
|
from typing import Any
|
|
|
|
# 4-connected movement on the tile grid.
|
|
_DIRS: tuple[tuple[int, int], ...] = ((1, 0), (-1, 0), (0, 1), (0, -1))
|
|
|
|
|
|
def find_path(
|
|
game_map: Any,
|
|
start: tuple[int, int],
|
|
goal: tuple[int, int],
|
|
blocked: frozenset[tuple[int, int]] = frozenset(),
|
|
) -> list[tuple[int, int]] | None:
|
|
"""Shortest 4-connected path from ``start`` to ``goal``.
|
|
|
|
The path excludes ``start`` and includes ``goal``. Returns ``[]`` when
|
|
``start == goal`` and ``None`` when no route exists. Walls and every tile
|
|
in ``blocked`` are impassable.
|
|
"""
|
|
if start == goal:
|
|
return []
|
|
if not game_map.walkable(*start) or not game_map.walkable(*goal) or goal in blocked:
|
|
return None
|
|
|
|
gx, gy = goal
|
|
|
|
def h(x: int, y: int) -> int:
|
|
return abs(x - gx) + abs(y - gy)
|
|
|
|
g_score: dict[tuple[int, int], int] = {start: 0}
|
|
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
|
counter = 0
|
|
open_heap: list[tuple[int, int, tuple[int, int]]] = [(h(*start), counter, start)]
|
|
closed: set[tuple[int, int]] = set()
|
|
|
|
while open_heap:
|
|
_, _, current = heapq.heappop(open_heap)
|
|
if current in closed:
|
|
continue
|
|
if current == goal:
|
|
path: list[tuple[int, int]] = []
|
|
node = goal
|
|
while node != start:
|
|
path.append(node)
|
|
node = came_from[node]
|
|
path.reverse()
|
|
return path
|
|
closed.add(current)
|
|
cx, cy = current
|
|
base = g_score[current]
|
|
for dx, dy in _DIRS:
|
|
nxt = (cx + dx, cy + dy)
|
|
if nxt in closed or nxt in blocked or not game_map.walkable(*nxt):
|
|
continue
|
|
tentative = base + 1
|
|
if tentative < g_score.get(nxt, float("inf")):
|
|
g_score[nxt] = tentative
|
|
came_from[nxt] = current
|
|
counter += 1
|
|
heapq.heappush(open_heap, (tentative + h(*nxt), counter, nxt))
|
|
return None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from engine.map_gen import generate_dungeon
|
|
|
|
gm = generate_dungeon(seed=1)[0]
|
|
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
|
|
# identity
|
|
assert find_path(gm, (sx, sy), (sx, sy)) == []
|
|
# reach stairs
|
|
if gm.stairs_down is not None:
|
|
p = find_path(gm, (sx, sy), gm.stairs_down)
|
|
assert p is not None and p[-1] == gm.stairs_down, (sx, sy, gm.stairs_down, p)
|
|
assert (sx, sy) not in p
|
|
assert all(gm.walkable(*t) for t in p)
|
|
print(f"path spawn->stairs: {len(p)} steps, first {p[:3]}")
|
|
# no path to a wall
|
|
wx = next(x for x in range(gm.width) if not gm.walkable(x, 0))
|
|
assert find_path(gm, (sx, sy), (wx, 0)) is None
|
|
print("pathfinding self-check: OK")
|