70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
"""Grid A* pathfinding with a Manhattan heuristic (plan.md §3)."""
|
|
from __future__ import annotations
|
|
|
|
import heapq
|
|
|
|
|
|
def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] | None:
|
|
"""Shortest floor path from start to goal, or None if unreachable.
|
|
|
|
Walkable tiles are in-bounds floor tiles. `blocked` marks extra impassable
|
|
tiles (other entities) except that the goal is always reachable even if it
|
|
sits in `blocked` (an enemy may path up to its target). Returns the path
|
|
including both endpoints; None if start/goal is a wall or out of bounds.
|
|
"""
|
|
sx, sy = start
|
|
gx, gy = goal
|
|
|
|
if not _is_floor(game_map, sx, sy) or not _is_floor(game_map, gx, gy):
|
|
return None
|
|
if start == goal:
|
|
return [(sx, sy)]
|
|
|
|
blocked_set = set(blocked)
|
|
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
|
g_score: dict[tuple[int, int], int] = {start: 0}
|
|
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
|
counter = 0
|
|
heapq.heappush(open_heap, (_manhattan(start, goal), counter, start))
|
|
closed: set[tuple[int, int]] = set()
|
|
|
|
while open_heap:
|
|
_, _, current = heapq.heappop(open_heap)
|
|
if current in closed:
|
|
continue
|
|
if current == goal:
|
|
return _reconstruct(came_from, current)
|
|
closed.add(current)
|
|
cx, cy = current
|
|
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
|
|
nb = (nx, ny)
|
|
if nb in closed or not _is_floor(game_map, nx, ny):
|
|
continue
|
|
if nb in blocked_set and nb != goal:
|
|
continue
|
|
tentative = g_score[current] + 1
|
|
if tentative < g_score.get(nb, 1_000_000):
|
|
g_score[nb] = tentative
|
|
came_from[nb] = current
|
|
counter += 1
|
|
heapq.heappush(open_heap, (tentative + _manhattan(nb, goal), counter, nb))
|
|
return None
|
|
|
|
|
|
def _is_floor(game_map, x: int, y: int) -> bool:
|
|
return (0 <= x < game_map.width and 0 <= y < game_map.height
|
|
and game_map.tiles[y][x] == 1)
|
|
|
|
|
|
def _manhattan(a: tuple[int, int], b: tuple[int, int]) -> int:
|
|
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
|
|
|
|
|
def _reconstruct(came_from: dict, current: tuple[int, int]) -> list[tuple[int, int]]:
|
|
path = [current]
|
|
while current in came_from:
|
|
current = came_from[current]
|
|
path.append(current)
|
|
path.reverse()
|
|
return path
|