340 lines
12 KiB
Python
340 lines
12 KiB
Python
"""Procedural dungeon generation via BSP.
|
|
|
|
Geometry contract honored by every floor:
|
|
* tiles indexed tiles[y][x]; TILE_WALL=0, TILE_FLOOR=1
|
|
* a 1-tile wall border surrounds the map
|
|
* rooms are carved strictly inside disjoint BSP leaves, so no two rooms ever
|
|
overlap (their interiors are disjoint)
|
|
* sibling rooms are joined by L-shaped corridors, so every room center is
|
|
reachable from every other by a floor-only flood fill
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import random
|
|
from dataclasses import dataclass, field
|
|
|
|
from data.constants import (
|
|
LEAF_MIN_H,
|
|
LEAF_MIN_W,
|
|
MAP_H,
|
|
MAP_W,
|
|
ROOM_MAX_H,
|
|
ROOM_MAX_W,
|
|
ROOM_MIN_H,
|
|
ROOM_MIN_W,
|
|
SPAWN_TABLE,
|
|
TILE_FLOOR,
|
|
TILE_WALL,
|
|
)
|
|
from data.enemies import ENEMY_FLOORS
|
|
from data.items import ITEM_BY_FLOOR
|
|
from entities.entity import Rect
|
|
from entities.enemy import make_enemy
|
|
from entities.item import make_item
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class GameMap:
|
|
width: int
|
|
height: int
|
|
tiles: list # list[list[int]], indexed [y][x]
|
|
rooms: list # list[Rect]
|
|
explored: list # list[list[bool]]
|
|
visible: list # list[list[bool]]
|
|
entities: list = field(default_factory=list)
|
|
stairs_down: object = None # tuple[int, int] | None
|
|
floor_index: int = 0
|
|
|
|
|
|
def is_walkable(gm: GameMap, x: int, y: int) -> bool:
|
|
if 0 <= x < gm.width and 0 <= y < gm.height:
|
|
return gm.tiles[y][x] == TILE_FLOOR
|
|
return False
|
|
|
|
|
|
class _Node:
|
|
"""A rectangular BSP region (internal node or leaf)."""
|
|
|
|
__slots__ = ("x", "y", "w", "h", "left", "right", "room")
|
|
|
|
def __init__(self, x: int, y: int, w: int, h: int):
|
|
self.x = x
|
|
self.y = y
|
|
self.w = w
|
|
self.h = h
|
|
self.left: _Node | None = None
|
|
self.right: _Node | None = None
|
|
self.room: Rect | None = None
|
|
|
|
@property
|
|
def is_leaf(self) -> bool:
|
|
return self.left is None and self.right is None
|
|
|
|
@property
|
|
def area(self) -> int:
|
|
return self.w * self.h
|
|
|
|
|
|
def generate_floor(floor_index: int = 0, width: int = MAP_W, height: int = MAP_H,
|
|
seed: int | None = None) -> GameMap:
|
|
rng = random.Random(seed)
|
|
gm = GameMap(
|
|
width=width,
|
|
height=height,
|
|
tiles=[[TILE_WALL] * width for _ in range(height)],
|
|
rooms=[],
|
|
explored=[[False] * width for _ in range(height)],
|
|
visible=[[False] * width for _ in range(height)],
|
|
entities=[],
|
|
stairs_down=None,
|
|
floor_index=floor_index,
|
|
)
|
|
gen = _FloorGenerator(gm, rng)
|
|
if floor_index == 9:
|
|
gen.build_boss_arena()
|
|
else:
|
|
gen.build_bsp()
|
|
gen.place_stairs()
|
|
gen.spawn_entities(floor_index)
|
|
return gm
|
|
|
|
|
|
class _FloorGenerator:
|
|
def __init__(self, gm: GameMap, rng: random.Random):
|
|
self.gm = gm
|
|
self.rng = rng
|
|
|
|
# -- BSP -----------------------------------------------------------------
|
|
def build_bsp(self) -> None:
|
|
# Playable interior leaves a 1-tile wall border intact.
|
|
root = _Node(1, 1, self.gm.width - 2, self.gm.height - 2)
|
|
target = self.rng.randint(5, 8)
|
|
counter = [0]
|
|
self._split(root, depth=0, target=target, counter=counter)
|
|
self._carve_rooms(root)
|
|
self._connect(root)
|
|
|
|
def _splittable(self, node: _Node) -> bool:
|
|
return node.w >= 2 * LEAF_MIN_W or node.h >= 2 * LEAF_MIN_H
|
|
|
|
def _choose_axis(self, node: _Node, depth: int) -> str | None:
|
|
can_v = node.w >= 2 * LEAF_MIN_W
|
|
can_h = node.h >= 2 * LEAF_MIN_H
|
|
if not (can_v or can_h):
|
|
return None
|
|
if can_v and can_h:
|
|
# Bias toward halving the longer dimension; otherwise alternate by depth.
|
|
if node.w > node.h * 1.25:
|
|
return "v"
|
|
if node.h > node.w * 1.25:
|
|
return "h"
|
|
return "v" if depth % 2 == 0 else "h"
|
|
return "v" if can_v else "h"
|
|
|
|
def _split(self, node: _Node, depth: int, target: int, counter: list) -> None:
|
|
if counter[0] >= target:
|
|
return
|
|
if not self._splittable(node):
|
|
return
|
|
axis = self._choose_axis(node, depth)
|
|
if axis is None:
|
|
return
|
|
if axis == "v":
|
|
lo, hi = LEAF_MIN_W, node.w - LEAF_MIN_W
|
|
at = self.rng.randint(lo, hi)
|
|
node.left = _Node(node.x, node.y, at, node.h)
|
|
node.right = _Node(node.x + at, node.y, node.w - at, node.h)
|
|
else:
|
|
lo, hi = LEAF_MIN_H, node.h - LEAF_MIN_H
|
|
at = self.rng.randint(lo, hi)
|
|
node.left = _Node(node.x, node.y, node.w, at)
|
|
node.right = _Node(node.x, node.y + at, node.w, node.h - at)
|
|
counter[0] += 1
|
|
# Depth-first; keep splitting until the budget is spent.
|
|
self._split(node.left, depth + 1, target, counter)
|
|
self._split(node.right, depth + 1, target, counter)
|
|
|
|
def _carve_rooms(self, node: _Node) -> None:
|
|
if node.is_leaf:
|
|
node.room = self._carve_room(node)
|
|
self.gm.rooms.append(node.room)
|
|
return
|
|
if node.left is not None:
|
|
self._carve_rooms(node.left)
|
|
if node.right is not None:
|
|
self._carve_rooms(node.right)
|
|
|
|
def _carve_room(self, node: _Node) -> Rect:
|
|
# Shrink 1-2 tiles in from each leaf edge, clamped so the room still fits.
|
|
margin = self.rng.randint(1, 2)
|
|
max_mw = max(0, (node.w - ROOM_MIN_W) // 2)
|
|
max_mh = max(0, (node.h - ROOM_MIN_H) // 2)
|
|
mw = min(margin, max_mw)
|
|
mh = min(margin, max_mh)
|
|
avail_w = node.w - 2 * mw
|
|
avail_h = node.h - 2 * mh
|
|
rw = min(ROOM_MAX_W, avail_w)
|
|
rh = min(ROOM_MAX_H, avail_h)
|
|
ox = self.rng.randint(0, avail_w - rw)
|
|
oy = self.rng.randint(0, avail_h - rh)
|
|
rx = node.x + mw + ox
|
|
ry = node.y + mh + oy
|
|
room = Rect(rx, ry, rw, rh)
|
|
for yy in range(ry, ry + rh):
|
|
row = self.gm.tiles[yy]
|
|
for xx in range(rx, rx + rw):
|
|
row[xx] = TILE_FLOOR
|
|
return room
|
|
|
|
def _connect(self, node: _Node) -> Rect | None:
|
|
"""Recursively join sibling rooms; returns a representative room."""
|
|
if node.is_leaf:
|
|
return node.room
|
|
left = self._connect(node.left) if node.left is not None else None
|
|
right = self._connect(node.right) if node.right is not None else None
|
|
if left is not None and right is not None:
|
|
self._draw_corridor(left.center, right.center)
|
|
return left or right
|
|
|
|
def _draw_corridor(self, c1: tuple[int, int], c2: tuple[int, int]) -> None:
|
|
x1, y1 = c1
|
|
x2, y2 = c2
|
|
if self.rng.random() < 0.5:
|
|
self._h_line(x1, x2, y1)
|
|
self._v_line(y1, y2, x2)
|
|
else:
|
|
self._v_line(y1, y2, x1)
|
|
self._h_line(x1, x2, y2)
|
|
|
|
def _h_line(self, x1: int, x2: int, y: int) -> None:
|
|
if not (0 <= y < self.gm.height):
|
|
return
|
|
row = self.gm.tiles[y]
|
|
for x in range(min(x1, x2), max(x1, x2) + 1):
|
|
if 0 <= x < self.gm.width:
|
|
row[x] = TILE_FLOOR
|
|
|
|
def _v_line(self, y1: int, y2: int, x: int) -> None:
|
|
if not (0 <= x < self.gm.width):
|
|
return
|
|
for y in range(min(y1, y2), max(y1, y2) + 1):
|
|
if 0 <= y < self.gm.height:
|
|
self.gm.tiles[y][x] = TILE_FLOOR
|
|
|
|
# -- stairs --------------------------------------------------------------
|
|
def place_stairs(self) -> None:
|
|
if len(self.gm.rooms) < 2:
|
|
return
|
|
spawn = self.gm.rooms[0].center
|
|
farthest = max(self.gm.rooms[1:], key=lambda r: _chebyshev(r.center, spawn))
|
|
self.gm.stairs_down = farthest.center
|
|
|
|
# -- floor 9 boss arena --------------------------------------------------
|
|
def build_boss_arena(self) -> None:
|
|
rw, rh = 20, 15
|
|
rx = (self.gm.width - rw) // 2
|
|
ry = (self.gm.height - rh) // 2
|
|
room = Rect(rx, ry, rw, rh)
|
|
self.gm.rooms.append(room)
|
|
for yy in range(ry, ry + rh):
|
|
row = self.gm.tiles[yy]
|
|
for xx in range(rx, rx + rw):
|
|
row[xx] = TILE_FLOOR
|
|
# No stairs in the boss arena (victory is the dragon's death).
|
|
self.gm.stairs_down = None
|
|
|
|
# -- entity spawning -----------------------------------------------------
|
|
def spawn_entities(self, floor_index: int) -> None:
|
|
if not self.gm.rooms:
|
|
return
|
|
if floor_index == 9:
|
|
self._spawn_boss_floor()
|
|
return
|
|
spec = SPAWN_TABLE.get(floor_index, (0, 0, 0, 0))
|
|
e_min, e_max, i_min, i_max = spec
|
|
self._spawn_enemies(e_min, e_max, floor_index)
|
|
self._spawn_items(i_min, i_max, floor_index)
|
|
|
|
def _spawn_boss_floor(self) -> None:
|
|
"""Floor 9: the Ancient Dragon alone, plus two healing potions at the
|
|
entrance. No other enemies and no stairs (cleared in build_boss_arena)."""
|
|
room = self.gm.rooms[0]
|
|
cx, cy = room.center
|
|
corners = [
|
|
(room.x + 1, room.y + 1),
|
|
(room.x + room.w - 2, room.y + 1),
|
|
(room.x + 1, room.y + room.h - 2),
|
|
(room.x + room.w - 2, room.y + room.h - 2),
|
|
]
|
|
dragon_pos = max(corners, key=lambda c: _chebyshev(c, (cx, cy)))
|
|
if is_walkable(self.gm, *dragon_pos):
|
|
self.gm.entities.append(make_enemy("ancient_dragon", *dragon_pos))
|
|
for pos in ((cx + 1, cy), (cx - 1, cy)):
|
|
if is_walkable(self.gm, *pos):
|
|
self.gm.entities.append(make_item("Healing Potion", *pos))
|
|
|
|
def _spawn_enemies(self, e_min: int, e_max: int, floor_index: int) -> None:
|
|
if e_max <= 0:
|
|
return
|
|
n = self.rng.randint(e_min, e_max)
|
|
for _ in range(n):
|
|
kind = self._pick_enemy_kind(floor_index)
|
|
if kind is None:
|
|
break
|
|
pos = self._free_tile(avoid_spawn_room=True)
|
|
if pos is None:
|
|
break
|
|
try:
|
|
self.gm.entities.append(make_enemy(kind, *pos))
|
|
except Exception:
|
|
pass
|
|
|
|
def _spawn_items(self, i_min: int, i_max: int, floor_index: int) -> None:
|
|
if i_max <= 0:
|
|
return
|
|
n = self.rng.randint(i_min, i_max)
|
|
for _ in range(n):
|
|
pos = self._free_tile()
|
|
if pos is None:
|
|
break
|
|
name = ITEM_BY_FLOOR(floor_index, self.rng)
|
|
if not name:
|
|
continue
|
|
try:
|
|
self.gm.entities.append(make_item(name, *pos))
|
|
except Exception:
|
|
pass
|
|
|
|
def _pick_enemy_kind(self, floor_index: int) -> str | None:
|
|
"""Random kind valid on this floor (excludes split-spawned small_slime
|
|
and the floor-9 boss, which are placed explicitly)."""
|
|
pool = [
|
|
kind for kind, (lo, hi) in ENEMY_FLOORS.items()
|
|
if lo <= floor_index <= hi
|
|
and kind not in ("small_slime", "ancient_dragon")
|
|
]
|
|
return self.rng.choice(pool) if pool else None
|
|
|
|
def _free_tile(self, avoid_spawn_room: bool = False) -> tuple[int, int] | None:
|
|
rooms = list(self.gm.rooms)
|
|
if avoid_spawn_room and len(rooms) > 1:
|
|
rooms = rooms[1:]
|
|
occupied = {
|
|
(getattr(e, "x", None), getattr(e, "y", None))
|
|
for e in self.gm.entities
|
|
if getattr(e, "blocks", False) or hasattr(e, "behavior")
|
|
}
|
|
for _ in range(80):
|
|
room = self.rng.choice(rooms)
|
|
x = self.rng.randint(room.x, room.x + room.w - 1)
|
|
y = self.rng.randint(room.y, room.y + room.h - 1)
|
|
if (x, y) in occupied or not is_walkable(self.gm, x, y):
|
|
continue
|
|
return (x, y)
|
|
return None
|
|
|
|
|
|
def _chebyshev(a: tuple[int, int], b: tuple[int, int]) -> int:
|
|
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
|