477 lines
14 KiB
Python
477 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
from array import array
|
|
from collections.abc import Callable
|
|
from dataclasses import dataclass
|
|
import random
|
|
|
|
from data.constants import (
|
|
ARENA_DRAGON_OFFSET,
|
|
ARENA_ENTRANCE_OFFSET,
|
|
ARENA_HEIGHT,
|
|
ARENA_WIDTH,
|
|
BSP_MAX_ROOMS,
|
|
BSP_MIN_ROOMS,
|
|
DRAGON_KEY,
|
|
FINAL_FLOOR,
|
|
FINAL_FLOOR_POTIONS,
|
|
JUNCTION_SIZE,
|
|
MAP_BORDER,
|
|
MAP_HEIGHT,
|
|
MAP_WIDTH,
|
|
MAX_CORRIDOR_LENGTH,
|
|
MAX_MAP_ATTEMPTS,
|
|
ROOM_MARGIN,
|
|
ROOM_MAX_HEIGHT,
|
|
ROOM_MAX_WIDTH,
|
|
ROOM_MIN_HEIGHT,
|
|
ROOM_MIN_WIDTH,
|
|
TILE_FLOOR,
|
|
TILE_WALL,
|
|
)
|
|
from data.enemies import roll_floor_enemies, spawn_enemy
|
|
from data.items import roll_floor_items, spawn_item
|
|
from entities.entity import Entity
|
|
|
|
Grid = list[array]
|
|
Point = tuple[int, int]
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Rect:
|
|
x: int
|
|
y: int
|
|
width: int
|
|
height: int
|
|
|
|
@property
|
|
def x2(self) -> int:
|
|
return self.x + self.width
|
|
|
|
@property
|
|
def y2(self) -> int:
|
|
return self.y + self.height
|
|
|
|
@property
|
|
def center(self) -> Point:
|
|
return self.x + self.width // 2, self.y + self.height // 2
|
|
|
|
def contains(self, point: Point) -> bool:
|
|
x, y = point
|
|
return self.x <= x < self.x2 and self.y <= y < self.y2
|
|
|
|
def overlaps(self, other: Rect) -> bool:
|
|
return not (
|
|
self.x2 <= other.x
|
|
or other.x2 <= self.x
|
|
or self.y2 <= other.y
|
|
or other.y2 <= self.y
|
|
)
|
|
|
|
def tiles(self) -> set[Point]:
|
|
return {
|
|
(x, y)
|
|
for y in range(self.y, self.y2)
|
|
for x in range(self.x, self.x2)
|
|
}
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class GameMap:
|
|
width: int
|
|
height: int
|
|
tiles: Grid
|
|
rooms: list[Rect]
|
|
junctions: list[Rect]
|
|
corridors: list[list[Point]]
|
|
explored: Grid
|
|
visible: Grid
|
|
entities: list[Entity]
|
|
stairs_down: Point | None
|
|
floor_index: int
|
|
spawn: Point
|
|
|
|
def in_bounds(self, x: int, y: int) -> bool:
|
|
return 0 <= x < self.width and 0 <= y < self.height
|
|
|
|
def tile_at(self, x: int, y: int) -> int:
|
|
return self.tiles[y][x] if self.in_bounds(x, y) else TILE_WALL
|
|
|
|
def is_walkable(self, x: int, y: int) -> bool:
|
|
return self.tile_at(x, y) == TILE_FLOOR
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class _Node:
|
|
region: Rect
|
|
depth: int = 0
|
|
left: _Node | None = None
|
|
right: _Node | None = None
|
|
room: Rect | None = None
|
|
|
|
@property
|
|
def is_leaf(self) -> bool:
|
|
return self.left is None and self.right is None
|
|
|
|
|
|
class _GenerationError(RuntimeError):
|
|
pass
|
|
|
|
|
|
_MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2
|
|
_MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2
|
|
|
|
|
|
def _new_grid(width: int, height: int, value: int) -> Grid:
|
|
return [array("b", [value]) * width for _ in range(height)]
|
|
|
|
|
|
def _leaves(node: _Node) -> list[_Node]:
|
|
if node.is_leaf:
|
|
return [node]
|
|
result: list[_Node] = []
|
|
if node.left is not None:
|
|
result.extend(_leaves(node.left))
|
|
if node.right is not None:
|
|
result.extend(_leaves(node.right))
|
|
return result
|
|
|
|
|
|
def _can_split(node: _Node) -> bool:
|
|
return (
|
|
node.region.width >= _MIN_REGION_WIDTH * 2
|
|
or node.region.height >= _MIN_REGION_HEIGHT * 2
|
|
)
|
|
|
|
|
|
def _balanced_offset(size: int, minimum: int, rng: random.Random) -> int:
|
|
low = max(minimum, size * 2 // 5)
|
|
high = min(size - minimum, size * 3 // 5)
|
|
if low > high:
|
|
low, high = minimum, size - minimum
|
|
return rng.randint(low, high)
|
|
|
|
|
|
def _split(node: _Node, rng: random.Random) -> bool:
|
|
region = node.region
|
|
can_vertical = region.width >= _MIN_REGION_WIDTH * 2
|
|
can_horizontal = region.height >= _MIN_REGION_HEIGHT * 2
|
|
if not can_vertical and not can_horizontal:
|
|
return False
|
|
|
|
vertical = node.depth % 2 == 0
|
|
if vertical and not can_vertical:
|
|
vertical = False
|
|
elif not vertical and not can_horizontal:
|
|
vertical = True
|
|
|
|
if vertical:
|
|
offset = _balanced_offset(region.width, _MIN_REGION_WIDTH, rng)
|
|
first = Rect(region.x, region.y, offset, region.height)
|
|
second = Rect(region.x + offset, region.y, region.width - offset, region.height)
|
|
else:
|
|
offset = _balanced_offset(region.height, _MIN_REGION_HEIGHT, rng)
|
|
first = Rect(region.x, region.y, region.width, offset)
|
|
second = Rect(region.x, region.y + offset, region.width, region.height - offset)
|
|
|
|
node.left = _Node(first, node.depth + 1)
|
|
node.right = _Node(second, node.depth + 1)
|
|
return True
|
|
|
|
|
|
def _build_tree(rng: random.Random) -> _Node:
|
|
root = _Node(
|
|
Rect(
|
|
MAP_BORDER,
|
|
MAP_BORDER,
|
|
MAP_WIDTH - MAP_BORDER * 2,
|
|
MAP_HEIGHT - MAP_BORDER * 2,
|
|
)
|
|
)
|
|
target = rng.randint(BSP_MIN_ROOMS, BSP_MAX_ROOMS)
|
|
while len(_leaves(root)) < target:
|
|
candidates = [leaf for leaf in _leaves(root) if _can_split(leaf)]
|
|
if not candidates:
|
|
raise _GenerationError("BSP could not reach its room target")
|
|
largest = max(
|
|
candidates,
|
|
key=lambda leaf: leaf.region.width * leaf.region.height,
|
|
)
|
|
if not _split(largest, rng):
|
|
raise _GenerationError("selected BSP leaf could not split")
|
|
return root
|
|
|
|
|
|
def _make_room(region: Rect, rng: random.Random) -> Rect:
|
|
maximum_width = min(ROOM_MAX_WIDTH, region.width - ROOM_MARGIN * 2)
|
|
maximum_height = min(ROOM_MAX_HEIGHT, region.height - ROOM_MARGIN * 2)
|
|
width = rng.randint(ROOM_MIN_WIDTH, maximum_width)
|
|
height = rng.randint(ROOM_MIN_HEIGHT, maximum_height)
|
|
x = rng.randint(region.x + ROOM_MARGIN, region.x2 - width - ROOM_MARGIN)
|
|
y = rng.randint(region.y + ROOM_MARGIN, region.y2 - height - ROOM_MARGIN)
|
|
return Rect(x, y, width, height)
|
|
|
|
|
|
def _carve_rect(tiles: Grid, rect: Rect) -> None:
|
|
for y in range(rect.y, rect.y2):
|
|
for x in range(rect.x, rect.x2):
|
|
tiles[y][x] = TILE_FLOOR
|
|
|
|
|
|
def _carve_path(tiles: Grid, path: list[Point]) -> None:
|
|
for x, y in path:
|
|
tiles[y][x] = TILE_FLOOR
|
|
|
|
|
|
def _clamp(value: int, low: int, high: int) -> int:
|
|
return max(low, min(value, high))
|
|
|
|
|
|
def _closest_endpoints(first: Rect, second: Rect) -> tuple[Point, Point, bool]:
|
|
if first.x2 <= second.x:
|
|
first_y = _clamp(second.center[1], first.y, first.y2 - 1)
|
|
second_y = _clamp(first_y, second.y, second.y2 - 1)
|
|
return (first.x2 - 1, first_y), (second.x, second_y), True
|
|
if second.x2 <= first.x:
|
|
first_y = _clamp(second.center[1], first.y, first.y2 - 1)
|
|
second_y = _clamp(first_y, second.y, second.y2 - 1)
|
|
return (first.x, first_y), (second.x2 - 1, second_y), True
|
|
if first.y2 <= second.y:
|
|
first_x = _clamp(second.center[0], first.x, first.x2 - 1)
|
|
second_x = _clamp(first_x, second.x, second.x2 - 1)
|
|
return (first_x, first.y2 - 1), (second_x, second.y), False
|
|
first_x = _clamp(second.center[0], first.x, first.x2 - 1)
|
|
second_x = _clamp(first_x, second.x, second.x2 - 1)
|
|
return (first_x, first.y), (second_x, second.y2 - 1), False
|
|
|
|
|
|
def _ordered_path(start: Point, end: Point, horizontal_first: bool) -> list[Point]:
|
|
path = [start]
|
|
x, y = start
|
|
end_x, end_y = end
|
|
axes = ("x", "y") if horizontal_first else ("y", "x")
|
|
for axis in axes:
|
|
if axis == "x":
|
|
while x != end_x:
|
|
x += 1 if end_x > x else -1
|
|
path.append((x, y))
|
|
else:
|
|
while y != end_y:
|
|
y += 1 if end_y > y else -1
|
|
path.append((x, y))
|
|
return path
|
|
|
|
|
|
def _junction_at(point: Point) -> Rect:
|
|
radius = JUNCTION_SIZE // 2
|
|
return Rect(point[0] - radius, point[1] - radius, JUNCTION_SIZE, JUNCTION_SIZE)
|
|
|
|
|
|
def _contains_feature(point: Point, rooms: list[Rect], junctions: list[Rect]) -> bool:
|
|
return any(feature.contains(point) for feature in [*rooms, *junctions])
|
|
|
|
|
|
def _valid_junction(candidate: Rect, rooms: list[Rect], junctions: list[Rect]) -> bool:
|
|
inside_border = (
|
|
candidate.x >= MAP_BORDER
|
|
and candidate.y >= MAP_BORDER
|
|
and candidate.x2 <= MAP_WIDTH - MAP_BORDER
|
|
and candidate.y2 <= MAP_HEIGHT - MAP_BORDER
|
|
)
|
|
return inside_border and not any(
|
|
candidate.overlaps(feature) for feature in [*rooms, *junctions]
|
|
)
|
|
|
|
|
|
def _partition_point(
|
|
path: list[Point],
|
|
start_index: int,
|
|
rooms: list[Rect],
|
|
junctions: list[Rect],
|
|
) -> tuple[int, Rect | None]:
|
|
furthest = min(start_index + MAX_CORRIDOR_LENGTH, len(path) - 1)
|
|
for index in range(furthest, start_index, -1):
|
|
point = path[index]
|
|
if _contains_feature(point, rooms, junctions):
|
|
return index, None
|
|
candidate = _junction_at(point)
|
|
if _valid_junction(candidate, rooms, junctions):
|
|
return index, candidate
|
|
raise _GenerationError("corridor could not place a valid junction")
|
|
|
|
|
|
def _record_route(
|
|
tiles: Grid,
|
|
path: list[Point],
|
|
rooms: list[Rect],
|
|
junctions: list[Rect],
|
|
corridors: list[list[Point]],
|
|
) -> None:
|
|
start_index = 0
|
|
while len(path) - 1 - start_index > MAX_CORRIDOR_LENGTH:
|
|
end_index, junction = _partition_point(path, start_index, rooms, junctions)
|
|
if junction is not None:
|
|
junctions.append(junction)
|
|
_carve_rect(tiles, junction)
|
|
section = path[start_index : end_index + 1]
|
|
corridors.append(section)
|
|
_carve_path(tiles, section)
|
|
start_index = end_index
|
|
|
|
section = path[start_index:]
|
|
corridors.append(section)
|
|
_carve_path(tiles, section)
|
|
|
|
|
|
def _room_distance(first: Rect, second: Rect) -> int:
|
|
start, end, _ = _closest_endpoints(first, second)
|
|
return abs(start[0] - end[0]) + abs(start[1] - end[1])
|
|
|
|
|
|
def _connect_tree(
|
|
node: _Node,
|
|
tiles: Grid,
|
|
rooms: list[Rect],
|
|
junctions: list[Rect],
|
|
corridors: list[list[Point]],
|
|
) -> list[Rect]:
|
|
if node.room is not None:
|
|
return [node.room]
|
|
if node.left is None or node.right is None:
|
|
raise _GenerationError("invalid BSP tree")
|
|
|
|
left_rooms = _connect_tree(node.left, tiles, rooms, junctions, corridors)
|
|
right_rooms = _connect_tree(node.right, tiles, rooms, junctions, corridors)
|
|
first, second = min(
|
|
((first, second) for first in left_rooms for second in right_rooms),
|
|
key=lambda pair: _room_distance(*pair),
|
|
)
|
|
start, end, horizontal_first = _closest_endpoints(first, second)
|
|
_record_route(
|
|
tiles,
|
|
_ordered_path(start, end, horizontal_first),
|
|
rooms,
|
|
junctions,
|
|
corridors,
|
|
)
|
|
return left_rooms + right_rooms
|
|
|
|
|
|
def _generate_attempt(floor_index: int, rng: random.Random) -> GameMap:
|
|
if floor_index == FINAL_FLOOR:
|
|
return _generate_arena(rng)
|
|
root = _build_tree(rng)
|
|
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
|
|
rooms: list[Rect] = []
|
|
for leaf in _leaves(root):
|
|
leaf.room = _make_room(leaf.region, rng)
|
|
rooms.append(leaf.room)
|
|
_carve_rect(tiles, leaf.room)
|
|
|
|
junctions: list[Rect] = []
|
|
corridors: list[list[Point]] = []
|
|
_connect_tree(root, tiles, rooms, junctions, corridors)
|
|
spawn = rooms[0].center
|
|
farthest_room = max(
|
|
rooms[1:],
|
|
key=lambda room: abs(room.center[0] - spawn[0])
|
|
+ abs(room.center[1] - spawn[1]),
|
|
)
|
|
game_map = GameMap(
|
|
width=MAP_WIDTH,
|
|
height=MAP_HEIGHT,
|
|
tiles=tiles,
|
|
rooms=rooms,
|
|
junctions=junctions,
|
|
corridors=corridors,
|
|
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
|
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
|
entities=[],
|
|
stairs_down=farthest_room.center,
|
|
floor_index=floor_index,
|
|
spawn=spawn,
|
|
)
|
|
_populate(game_map, rng)
|
|
return game_map
|
|
|
|
|
|
def _generate_arena(rng: random.Random) -> GameMap:
|
|
"""Floor 9: one large room, the dragon across from the entrance."""
|
|
arena = Rect(
|
|
(MAP_WIDTH - ARENA_WIDTH) // 2,
|
|
(MAP_HEIGHT - ARENA_HEIGHT) // 2,
|
|
ARENA_WIDTH,
|
|
ARENA_HEIGHT,
|
|
)
|
|
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
|
|
_carve_rect(tiles, arena)
|
|
entrance = (arena.x + ARENA_ENTRANCE_OFFSET, arena.center[1])
|
|
game_map = GameMap(
|
|
width=MAP_WIDTH,
|
|
height=MAP_HEIGHT,
|
|
tiles=tiles,
|
|
rooms=[arena],
|
|
junctions=[],
|
|
corridors=[],
|
|
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
|
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
|
|
entities=[
|
|
spawn_enemy(
|
|
DRAGON_KEY,
|
|
arena.x2 - 1 - ARENA_DRAGON_OFFSET,
|
|
arena.center[1],
|
|
)
|
|
],
|
|
stairs_down=None,
|
|
floor_index=FINAL_FLOOR,
|
|
spawn=entrance,
|
|
)
|
|
for offset in (-2, 2):
|
|
potion = spawn_item("healing_potion", entrance[0], entrance[1] + offset)
|
|
game_map.entities.append(potion)
|
|
return game_map
|
|
|
|
|
|
def _free_tiles(room: Rect, occupied: set[Point]) -> list[Point]:
|
|
return [tile for tile in room.tiles() if tile not in occupied]
|
|
|
|
|
|
def _populate(game_map: GameMap, rng: random.Random) -> None:
|
|
"""Place floor items then enemies, spread round-robin over non-spawn rooms."""
|
|
occupied = {game_map.spawn}
|
|
if game_map.stairs_down is not None:
|
|
occupied.add(game_map.stairs_down)
|
|
rooms = [room for room in game_map.rooms if not room.contains(game_map.spawn)]
|
|
if not rooms:
|
|
rooms = list(game_map.rooms)
|
|
rng.shuffle(rooms)
|
|
|
|
placements: list[tuple[Callable[[str, int, int], Entity], str]] = [
|
|
*[(spawn_item, key) for key in roll_floor_items(game_map.floor_index, rng)],
|
|
*[(spawn_enemy, key) for key in roll_floor_enemies(game_map.floor_index, rng)],
|
|
]
|
|
for index, (spawner, key) in enumerate(placements):
|
|
free: list[Point] = []
|
|
for shift in range(len(rooms)):
|
|
candidate = rooms[(index + shift) % len(rooms)]
|
|
free = _free_tiles(candidate, occupied)
|
|
if free:
|
|
break
|
|
if not free:
|
|
raise _GenerationError("population ran out of free room tiles")
|
|
tile = rng.choice(free)
|
|
occupied.add(tile)
|
|
game_map.entities.append(spawner(key, tile[0], tile[1]))
|
|
|
|
|
|
def generate_map(floor_index: int = 0, seed: int | None = None) -> GameMap:
|
|
if not 0 <= floor_index <= FINAL_FLOOR:
|
|
raise ValueError(f"floor index must be between 0 and {FINAL_FLOOR}")
|
|
rng = random.Random(seed)
|
|
for _ in range(MAX_MAP_ATTEMPTS):
|
|
try:
|
|
return _generate_attempt(floor_index, rng)
|
|
except _GenerationError:
|
|
continue
|
|
raise RuntimeError(f"failed to generate floor {floor_index} after {MAX_MAP_ATTEMPTS} attempts")
|