Files
agentic-labs-challenge/underdepths/engine/pathfinding.py
T
2026-08-12 18:44:04 +02:00

215 lines
7.3 KiB
Python

"""Grid-based A* pathfinding with the Manhattan heuristic.
Implemented from scratch (no third-party deps, no pygame). Used by the enemy AI
to chase / flee across the dungeon grid.
Geometry contract (shared with the rest of the engine):
* tiles are indexed ``tiles[y][x]``; ``TILE_WALL=0``, ``TILE_FLOOR=1``.
* a tile is *walkable* iff it is in-bounds, equals ``1`` (floor), and is not a
member of the ``blocked`` set (e.g. tiles occupied by other actors).
* movement is 4-connected (no diagonals); every step costs 1.
The public entry point :func:`astar` is pure: it never mutates ``tiles``,
``blocked``, ``start`` or ``goal`` and performs all of its bookkeeping in local
structures. Tie-breaking is deterministic (a monotonic push counter gives FIFO
ordering among equal-priority frontier nodes), so the same inputs always yield
the same path.
"""
from __future__ import annotations
import heapq
__all__ = ["astar"]
# 4-connected neighbourhood (orthogonal moves only).
_NEIGHBORS = ((1, 0), (-1, 0), (0, 1), (0, -1))
def astar(
width: int,
height: int,
tiles,
start: tuple,
goal: tuple,
blocked: frozenset = frozenset(),
) -> "list[tuple[int, int]] | None":
"""Find a shortest path from ``start`` to ``goal`` on a floor grid.
Parameters
----------
width, height:
Dimensions of ``tiles``.
tiles:
2D sequence indexed ``tiles[y][x]``; ``1`` means floor.
start, goal:
``(x, y)`` integer coordinate pairs. Both endpoints are included in the
returned path.
blocked:
Any iterable of ``(x, y)`` pairs treated as impassable (typically the
tiles currently occupied by other entities). Defaults to an empty
frozenset.
Returns
-------
list[tuple[int, int]] | None
The path from ``start`` to ``goal`` inclusive, as a list of ``(x, y)``
tuples, or ``None`` when no route exists (goal walled off, blocked, or
out of bounds).
"""
sx, sy = start
gx, gy = goal
# Endpoints must live on the map.
if not (0 <= sx < width and 0 <= sy < height):
return None
if not (0 <= gx < width and 0 <= gy < height):
return None
def walkable(x: int, y: int) -> bool:
return (
0 <= x < width
and 0 <= y < height
and tiles[y][x] == 1
and (x, y) not in blocked
)
# Trivial case: already there. Reported even for non-floor tiles so callers
# asking "am I at my destination?" always get a sensible answer.
if start == goal:
return [start]
# An un-walkable endpoint means no legal route can begin / end there.
if not walkable(sx, sy) or not walkable(gx, gy):
return None
# Manhattan distance to the goal — admissible & consistent for 4-connected
# grids with uniform step cost, so the first time we pop the goal we have a
# shortest path.
def h(x: int, y: int) -> int:
return abs(x - gx) + abs(y - gy)
# Priority queue of (f_score, tiebreak_counter, x, y). The monotonic counter
# makes ordering fully deterministic for equal f-scores (FIFO by insertion),
# and guarantees heapq never has to compare the (x, y) tuples directly.
open_heap: list = []
counter = 0
g_score = {start: 0}
came_from: dict = {}
heapq.heappush(open_heap, (h(sx, sy), counter, sx, sy))
counter += 1
closed: set = set()
while open_heap:
f, _, x, y = heapq.heappop(open_heap)
node = (x, y)
# Lazy deletion: a node may have been pushed several times before being
# settled. Skip any we've already expanded via a cheaper route.
if node in closed:
continue
if node == goal:
path = [node]
cur = node
while cur in came_from:
cur = came_from[cur]
path.append(cur)
path.reverse()
return path
closed.add(node)
base_g = g_score[node]
for dx, dy in _NEIGHBORS:
nx, ny = x + dx, y + dy
if not walkable(nx, ny):
continue
nxt = (nx, ny)
if nxt in closed:
continue
tentative_g = base_g + 1
if tentative_g < g_score.get(nxt, float("inf")):
g_score[nxt] = tentative_g
came_from[nxt] = node
heapq.heappush(open_heap, (tentative_g + h(nx, ny), counter, nx, ny))
counter += 1
# Frontier exhausted without reaching the goal: it is unreachable.
return None
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
# Self-check: exercise the interesting cases without relying on the rest of
# the engine. Exits non-zero on the first failure.
FLOOR, WALL = 1, 0
def _grid(w, h, fill=FLOOR):
return [[fill] * w for _ in range(h)]
# 1. Straight-line optimal length on open ground.
g = _grid(10, 10)
p = astar(10, 10, g, (0, 0), (3, 0))
assert p is not None, "open-ground path should exist"
assert p[0] == (0, 0) and p[-1] == (3, 0), "endpoints"
assert len(p) == 4, f"optimal open length is 4, got {len(p)}"
assert len(p) == len(set(p)), "path revisits a tile"
# 2. Contiguity + walkability of every step.
for i, (x, y) in enumerate(p):
assert g[y][x] == FLOOR, f"path crosses wall at {(x, y)}"
if i > 0:
px, py = p[i - 1]
assert max(abs(x - px), abs(y - py)) == 1, f"non-contiguous step at {i}"
# 3. Manhattan-optimality on an L-shaped open route.
p2 = astar(10, 10, g, (0, 0), (4, 5))
assert p2 is not None and len(p2) == 10, f"L-route length, got {p2}"
# 4. start == goal.
assert astar(10, 10, g, (2, 2), (2, 2)) == [(2, 2)], "self path"
# 5. Unreachable -> None (sealed box).
sealed = _grid(7, 7)
for x in range(7):
sealed[3][x] = WALL # full wall row, no gap
assert astar(7, 7, sealed, (1, 1), (5, 5)) is None, "sealed map should be None"
# 6. Path threads a single gap in a wall column.
W = H = 12
t = _grid(W, H)
for y in range(H):
t[y][6] = WALL
t[6][6] = FLOOR # the only gap
pg = astar(W, H, t, (1, 1), (10, 10))
assert pg is not None, "gap path should exist"
assert pg[0] == (1, 1) and pg[-1] == (10, 10)
assert all(t[y][x] == FLOOR for x, y in pg), "gap path crosses a wall"
# Must actually use the gap.
assert (6, 6) in pg, "gap path should pass through the gap"
# 7. `blocked` forces a detour and can close a gap entirely.
t2 = [row[:] for row in t]
none_when_gap_blocked = astar(W, H, t2, (1, 1), (10, 10), blocked={(6, 6)})
assert none_when_gap_blocked is None, "blocking the only gap => None"
# 8. Determinism: repeated calls give identical results.
again = astar(W, H, t, (1, 1), (10, 10))
assert again == pg, "non-deterministic path"
# 9. Out-of-bounds endpoints -> None, no crash.
assert astar(W, H, t, (-1, 1), (10, 10)) is None
assert astar(W, H, t, (1, 1), (W, H)) is None
# 10. No mutation of inputs.
snapshot = [row[:] for row in t]
bl_snapshot = frozenset({(6, 6)})
_ = astar(W, H, t, (1, 1), (10, 10), blocked=bl_snapshot)
assert t == snapshot, "tiles mutated"
assert bl_snapshot == frozenset({(6, 6)}), "blocked mutated"
print("pathfinding self-check OK")