Files
agentic-labs-challenge/underdepths/engine/map_gen.py
T
2026-08-13 15:23:35 +02:00

310 lines
11 KiB
Python

"""BSP dungeon generation, the GameMap/Rect model, and per-floor population."""
from __future__ import annotations
import random
from dataclasses import dataclass
from data import constants as C
from entities.enemy import make_enemy, kinds_for_floor
from entities.item import make_item, item_pool_for_floor
# BSP / room sizing. Rooms are 4x4..10x8 (plan.md §1); leaves must hold one.
MIN_LEAF: int = 8
MIN_ROOM_W: int = 4
MIN_ROOM_H: int = 4
MAX_ROOM_W: int = 10
MAX_ROOM_H: int = 8
BOSS_ROOM_W: int = 20
BOSS_ROOM_H: int = 15
@dataclass(slots=True)
class Rect:
x: int
y: int
w: int
h: int
@property
def center(self) -> tuple[int, int]:
return (self.x + self.w // 2, self.y + self.h // 2)
@dataclass(slots=True)
class GameMap:
width: int
height: int
tiles: list[list[int]] # 0 = wall, 1 = floor
rooms: list[Rect]
explored: list[list[bool]]
visible: list[list[bool]]
entities: list # enemies + items present on this floor
stairs_down: tuple[int, int]
floor_index: int
def is_walkable(game_map: GameMap, x: int, y: int) -> bool:
"""True if (x, y) is in bounds and a floor tile."""
if not (0 <= x < game_map.width and 0 <= y < game_map.height):
return False
return game_map.tiles[y][x] == 1
# --------------------------------------------------------------------------- #
# Generation
# --------------------------------------------------------------------------- #
def generate_dungeon(floor_index: int, width: int = C.MAP_WIDTH,
height: int = C.MAP_HEIGHT) -> GameMap:
"""Generate one floor via BSP (floors 0-8) or a boss arena (floor 9).
Uses the global `random` state so new_game(seed) can seed the whole dive.
"""
tiles: list[list[int]] = [[0] * width for _ in range(height)]
if floor_index == C.FLOORS - 1:
return _boss_arena(floor_index, width, height, tiles)
# Working area sits inside the 1-tile wall border.
root = {"x": 1, "y": 1, "w": width - 2, "h": height - 2}
_build_bsp(root, random.randint(5, 8))
leaves: list[dict] = []
_collect_leaves(root, leaves)
rooms: list[Rect] = []
for leaf in leaves:
leaf["room"] = _carve_room(leaf, tiles, width, height)
rooms.append(leaf["room"])
_connect(root, tiles, width, height)
# Stairs go in the room farthest from the spawn room.
spawn = rooms[0].center
stairs_room = max(rooms, key=lambda r: _dist2(r.center, spawn))
explored = [[False] * width for _ in range(height)]
visible = [[False] * width for _ in range(height)]
return GameMap(width, height, tiles, rooms, explored, visible, [],
stairs_room.center, floor_index)
def _build_bsp(root: dict, target_splits: int) -> None:
"""Split the largest splittable leaf until target_splits splits are done."""
splittable = [root]
done = 0
prefer_horiz = True
while done < target_splits and splittable:
splittable.sort(key=lambda n: n["w"] * n["h"], reverse=True)
node = splittable.pop(0)
halves = _split_node(node, prefer_horiz)
prefer_horiz = not prefer_horiz
if halves is None:
continue # this leaf can't be split; it stays a leaf
left, right = halves
node["left"] = left
node["right"] = right
splittable.append(left)
splittable.append(right)
done += 1
def _split_node(node: dict, prefer_horiz: bool) -> tuple[dict, dict] | None:
"""Split a region on the preferred axis, falling back to the other.
Returns the two child regions, or None if neither axis can be split.
"""
use_horiz = prefer_horiz
if use_horiz and node["w"] < 2 * MIN_LEAF:
use_horiz = False
if not use_horiz and node["h"] < 2 * MIN_LEAF:
use_horiz = True
length = node["w"] if use_horiz else node["h"]
if length < 2 * MIN_LEAF:
return None
p = random.randint(MIN_LEAF, length - MIN_LEAF)
if use_horiz:
left = {"x": node["x"], "y": node["y"], "w": p, "h": node["h"]}
right = {"x": node["x"] + p, "y": node["y"], "w": node["w"] - p, "h": node["h"]}
else:
left = {"x": node["x"], "y": node["y"], "w": node["w"], "h": p}
right = {"x": node["x"], "y": node["y"] + p, "w": node["w"], "h": node["h"] - p}
return left, right
def _collect_leaves(node: dict, out: list[dict]) -> None:
if "left" in node:
_collect_leaves(node["left"], out)
_collect_leaves(node["right"], out)
else:
out.append(node)
def _carve_room(leaf: dict, tiles: list[list[int]], width: int, height: int) -> Rect:
"""Carve a room (4x4..10x8) inside the leaf, shrunk from its edges."""
shrink = random.randint(1, 2)
max_w = max(MIN_ROOM_W, leaf["w"] - 2 * shrink)
max_h = max(MIN_ROOM_H, leaf["h"] - 2 * shrink)
rw = random.randint(MIN_ROOM_W, min(MAX_ROOM_W, max_w))
rh = random.randint(MIN_ROOM_H, min(MAX_ROOM_H, max_h))
ox = random.randint(shrink, max(shrink, leaf["w"] - rw - shrink))
oy = random.randint(shrink, max(shrink, leaf["h"] - rh - shrink))
rx = leaf["x"] + ox
ry = leaf["y"] + oy
for y in range(ry, ry + rh):
for x in range(rx, rx + rw):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
return Rect(rx, ry, rw, rh)
def _connect(node: dict, tiles: list[list[int]], width: int, height: int) -> Rect | None:
"""Carve L-corridors between sibling subtree rooms so all rooms connect."""
if "left" not in node:
return node.get("room")
lr = _connect(node["left"], tiles, width, height)
rr = _connect(node["right"], tiles, width, height)
if lr is not None and rr is not None:
_carve_corridor(lr.center, rr.center, tiles, width, height)
return lr if lr is not None else rr
def _carve_corridor(a: tuple[int, int], b: tuple[int, int],
tiles: list[list[int]], width: int, height: int) -> None:
x1, y1 = a
x2, y2 = b
if random.random() < 0.5:
_h_tunnel(x1, x2, y1, tiles, width, height)
_v_tunnel(y1, y2, x2, tiles, width, height)
else:
_v_tunnel(y1, y2, x1, tiles, width, height)
_h_tunnel(x1, x2, y2, tiles, width, height)
def _h_tunnel(x1: int, x2: int, y: int, tiles: list[list[int]],
width: int, height: int) -> None:
for x in range(min(x1, x2), max(x1, x2) + 1):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
def _v_tunnel(y1: int, y2: int, x: int, tiles: list[list[int]],
width: int, height: int) -> None:
for y in range(min(y1, y2), max(y1, y2) + 1):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
def _boss_arena(floor_index: int, width: int, height: int,
tiles: list[list[int]]) -> GameMap:
"""Floor 9: a single large room; the dragon is placed by populate()."""
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
rx = (width - rw) // 2
ry = (height - rh) // 2
for y in range(ry, ry + rh):
for x in range(rx, rx + rw):
tiles[y][x] = 1
room = Rect(rx, ry, rw, rh)
stairs = (rx + rw // 2, ry + rh - 2) # unused for descent; victory ends the run
explored = [[False] * width for _ in range(height)]
visible = [[False] * width for _ in range(height)]
return GameMap(width, height, tiles, [room], explored, visible, [],
stairs, floor_index)
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
# --------------------------------------------------------------------------- #
# Population
# --------------------------------------------------------------------------- #
def populate(game_map: GameMap, floor_index: int, rng: random.Random | None = None) -> None:
"""Place enemies AND items per the plan's per-floor distribution. Never raises.
Floor 9 (boss) gets the dragon plus exactly two healing potions near the
entrance; every other floor gets enemies and items drawn from the roster /
catalog, depth-gated.
"""
r = rng if rng is not None else random
if floor_index == C.FLOORS - 1:
room = game_map.rooms[0]
dx, dy = room.x + room.w // 2, room.y + 2
if not is_walkable(game_map, dx, dy):
ft = _first_floor_tile(game_map)
if ft is None:
return
dx, dy = ft
game_map.entities.append(make_enemy("ancient_dragon", dx, dy))
_place_boss_potions(game_map, room, r)
return
lo, hi = C.ENEMY_COUNT[floor_index]
n = r.randint(lo, hi)
pool = [
(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
]
if not pool:
return
kinds = kinds_for_floor(floor_index)
if not kinds:
return
r.shuffle(pool)
placed = 0
for tile in pool:
if placed >= n:
break
kind = r.choice(kinds)
game_map.entities.append(make_enemy(kind, tile[0], tile[1]))
placed += 1
_place_items(game_map, floor_index, r)
def _place_items(game_map: GameMap, floor_index: int, r) -> None:
"""Scatter ITEM_COUNT items from the depth-weighted pool across floor tiles."""
lo, hi = C.ITEM_COUNT[floor_index]
n = r.randint(lo, hi)
pool = [
(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
]
if not pool:
return
r.shuffle(pool)
names = item_pool_for_floor(floor_index)
placed = 0
for tile in pool:
if placed >= n:
break
game_map.entities.append(make_item(r.choice(names), tile[0], tile[1]))
placed += 1
def _place_boss_potions(game_map: GameMap, room: Rect, r) -> None:
"""Put two Healing Potions by the boss-room entrance (far side from the dragon)."""
ex, ey = room.center[0], room.y + room.h - 2
placed = 0
for dx in (-1, 0, 1):
if placed >= 2:
break
x, y = ex + dx, ey
if is_walkable(game_map, x, y):
game_map.entities.append(make_item("Healing Potion", x, y))
placed += 1
if placed < 2: # entrance row blocked: fall back to any floor tiles
pool = [(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1]
r.shuffle(pool)
for (x, y) in pool:
if placed >= 2:
break
game_map.entities.append(make_item("Healing Potion", x, y))
placed += 1
def _first_floor_tile(game_map: GameMap) -> tuple[int, int] | None:
for y in range(game_map.height):
for x in range(game_map.width):
if game_map.tiles[y][x] == 1:
return (x, y)
return None