from __future__ import annotations from dataclasses import dataclass from pathlib import Path from textwrap import wrap import pygame from ai.behaviors import take_enemy_turns from data.constants import ( BACKGROUND_COLOR, BOTTOM_PANEL_HEIGHT, ENTITY_INSET, EXPLORED_FLOOR_COLOR, EXPLORED_WALL_COLOR, FLOOR_COLOR, FPS, GAME_STATE_DEAD, GAME_STATE_PLAYING, GAME_STATE_VICTORY, GAME_TITLE, HELP_LINES, ITEM_INSET, LEVEL_THRESHOLDS, MESSAGE_WRAP_WIDTH, OVERLAY_HEIGHT, OVERLAY_WIDTH, PLAYER_COLOR, RIGHT_PANEL_WIDTH, STAIRS_COLOR, TILE_SIZE, TOP_PANEL_HEIGHT, UI_BACKGROUND_COLOR, UI_BAR_HEIGHT, UI_BORDER_COLOR, UI_DAMAGE_COLOR, UI_FONT_SIZE, UI_HEALTH_COLOR, UI_HEALTH_MISSING_COLOR, UI_ITEM_COLOR, UI_LEVEL_COLOR, UI_LINE_HEIGHT, UI_MUTED_COLOR, UI_OVERLAY_COLOR, UI_PADDING, UI_PANEL_COLOR, UI_SMALL_FONT_SIZE, UI_TEXT_COLOR, UI_TITLE_FONT_SIZE, UI_XP_COLOR, VIEWPORT_HEIGHT, VIEWPORT_WIDTH, WALL_COLOR, WINDOW_HEIGHT, WINDOW_WIDTH, ) from engine.fov import compute_fov from engine.game_state import ( GameSession, descend_floor, equip_item, move_player, new_game, pickup_item, tick_player_effects, use_item, ) from engine.serializers import ( DEFAULT_SAVE_PATH, delete_save, load_game, save_exists, save_game, ) from entities.item import Item MENU_NEW_GAME = "New Game" MENU_CONTINUE = "Continue" MENU_QUIT = "Quit" MODE_GAME = "game" MODE_INVENTORY = "inventory" MODE_EQUIPMENT = "equipment" MODE_POTION = "potion" MODE_SCROLL = "scroll" MODE_HELP = "help" MODE_TARGET = "target" ACTION_NONE = "none" ACTION_TURN = "turn" ACTION_SAVED = "saved" _MOVE_KEYS: dict[int, tuple[int, int]] = { pygame.K_UP: (0, -1), pygame.K_k: (0, -1), pygame.K_DOWN: (0, 1), pygame.K_j: (0, 1), pygame.K_LEFT: (-1, 0), pygame.K_h: (-1, 0), pygame.K_RIGHT: (1, 0), pygame.K_l: (1, 0), } @dataclass(slots=True) class UIState: mode: str = MODE_GAME selected: int = 0 target: tuple[int, int] | None = None pending_item: Item | None = None @dataclass(frozen=True, slots=True) class Fonts: small: pygame.font.Font normal: pygame.font.Font title: pygame.font.Font def create_fonts() -> Fonts: return Fonts( small=pygame.font.Font(None, UI_SMALL_FONT_SIZE), normal=pygame.font.Font(None, UI_FONT_SIZE), title=pygame.font.Font(None, UI_TITLE_FONT_SIZE), ) def menu_options(save_path: str | Path = DEFAULT_SAVE_PATH) -> tuple[str, ...]: if save_exists(save_path): return MENU_NEW_GAME, MENU_CONTINUE, MENU_QUIT return MENU_NEW_GAME, MENU_QUIT def handle_menu_key( key: int, selected: int, options: tuple[str, ...] ) -> tuple[int, str | None]: if not options: return 0, None if key in {pygame.K_UP, pygame.K_k}: return (selected - 1) % len(options), None if key in {pygame.K_DOWN, pygame.K_j}: return (selected + 1) % len(options), None if key in {pygame.K_RETURN, pygame.K_KP_ENTER}: return selected % len(options), options[selected % len(options)] direct = { pygame.K_n: MENU_NEW_GAME, pygame.K_c: MENU_CONTINUE, pygame.K_q: MENU_QUIT, pygame.K_ESCAPE: MENU_QUIT, }.get(key) return selected % len(options), direct if direct in options else None def activate_menu_option( option: str, save_path: str | Path = DEFAULT_SAVE_PATH ) -> GameSession | None: if option == MENU_QUIT: return None session = new_game() if option == MENU_NEW_GAME else load_game(save_path) if session.state != GAME_STATE_PLAYING: delete_save(save_path) raise ValueError("the saved run has already ended") compute_fov(session.current_map, session.player.x, session.player.y) return session def enforce_permadeath( session: GameSession, save_path: str | Path = DEFAULT_SAVE_PATH ) -> bool: if session.state not in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: return False delete_save(save_path) return True def _finish_turn(session: GameSession) -> None: tick_player_effects(session) session.turn += 1 take_enemy_turns(session) compute_fov(session.current_map, session.player.x, session.player.y) def _open_mode(ui: UIState, mode: str) -> None: ui.mode = mode ui.selected = 0 ui.target = None ui.pending_item = None def selectable_items(session: GameSession, mode: str) -> list[Item]: if mode == MODE_EQUIPMENT: return [item for item in session.player.inventory if item.category in {"weapon", "armor"}] if mode == MODE_POTION: return [item for item in session.player.inventory if item.category == "potion"] if mode == MODE_SCROLL: return [item for item in session.player.inventory if item.category == "scroll"] return list(session.player.inventory) def _confirm_item(session: GameSession, ui: UIState, item: Item) -> str: if item.category in {"weapon", "armor"}: if equip_item(session, item): _open_mode(ui, MODE_GAME) _finish_turn(session) return ACTION_TURN return ACTION_NONE if item.effect == "fireball": ui.mode = MODE_TARGET ui.target = session.player.position ui.pending_item = item return ACTION_NONE if use_item(session, item): _open_mode(ui, MODE_GAME) _finish_turn(session) return ACTION_TURN return ACTION_NONE def _handle_target_key(session: GameSession, key: int, ui: UIState) -> str: if key == pygame.K_ESCAPE: _open_mode(ui, MODE_SCROLL) return ACTION_NONE if key in _MOVE_KEYS and ui.target is not None: dx, dy = _MOVE_KEYS[key] x = min(max(0, ui.target[0] + dx), session.current_map.width - 1) y = min(max(0, ui.target[1] + dy), session.current_map.height - 1) ui.target = x, y return ACTION_NONE if key not in {pygame.K_RETURN, pygame.K_KP_ENTER}: return ACTION_NONE if ui.pending_item is None or ui.target is None: _open_mode(ui, MODE_GAME) return ACTION_NONE if not session.current_map.visible[session.current_map.index(*ui.target)]: session.add_message("You cannot target a place you cannot see.") return ACTION_NONE if use_item(session, ui.pending_item, ui.target): _open_mode(ui, MODE_GAME) _finish_turn(session) return ACTION_TURN return ACTION_NONE def _handle_overlay_key(session: GameSession, key: int, ui: UIState) -> str: if ui.mode == MODE_TARGET: return _handle_target_key(session, key, ui) if key == pygame.K_ESCAPE: _open_mode(ui, MODE_GAME) return ACTION_NONE if ui.mode == MODE_HELP: if key in {pygame.K_SLASH, getattr(pygame, "K_QUESTION", ord("?"))}: _open_mode(ui, MODE_GAME) return ACTION_NONE items = selectable_items(session, ui.mode) if not items: return ACTION_NONE if key in {pygame.K_UP, pygame.K_k}: ui.selected = (ui.selected - 1) % len(items) return ACTION_NONE if key in {pygame.K_DOWN, pygame.K_j}: ui.selected = (ui.selected + 1) % len(items) return ACTION_NONE if pygame.K_a <= key <= pygame.K_z: index = key - pygame.K_a if index < len(items): ui.selected = index return _confirm_item(session, ui, items[index]) return ACTION_NONE if key in {pygame.K_RETURN, pygame.K_KP_ENTER}: ui.selected %= len(items) return _confirm_item(session, ui, items[ui.selected]) return ACTION_NONE def handle_key( session: GameSession, key: int, ui: UIState | None = None, save_path: str | Path = DEFAULT_SAVE_PATH, mods: int = 0, ) -> str: ui = ui or UIState() if ui.mode != MODE_GAME: return _handle_overlay_key(session, key, ui) if key == pygame.K_ESCAPE: return ACTION_NONE if key == pygame.K_i: _open_mode(ui, MODE_INVENTORY) return ACTION_NONE if key == pygame.K_e: _open_mode(ui, MODE_EQUIPMENT) return ACTION_NONE if key == pygame.K_q: _open_mode(ui, MODE_POTION) return ACTION_NONE if key == pygame.K_r: _open_mode(ui, MODE_SCROLL) return ACTION_NONE if key in {pygame.K_SLASH, getattr(pygame, "K_QUESTION", ord("?"))} and ( key != pygame.K_SLASH or mods & pygame.KMOD_SHIFT ): _open_mode(ui, MODE_HELP) return ACTION_NONE if key == pygame.K_s: try: save_game(session, save_path) except OSError as error: session.add_message(f"Could not save: {error}") return ACTION_NONE return ACTION_SAVED if key in _MOVE_KEYS: if not move_player(session, *_MOVE_KEYS[key]): return ACTION_NONE take_enemy_turns(session) compute_fov(session.current_map, session.player.x, session.player.y) return ACTION_TURN if key == pygame.K_g: if not pickup_item(session): return ACTION_NONE _finish_turn(session) return ACTION_TURN if key in {pygame.K_PERIOD, getattr(pygame, "K_GREATER", ord(">"))} and ( key != pygame.K_PERIOD or mods & pygame.KMOD_SHIFT ): if not descend_floor(session): return ACTION_NONE _finish_turn(session) return ACTION_TURN return ACTION_NONE def camera_origin(session: GameSession) -> tuple[int, int]: game_map = session.current_map x = min(max(0, session.player.x - VIEWPORT_WIDTH // 2), game_map.width - VIEWPORT_WIDTH) y = min(max(0, session.player.y - VIEWPORT_HEIGHT // 2), game_map.height - VIEWPORT_HEIGHT) return x, y def _draw_bar( screen: pygame.Surface, rect: pygame.Rect, ratio: float, fill_color: tuple[int, int, int], empty_color: tuple[int, int, int], ) -> None: pygame.draw.rect(screen, empty_color, rect) filled = rect.copy() filled.width = round(rect.width * min(1.0, max(0.0, ratio))) pygame.draw.rect(screen, fill_color, filled) pygame.draw.rect(screen, UI_BORDER_COLOR, rect, 1) def _draw_world(screen: pygame.Surface, session: GameSession, fonts: Fonts) -> None: game_map = session.current_map camera_x, camera_y = camera_origin(session) for screen_y in range(VIEWPORT_HEIGHT): map_y = camera_y + screen_y for screen_x in range(VIEWPORT_WIDTH): map_x = camera_x + screen_x index = game_map.index(map_x, map_y) if not game_map.explored[index]: color = BACKGROUND_COLOR elif game_map.visible[index]: color = FLOOR_COLOR if game_map.is_floor(map_x, map_y) else WALL_COLOR else: color = EXPLORED_FLOOR_COLOR if game_map.is_floor(map_x, map_y) else EXPLORED_WALL_COLOR pygame.draw.rect( screen, color, ( screen_x * TILE_SIZE, TOP_PANEL_HEIGHT + screen_y * TILE_SIZE, TILE_SIZE, TILE_SIZE, ), ) if game_map.stairs_down is not None: stairs_x, stairs_y = game_map.stairs_down stairs_index = game_map.index(stairs_x, stairs_y) if game_map.explored[stairs_index]: color = STAIRS_COLOR if game_map.visible[stairs_index] else UI_MUTED_COLOR glyph = fonts.small.render(">", True, color) screen.blit( glyph, ( (stairs_x - camera_x) * TILE_SIZE, TOP_PANEL_HEIGHT + (stairs_y - camera_y) * TILE_SIZE, ), ) for entity in game_map.entities: if not game_map.visible[game_map.index(entity.x, entity.y)]: continue screen_x = entity.x - camera_x screen_y = entity.y - camera_y if not 0 <= screen_x < VIEWPORT_WIDTH or not 0 <= screen_y < VIEWPORT_HEIGHT: continue inset = ITEM_INSET if isinstance(entity, Item) else ENTITY_INSET pygame.draw.rect( screen, entity.color, ( screen_x * TILE_SIZE + inset, TOP_PANEL_HEIGHT + screen_y * TILE_SIZE + inset, TILE_SIZE - inset * 2, TILE_SIZE - inset * 2, ), ) player_x = (session.player.x - camera_x) * TILE_SIZE + TILE_SIZE // 2 player_y = TOP_PANEL_HEIGHT + (session.player.y - camera_y) * TILE_SIZE + TILE_SIZE // 2 pygame.draw.circle(screen, PLAYER_COLOR, (player_x, player_y), TILE_SIZE // 2) def _message_color(message: str) -> tuple[int, int, int]: lowered = message.lower() if "reach level" in lowered: return UI_LEVEL_COLOR if any(word in lowered for word in ("pick up", "equip", "potion", "scroll")): return UI_ITEM_COLOR if any(phrase in lowered for phrase in ("hits you", "shoots you", "burns you", "you died")): return UI_DAMAGE_COLOR return UI_TEXT_COLOR def _draw_panels(screen: pygame.Surface, session: GameSession, fonts: Fonts) -> None: map_width = VIEWPORT_WIDTH * TILE_SIZE map_height = VIEWPORT_HEIGHT * TILE_SIZE pygame.draw.rect(screen, UI_PANEL_COLOR, (0, 0, map_width, TOP_PANEL_HEIGHT)) pygame.draw.rect( screen, UI_PANEL_COLOR, (map_width, 0, RIGHT_PANEL_WIDTH, WINDOW_HEIGHT), ) pygame.draw.rect( screen, UI_PANEL_COLOR, (0, TOP_PANEL_HEIGHT + map_height, map_width, BOTTOM_PANEL_HEIGHT), ) pygame.draw.line(screen, UI_BORDER_COLOR, (map_width, 0), (map_width, WINDOW_HEIGHT)) floor_text = fonts.normal.render( f"Floor {session.current_floor + 1}/10", True, UI_TEXT_COLOR ) screen.blit(floor_text, (UI_PADDING, UI_PADDING)) hp_x = floor_text.get_width() + UI_PADDING * 2 hp_width = map_width // 3 hp_rect = pygame.Rect(hp_x, UI_PADDING, hp_width, UI_BAR_HEIGHT) _draw_bar( screen, hp_rect, session.player.hp / max(1, session.player.max_hp), UI_HEALTH_COLOR, UI_HEALTH_MISSING_COLOR, ) hp_text = fonts.small.render( f"HP {max(0, session.player.hp)}/{session.player.max_hp}", True, UI_TEXT_COLOR ) screen.blit(hp_text, (hp_x + UI_PADDING // 2, UI_PADDING)) level_text = fonts.normal.render(f"Level {session.player.level}", True, UI_TEXT_COLOR) level_x = hp_rect.right + UI_PADDING screen.blit(level_text, (level_x, UI_PADDING)) previous_xp = LEVEL_THRESHOLDS[session.player.level - 2] if session.player.level > 1 else 0 next_xp = ( LEVEL_THRESHOLDS[session.player.level - 1] if session.player.level <= len(LEVEL_THRESHOLDS) else session.player.xp ) xp_ratio = 1.0 if next_xp == previous_xp else (session.player.xp - previous_xp) / (next_xp - previous_xp) xp_rect = pygame.Rect(level_x + level_text.get_width() + UI_PADDING, UI_PADDING, map_width - level_x - level_text.get_width() - UI_PADDING * 2, UI_BAR_HEIGHT) _draw_bar(screen, xp_rect, xp_ratio, UI_XP_COLOR, UI_BACKGROUND_COLOR) log_title = fonts.normal.render("Messages", True, UI_TEXT_COLOR) screen.blit(log_title, (map_width + UI_PADDING, UI_PADDING)) lines: list[tuple[str, tuple[int, int, int]]] = [] for message in session.log[-8:]: color = _message_color(message) lines.extend((line, color) for line in wrap(message, MESSAGE_WRAP_WIDTH) or [message]) lines = lines[-8:] log_bottom = TOP_PANEL_HEIGHT + map_height - UI_PADDING for offset, (line, color) in enumerate(reversed(lines), start=1): text = fonts.small.render(line, True, color) screen.blit(text, (map_width + UI_PADDING, log_bottom - offset * UI_LINE_HEIGHT)) weapon = session.player.weapon.name if session.player.weapon else "None" armor = session.player.armor_item.name if session.player.armor_item else "None" equipment = fonts.normal.render( f"Weapon: {weapon} Armor: {armor}", True, UI_TEXT_COLOR ) screen.blit(equipment, (UI_PADDING, TOP_PANEL_HEIGHT + map_height + UI_PADDING)) def _overlay_title(mode: str) -> str: return { MODE_INVENTORY: "Inventory", MODE_EQUIPMENT: "Equipment", MODE_POTION: "Quaff a Potion", MODE_SCROLL: "Read a Scroll", MODE_HELP: "Help", MODE_TARGET: "Target Fireball", }.get(mode, "") def _draw_overlay( screen: pygame.Surface, session: GameSession, ui: UIState, fonts: Fonts ) -> None: if ui.mode == MODE_GAME: return left = (WINDOW_WIDTH - OVERLAY_WIDTH) // 2 top = (WINDOW_HEIGHT - OVERLAY_HEIGHT) // 2 rect = pygame.Rect(left, top, OVERLAY_WIDTH, OVERLAY_HEIGHT) pygame.draw.rect(screen, UI_OVERLAY_COLOR, rect) pygame.draw.rect(screen, UI_BORDER_COLOR, rect, 2) title = fonts.title.render(_overlay_title(ui.mode), True, UI_TEXT_COLOR) screen.blit(title, (left + UI_PADDING, top + UI_PADDING)) y = top + title.get_height() + UI_PADDING * 2 if ui.mode == MODE_HELP: for line in HELP_LINES: screen.blit(fonts.normal.render(line, True, UI_TEXT_COLOR), (left + UI_PADDING, y)) y += UI_LINE_HEIGHT return if ui.mode == MODE_TARGET: line = "Arrows/hjkl move target; Enter casts; Esc cancels" screen.blit(fonts.normal.render(line, True, UI_TEXT_COLOR), (left + UI_PADDING, y)) if ui.target is not None: target = fonts.normal.render(f"Target: {ui.target}", True, UI_ITEM_COLOR) screen.blit(target, (left + UI_PADDING, y + UI_LINE_HEIGHT * 2)) camera_x, camera_y = camera_origin(session) x = (ui.target[0] - camera_x) * TILE_SIZE target_y = TOP_PANEL_HEIGHT + (ui.target[1] - camera_y) * TILE_SIZE pygame.draw.rect(screen, UI_ITEM_COLOR, (x, target_y, TILE_SIZE, TILE_SIZE), 2) return if ui.mode == MODE_EQUIPMENT: weapon = session.player.weapon.name if session.player.weapon else "None" armor = session.player.armor_item.name if session.player.armor_item else "None" for line in (f"Weapon: {weapon}", f"Armor: {armor}"): screen.blit(fonts.normal.render(line, True, UI_MUTED_COLOR), (left + UI_PADDING, y)) y += UI_LINE_HEIGHT y += UI_PADDING items = selectable_items(session, ui.mode) if not items: empty = fonts.normal.render("No matching items. Esc closes.", True, UI_MUTED_COLOR) screen.blit(empty, (left + UI_PADDING, y)) return ui.selected %= len(items) rows = max(1, (top + OVERLAY_HEIGHT - UI_PADDING - y) // UI_LINE_HEIGHT) start = min(max(0, ui.selected - rows + 1), max(0, len(items) - rows)) for index in range(start, min(len(items), start + rows)): item = items[index] prefix = chr(ord("a") + index) color = UI_ITEM_COLOR if index == ui.selected else UI_TEXT_COLOR marker = ">" if index == ui.selected else " " text = fonts.normal.render(f"{marker} {prefix}) {item.name}", True, color) screen.blit(text, (left + UI_PADDING, y)) y += UI_LINE_HEIGHT def render( screen: pygame.Surface, session: GameSession, ui: UIState | None = None, fonts: Fonts | None = None, ) -> None: fonts = fonts or create_fonts() ui = ui or UIState() screen.fill(UI_BACKGROUND_COLOR) _draw_world(screen, session, fonts) _draw_panels(screen, session, fonts) _draw_overlay(screen, session, ui, fonts) def render_menu( screen: pygame.Surface, selected: int, save_path: str | Path = DEFAULT_SAVE_PATH, message: str = "", fonts: Fonts | None = None, ) -> None: fonts = fonts or create_fonts() screen.fill(UI_BACKGROUND_COLOR) title = fonts.title.render(GAME_TITLE, True, UI_TEXT_COLOR) screen.blit(title, ((WINDOW_WIDTH - title.get_width()) // 2, WINDOW_HEIGHT // 4)) options = menu_options(save_path) for index, option in enumerate(options): color = UI_ITEM_COLOR if index == selected % len(options) else UI_TEXT_COLOR text = fonts.normal.render(option, True, color) screen.blit( text, ( (WINDOW_WIDTH - text.get_width()) // 2, WINDOW_HEIGHT // 2 + index * UI_LINE_HEIGHT * 2, ), ) if message: text = fonts.small.render(message, True, UI_DAMAGE_COLOR) screen.blit(text, ((WINDOW_WIDTH - text.get_width()) // 2, WINDOW_HEIGHT - UI_PADDING * 3)) def render_end_screen( screen: pygame.Surface, session: GameSession, fonts: Fonts | None = None ) -> None: fonts = fonts or create_fonts() screen.fill(UI_BACKGROUND_COLOR) if session.state == GAME_STATE_DEAD: title_text = "You died" detail = f"You died on floor {session.current_floor + 1}. You reached level {session.player.level}." color = UI_DAMAGE_COLOR else: title_text = "Victory" detail = "You slew the Ancient Dragon! You conquered Underdepths." color = UI_LEVEL_COLOR title = fonts.title.render(title_text, True, color) message = fonts.normal.render(detail, True, UI_TEXT_COLOR) prompt = fonts.small.render("Press any key to return to the menu.", True, UI_MUTED_COLOR) center_y = WINDOW_HEIGHT // 2 screen.blit(title, ((WINDOW_WIDTH - title.get_width()) // 2, center_y - UI_LINE_HEIGHT * 3)) screen.blit(message, ((WINDOW_WIDTH - message.get_width()) // 2, center_y)) screen.blit(prompt, ((WINDOW_WIDTH - prompt.get_width()) // 2, center_y + UI_LINE_HEIGHT * 2)) def main(max_frames: int | None = None) -> None: pygame.init() screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption(GAME_TITLE) fonts = create_fonts() clock = pygame.time.Clock() session: GameSession | None = None ui = UIState() menu_selected = 0 menu_message = "" running = True frames = 0 while running and (max_frames is None or frames < max_frames): for event in pygame.event.get(): if event.type == pygame.QUIT: running = False continue if event.type != pygame.KEYDOWN: continue if session is None: options = menu_options() menu_selected, option = handle_menu_key(event.key, menu_selected, options) if option == MENU_QUIT: running = False elif option is not None: try: session = activate_menu_option(option) ui = UIState() menu_message = "" except ValueError as error: menu_message = str(error) continue if session.state in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: enforce_permadeath(session) session = None menu_selected = 0 continue result = handle_key(session, event.key, ui, mods=event.mod) enforce_permadeath(session) if result == ACTION_SAVED: session = None ui = UIState() menu_selected = 0 if session is None: options = menu_options() menu_selected %= len(options) render_menu(screen, menu_selected, message=menu_message, fonts=fonts) elif session.state in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: enforce_permadeath(session) render_end_screen(screen, session, fonts) else: render(screen, session, ui, fonts) pygame.display.flip() clock.tick(FPS) frames += 1 pygame.quit() if __name__ == "__main__": main()