96 lines
3.0 KiB
Python
96 lines
3.0 KiB
Python
"""Grid A* with Manhattan heuristic.
|
|
|
|
4-connected movement (matches the plan's one-tile enemy steps and the
|
|
Manhattan distance heuristic). Returns the full path start..goal inclusive.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import heapq
|
|
from typing import Any
|
|
|
|
from engine.map_gen import GameMap
|
|
|
|
|
|
def _heuristic(a: tuple[int, int], b: tuple[int, int]) -> int:
|
|
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
|
|
|
|
|
def _walkable(gmap: GameMap, x: int, y: int, blocked: set[tuple[int, int]] | None) -> bool:
|
|
if x < 0 or y < 0 or x >= gmap.width or y >= gmap.height:
|
|
return False
|
|
if gmap.tiles[y][x] != 1:
|
|
return False
|
|
if blocked is not None and (x, y) in blocked:
|
|
return False
|
|
return True
|
|
|
|
|
|
def astar(
|
|
gmap: Any,
|
|
start: tuple[int, int],
|
|
goal: tuple[int, int],
|
|
blocked: set[tuple[int, int]] | None = None,
|
|
) -> list[tuple[int, int]] | None:
|
|
if not _walkable(gmap, start[0], start[1], blocked) or not _walkable(gmap, goal[0], goal[1], blocked):
|
|
return None
|
|
|
|
if start == goal:
|
|
return [start]
|
|
|
|
# (f, tie_breaker, node)
|
|
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
|
counter = 0
|
|
heapq.heappush(open_heap, (_heuristic(start, goal), counter, start))
|
|
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
|
g_score: dict[tuple[int, int], int] = {start: 0}
|
|
|
|
neighbors = ((0, -1), (0, 1), (-1, 0), (1, 0))
|
|
|
|
while open_heap:
|
|
_, _, current = heapq.heappop(open_heap)
|
|
if current == goal:
|
|
path = [current]
|
|
while current in came_from:
|
|
current = came_from[current]
|
|
path.append(current)
|
|
path.reverse()
|
|
return path
|
|
|
|
cx, cy = current
|
|
step = g_score[current] + 1
|
|
for dx, dy in neighbors:
|
|
nxt = (cx + dx, cy + dy)
|
|
if nxt in g_score and step >= g_score[nxt]:
|
|
continue
|
|
if not _walkable(gmap, nxt[0], nxt[1], blocked):
|
|
continue
|
|
g_score[nxt] = step
|
|
f = step + _heuristic(nxt, goal)
|
|
counter += 1
|
|
heapq.heappush(open_heap, (f, counter, nxt))
|
|
came_from[nxt] = current
|
|
|
|
return None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from random import Random
|
|
from engine.map_gen import generate_dungeon
|
|
|
|
rng = Random(0)
|
|
failures = 0
|
|
for floor in range(9):
|
|
m = generate_dungeon(floor, rng)
|
|
floors = [(x, y) for y in range(m.height) for x in range(m.width) if m.tiles[y][x] == 1]
|
|
a, b = floors[0], floors[-1]
|
|
p = astar(m, a, b)
|
|
if p is None or p[0] != a or p[-1] != b:
|
|
failures += 1
|
|
print(f"floor {floor}: FAIL a={a} b={b} p={p}")
|
|
# blocked corner case: wall off goal
|
|
flat = GameMap(5, 1, [[1, 1, 0, 1, 1]], [], [], [], [], None, 0)
|
|
assert astar(flat, (0, 0), (4, 0)) is None, "wall should block"
|
|
assert astar(flat, (0, 0), (1, 0)) == [(0, 0), (1, 0)]
|
|
print(f"astar ok ({failures} connectivity failures)")
|