from __future__ import annotations import random from array import array from dataclasses import dataclass from data.constants import ( BSP_MAX_SPLITS, BSP_MIN_SPLITS, BOSS_ARENA_HEIGHT, BOSS_ARENA_WIDTH, BOSS_FLOOR, FLOOR_SPAWN_COUNTS, MAP_HEIGHT, MAP_WIDTH, ROOM_MARGIN, ROOM_MAX_HEIGHT, ROOM_MAX_WIDTH, ROOM_MIN_HEIGHT, ROOM_MIN_WIDTH, TILE_FLOOR, TILE_WALL, ) from entities.entity import Entity @dataclass(frozen=True, slots=True) class Rect: x: int y: int width: int height: int @property def right(self) -> int: return self.x + self.width @property def bottom(self) -> int: return self.y + self.height @property def center(self) -> tuple[int, int]: return self.x + self.width // 2, self.y + self.height // 2 def intersects(self, other: Rect) -> bool: return not ( self.right <= other.x or other.right <= self.x or self.bottom <= other.y or other.bottom <= self.y ) @dataclass(slots=True) class GameMap: width: int height: int tiles: array[int] rooms: list[Rect] explored: array[int] visible: array[int] entities: list[Entity] stairs_down: tuple[int, int] | None spawn: tuple[int, int] floor_index: int def index(self, x: int, y: int) -> int: return y * self.width + x def in_bounds(self, x: int, y: int) -> bool: return 0 <= x < self.width and 0 <= y < self.height def is_floor(self, x: int, y: int) -> bool: return self.in_bounds(x, y) and self.tiles[self.index(x, y)] == TILE_FLOOR def ascii(self) -> str: rows: list[str] = [] for y in range(self.height): row: list[str] = [] for x in range(self.width): position = (x, y) if position == self.spawn: row.append("@") elif position == self.stairs_down: row.append(">") else: row.append("." if self.is_floor(x, y) else "#") rows.append("".join(row)) return "\n".join(rows) @dataclass(slots=True) class _Node: region: Rect depth: int left: _Node | None = None right: _Node | None = None room: Rect | None = None @property def is_leaf(self) -> bool: return self.left is None _MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2 _MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2 def _split(node: _Node, rng: random.Random) -> bool: can_split_vertical = node.region.width >= _MIN_REGION_WIDTH * 2 can_split_horizontal = node.region.height >= _MIN_REGION_HEIGHT * 2 if not can_split_vertical and not can_split_horizontal: return False split_vertical = node.depth % 2 == 0 if split_vertical and not can_split_vertical: split_vertical = False elif not split_vertical and not can_split_horizontal: split_vertical = True region = node.region if split_vertical: offset = rng.randint(_MIN_REGION_WIDTH, region.width - _MIN_REGION_WIDTH) first = Rect(region.x, region.y, offset, region.height) second = Rect(region.x + offset, region.y, region.width - offset, region.height) else: offset = rng.randint(_MIN_REGION_HEIGHT, region.height - _MIN_REGION_HEIGHT) 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 _carve_tile(game_map: GameMap, x: int, y: int) -> None: game_map.tiles[game_map.index(x, y)] = TILE_FLOOR def _carve_room(game_map: GameMap, room: Rect) -> None: for y in range(room.y, room.bottom): for x in range(room.x, room.right): _carve_tile(game_map, x, y) def _carve_corridor( game_map: GameMap, start: tuple[int, int], end: tuple[int, int], rng: random.Random, ) -> None: x1, y1 = start x2, y2 = end corner = (x2, y1) if rng.random() < 0.5 else (x1, y2) for x in range(min(x1, corner[0]), max(x1, corner[0]) + 1): _carve_tile(game_map, x, y1) for y in range(min(y1, corner[1]), max(y1, corner[1]) + 1): _carve_tile(game_map, corner[0], y) for x in range(min(corner[0], x2), max(corner[0], x2) + 1): _carve_tile(game_map, x, y2) for y in range(min(corner[1], y2), max(corner[1], y2) + 1): _carve_tile(game_map, x2, y) def _carve_tree(game_map: GameMap, node: _Node, rng: random.Random) -> tuple[int, int]: if node.is_leaf: region = node.region room_width = rng.randint(ROOM_MIN_WIDTH, min(ROOM_MAX_WIDTH, region.width - ROOM_MARGIN * 2)) room_height = rng.randint(ROOM_MIN_HEIGHT, min(ROOM_MAX_HEIGHT, region.height - ROOM_MARGIN * 2)) room = Rect( rng.randint(region.x + ROOM_MARGIN, region.right - room_width - ROOM_MARGIN), rng.randint(region.y + ROOM_MARGIN, region.bottom - room_height - ROOM_MARGIN), room_width, room_height, ) node.room = room game_map.rooms.append(room) _carve_room(game_map, room) return room.center if node.left is None or node.right is None: raise RuntimeError("invalid BSP tree") left_center = _carve_tree(game_map, node.left, rng) right_center = _carve_tree(game_map, node.right, rng) _carve_corridor(game_map, left_center, right_center, rng) return left_center def generate_dungeon(floor_index: int = 0, rng: random.Random | None = None) -> GameMap: rng = rng or random.Random() if floor_index == BOSS_FLOOR: return _generate_boss_arena(rng) root = _Node(Rect(1, 1, MAP_WIDTH - 2, MAP_HEIGHT - 2), 0) leaves = [root] for _ in range(rng.randint(BSP_MIN_SPLITS, BSP_MAX_SPLITS)): candidates = [leaf for leaf in leaves if _split_possible(leaf)] if not candidates: break leaf = max(candidates, key=lambda candidate: candidate.region.width * candidate.region.height) leaves.remove(leaf) if _split(leaf, rng): if leaf.left is None or leaf.right is None: raise RuntimeError("BSP split did not create children") leaves.extend((leaf.left, leaf.right)) game_map = _empty_map(floor_index) _carve_tree(game_map, root, rng) game_map.spawn = game_map.rooms[0].center game_map.stairs_down = max( (room.center for room in game_map.rooms), key=lambda center: abs(center[0] - game_map.spawn[0]) + abs(center[1] - game_map.spawn[1]), ) _spawn_content(game_map, rng) return game_map def _empty_map(floor_index: int) -> GameMap: size = MAP_WIDTH * MAP_HEIGHT return GameMap( width=MAP_WIDTH, height=MAP_HEIGHT, tiles=array("B", [TILE_WALL]) * size, rooms=[], explored=array("B", [0]) * size, visible=array("B", [0]) * size, entities=[], stairs_down=None, spawn=(0, 0), floor_index=floor_index, ) def _generate_boss_arena(rng: random.Random) -> GameMap: from data.enemies import create_enemy from data.items import create_item game_map = _empty_map(BOSS_FLOOR) arena = Rect( rng.randint(1, MAP_WIDTH - BOSS_ARENA_WIDTH - 1), rng.randint(1, MAP_HEIGHT - BOSS_ARENA_HEIGHT - 1), BOSS_ARENA_WIDTH, BOSS_ARENA_HEIGHT, ) game_map.rooms.append(arena) _carve_room(game_map, arena) entrance_x = arena.x + 1 entrance_y = arena.y + arena.height // 2 game_map.spawn = (entrance_x, entrance_y) game_map.entities.append(create_enemy("Ancient Dragon", arena.right - 2, entrance_y)) potion_positions = ((entrance_x + 1, entrance_y - 1), (entrance_x + 1, entrance_y + 1)) game_map.entities.extend(create_item("Healing Potion", x, y) for x, y in potion_positions) return game_map def _spawn_content(game_map: GameMap, rng: random.Random) -> None: from data.enemies import create_enemy, enemy_names_for_floor from data.items import create_item, item_names_for_floor minimum_enemies, maximum_enemies, minimum_items, maximum_items = FLOOR_SPAWN_COUNTS[game_map.floor_index] enemy_count = rng.randint(minimum_enemies, maximum_enemies) item_count = rng.randint(minimum_items, maximum_items) blocked = {game_map.spawn, game_map.stairs_down} positions = [ (x, y) for y in range(game_map.height) for x in range(game_map.width) if game_map.is_floor(x, y) and (x, y) not in blocked ] rng.shuffle(positions) enemy_names = enemy_names_for_floor(game_map.floor_index) item_names = item_names_for_floor(game_map.floor_index) for position in positions[:enemy_count]: game_map.entities.append(create_enemy(rng.choice(enemy_names), *position)) for position in positions[enemy_count : enemy_count + item_count]: game_map.entities.append(create_item(rng.choice(item_names), *position)) def _split_possible(node: _Node) -> bool: return ( node.region.width >= _MIN_REGION_WIDTH * 2 or node.region.height >= _MIN_REGION_HEIGHT * 2 )