Files
2026-08-16 19:10:31 +02:00

162 lines
5.5 KiB
Python

from __future__ import annotations
from collections.abc import Collection
from heapq import heappush, heappop
from itertools import count
from engine.map_gen import GameMap, Point
def _manhattan(a: Point, b: Point) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def blocked_positions(game_map: GameMap) -> set[Point]:
return {
entity.position
for entity in game_map.entities
if entity.blocks_movement
}
def _neighbors(point: Point) -> tuple[Point, Point, Point, Point]:
x, y = point
return (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)
def _reconstruct(came_from: dict[Point, Point], goal: Point) -> list[Point]:
path = [goal]
while path[-1] in came_from:
path.append(came_from[path[-1]])
path.reverse()
return path
def astar_path(
game_map: GameMap,
start: Point,
goal: Point,
occupied: Collection[Point] | None = None,
) -> list[Point]:
"""A* path from start to goal, 4-directional, Manhattan heuristic.
Obstacles are walls and occupied tiles, so movers never stack. The start
tile is exempt from occupancy (the mover already stands there). Callers
chasing the player should pass enemy positions only, letting the player's
tile stay a valid goal.
Returns the full path [start, ..., goal]; [] when no path exists or an
endpoint is not a floor tile. Never raises on any game state.
"""
if not game_map.is_walkable(*start) or not game_map.is_walkable(*goal):
return []
if start == goal:
return [start]
blockers = blocked_positions(game_map) if occupied is None else set(occupied)
if goal in blockers:
return []
tie = count()
start_h = _manhattan(start, goal)
frontier: list[tuple[int, int, int, Point]] = [(start_h, start_h, next(tie), start)]
came_from: dict[Point, Point] = {}
best_g: dict[Point, int] = {start: 0}
visited: set[Point] = set()
while frontier:
_, _, _, current = heappop(frontier)
if current in visited:
continue
visited.add(current)
if current == goal:
return _reconstruct(came_from, current)
g_next = best_g[current] + 1
for neighbor in _neighbors(current):
if neighbor in visited or neighbor in blockers:
continue
if not game_map.is_walkable(*neighbor):
continue
if g_next < best_g.get(neighbor, g_next + 1):
best_g[neighbor] = g_next
came_from[neighbor] = current
h = _manhattan(neighbor, goal)
heappush(frontier, (g_next + h, h, next(tie), neighbor))
return []
if __name__ == "__main__":
# Run from the repo root: python -m engine.pathfinding
import random
from array import array
from data.constants import TILE_FLOOR, TILE_WALL
from entities.entity import Entity
from engine.map_gen import generate_map
rng = random.Random(7)
for floor in range(5):
game_map = generate_map(floor, seed=floor)
occupied = blocked_positions(game_map)
walkable = [
(x, y)
for y, row in enumerate(game_map.tiles)
for x, tile in enumerate(row)
if tile == TILE_FLOOR and (x, y) not in occupied
]
assert astar_path(game_map, walkable[0], walkable[0], occupied=set()) == [walkable[0]]
for _ in range(20):
a, b = rng.sample(walkable, 2)
# walls-only: mobs may legitimately seal a chokepoint, so the
# any-two-tiles contract holds on the free floor graph
path = astar_path(game_map, a, b, occupied=set())
assert path, f"floor {floor}: no path {a} -> {b}"
assert path[0] == a and path[-1] == b
assert len(set(path)) == len(path)
assert all(
abs(p[0] - q[0]) + abs(p[1] - q[1]) == 1
for p, q in zip(path, path[1:])
), "path must be 4-directionally contiguous"
assert all(game_map.is_walkable(*p) for p in path)
wall = next(
(x, y)
for y, row in enumerate(game_map.tiles)
for x, tile in enumerate(row)
if tile == TILE_WALL
)
assert astar_path(game_map, walkable[0], wall) == []
assert astar_path(game_map, wall, walkable[0]) == []
def manual_map(floors: list[Point]) -> GameMap:
tiles = [array("b", [TILE_WALL] * 5) for _ in range(5)]
for x, y in floors:
tiles[y][x] = TILE_FLOOR
return GameMap(
width=5,
height=5,
tiles=tiles,
rooms=[],
junctions=[],
corridors=[],
explored=[array("b", [0] * 5) for _ in range(5)],
visible=[array("b", [0] * 5) for _ in range(5)],
entities=[],
stairs_down=None,
floor_index=0,
spawn=floors[0],
)
split = manual_map([(1, 1), (3, 3)])
assert astar_path(split, (1, 1), (3, 3)) == [], "walled-off goal must yield no path"
corridor = manual_map([(1, 1), (2, 1), (3, 1)])
straight = astar_path(corridor, (1, 1), (3, 1))
assert straight == [(1, 1), (2, 1), (3, 1)], "Manhattan-optimal length expected"
assert astar_path(corridor, (1, 1), (3, 1), occupied={(2, 1)}) == []
corridor.entities.append(Entity(x=2, y=1, name="Goblin"))
assert astar_path(corridor, (1, 1), (3, 1)) == [], "entity on map must block"
assert astar_path(corridor, (2, 1), (3, 1)) == [(2, 1), (3, 1)], "start is exempt"
print("pathfinding self-check: PASS")