Files
agentic-labs-challenge/underdepths/main.py
T
2026-08-14 09:46:04 +02:00

281 lines
11 KiB
Python

"""Entry point, game loop, and state machine for Underdepths.
Headless detection honors ``SDL_VIDEODRIVER=='dummy'`` (never forced in code);
``UNDERDEPTHS_MAX_FRAMES`` bounds a run so the harness can launch this headless
and exit cleanly. ``new_game(seed)`` builds a fresh ``GameSession``.
State machine: menu -> (howto) -> playing -> {dead, victory, saved} -> menu.
All gameplay intents flow through ``engine.actions.apply_input``; sound effects
are best-effort and never block.
"""
from __future__ import annotations
import os
import sys
from typing import Any
import pygame
from data.constants import MAP_W, MAP_H, TILE, COLORS
from engine import actions as act
from engine.audio import AudioEngine
from engine.game_state import new_session
from render.camera import Camera
from render.renderer import Renderer
SCREEN_W = 960
SCREEN_H = 600
FONT_STACK = "monospace,consolas,couriernew,dejavusans"
MAXFRAMES_ENV = "UNDERDEPTHS_MAX_FRAMES"
_MENU = ["New Game", "Continue", "How to Play", "Quit"]
_HOWTO = [
"UNDERDEPTHS - How to Play",
"",
"Move / attack ....... Arrows or H J K L (walk into an enemy to hit it)",
"Pick up item ........ G (stand on the item first)",
"Descend stairs ...... F (stand on the yellow > stairs first)",
"Inventory list ...... I Equip best gear ... E",
"Quaff potion ........ Q Read scroll ........ R",
"Save & quit ......... S How to Play ........ ?",
"Mute sound .......... M Wait one turn ...... .",
"Cancel / close ...... Esc",
"",
"Descend 10 floors. Slay the Ancient Dragon on floor 10 to win.",
"Walk onto an item's tile, then press G to pick it up.",
"Walk onto the yellow > stairs tile, then press F to descend.",
"",
"Press any key to return.",
]
def new_game(seed: int = 0) -> Any:
return new_session(seed)
# --------------------------------------------------------------------- helpers
def _font(size: int, bold: bool = False) -> pygame.font.Font:
try:
return pygame.font.SysFont(FONT_STACK, size, bold=bold)
except Exception:
return pygame.font.Font(None, size)
def _draw_text(surf: pygame.Surface, msg: str, pos: tuple[int, int],
color: tuple[int, int, int], font: pygame.font.Font) -> None:
try:
surf.blit(font.render(msg, True, color), pos)
except Exception:
pass
def _play_for_log(audio: AudioEngine, new_lines: list[str]) -> None:
for line in new_lines:
low = line.lower()
if "critical" in low:
audio.play("crit")
elif "defeated" in low or "slew" in low:
audio.play("levelup")
elif "reach level" in low:
audio.play("levelup")
elif "you hit" in low:
audio.play("hit")
elif "miss" in low:
audio.play("miss")
elif "pick up" in low:
audio.play("pickup")
elif "descend" in low:
audio.play("stairs")
elif "equip" in low or "quaff" in low or "read" in low:
audio.play("use")
_KEYMAP = {
pygame.K_UP: "up", pygame.K_DOWN: "down", pygame.K_LEFT: "left", pygame.K_RIGHT: "right",
pygame.K_h: "left", pygame.K_j: "down", pygame.K_k: "up", pygame.K_l: "right",
pygame.K_g: "g", pygame.K_f: "f", pygame.K_i: "i", pygame.K_e: "e",
pygame.K_q: "q", pygame.K_r: "r", pygame.K_PERIOD: "wait",
}
# --------------------------------------------------------------------- screens
def _draw_menu(screen: pygame.Surface, idx: int, has_save: bool,
title_f: pygame.font.Font, opt_f: pygame.font.Font) -> None:
screen.fill(COLORS["bg"])
_draw_text(screen, "UNDERDEPTHS", (SCREEN_W // 2 - 140, 90), COLORS["stairs"], title_f)
_draw_text(screen, "a turn-based roguelike descent", (SCREEN_W // 2 - 150, 140),
COLORS["text_dim"], opt_f)
y = 230
for i, label in enumerate(_MENU):
if label == "Continue" and not has_save:
color = COLORS["text_dim"]
elif i == idx:
color = COLORS["stairs"]
_draw_text(screen, ">", (SCREEN_W // 2 - 130, y), COLORS["stairs"], opt_f)
color = COLORS["stairs"]
else:
color = COLORS["text"]
_draw_text(screen, label, (SCREEN_W // 2 - 100, y), color, opt_f)
y += 40
_draw_text(screen, "Up/Down to choose, Enter to select", (SCREEN_W // 2 - 160, SCREEN_H - 50),
COLORS["text_dim"], opt_f)
def _draw_howto(screen: pygame.Surface, font: pygame.font.Font,
big: pygame.font.Font) -> None:
screen.fill(COLORS["bg"])
for i, line in enumerate(_HOWTO):
col = COLORS["stairs"] if line.startswith("UNDERDEPTHS") else COLORS["text"]
f = big if i == 0 else font
_draw_text(screen, line, (60, 40 + i * 28), col, f)
def _draw_endcard(screen: pygame.Surface, session: Any, kind: str,
big: pygame.font.Font, font: pygame.font.Font) -> None:
overlay = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 170))
screen.blit(overlay, (0, 0))
if kind == "dead":
title, col = "YOU DIED", COLORS["hp_empty"]
sub = f"You fell on floor {session.current_floor + 1} at level {session.player.level}."
else:
title, col = "VICTORY", COLORS["stairs"]
sub = "You slew the Ancient Dragon and conquered Underdepths."
_draw_text(screen, title, (SCREEN_W // 2 - 120, SCREEN_H // 2 - 60), col, big)
_draw_text(screen, sub, (SCREEN_W // 2 - 220, SCREEN_H // 2), COLORS["text"], font)
_draw_text(screen, "Press any key to return to the menu",
(SCREEN_W // 2 - 160, SCREEN_H // 2 + 50), COLORS["text_dim"], font)
# --------------------------------------------------------------------- main
def main(argv: list[str] | None = None) -> int:
headless = os.environ.get("SDL_VIDEODRIVER") == "dummy"
try:
max_frames = int(os.environ.get(MAXFRAMES_ENV, "0"))
except ValueError:
max_frames = 0
pygame.init()
audio = AudioEngine(enabled=True)
try:
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), 0 if headless else pygame.SCALED)
except Exception:
screen = pygame.Surface((SCREEN_W, SCREEN_H))
pygame.display.set_caption("Underdepths")
renderer = Renderer()
camera = Camera()
title_f, opt_f, big_f, font_f = _font(40, True), _font(20, True), _font(28, True), _font(18)
ui = "menu"
menu_idx = 0
session: Any = None
last_log_len = 0
clock = pygame.time.Clock()
running = True
frame = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
k = event.key
if ui == "menu":
if k in (pygame.K_DOWN, pygame.K_s):
menu_idx = (menu_idx + 1) % len(_MENU)
audio.play("menu")
elif k in (pygame.K_UP, pygame.K_w):
menu_idx = (menu_idx - 1) % len(_MENU)
audio.play("menu")
elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
choice = _MENU[menu_idx]
if choice == "New Game":
session = new_game(seed=0)
camera.reset((session.player.x, session.player.y))
last_log_len = len(session.log)
ui = "howto"
elif choice == "Continue":
loaded = act.load_saved()
if loaded is not None:
session = loaded
session.state = "playing"
camera.reset((session.player.x, session.player.y))
last_log_len = len(session.log)
ui = "playing"
elif choice == "How to Play":
ui = "howto"
elif choice == "Quit":
running = False
elif k == pygame.K_ESCAPE:
running = False
elif ui == "howto":
if k == pygame.K_ESCAPE:
ui = "playing" if session is not None else "menu"
else:
ui = "playing" if session is not None else "menu"
elif ui == "playing" and session is not None:
if k == pygame.K_m:
audio.toggle_mute()
elif k == pygame.K_SLASH:
ui = "howto"
elif k == pygame.K_ESCAPE:
ui = "menu"
session = None
elif k == pygame.K_s:
before = len(session.log)
act.apply_input(session, "S")
_play_for_log(audio, session.log[before:])
elif k in _KEYMAP:
before = len(session.log)
act.apply_input(session, _KEYMAP[k])
_play_for_log(audio, session.log[before:])
elif ui in ("dead", "victory"):
ui = "menu"
session = None
# sync UI from session state
if session is not None and ui == "playing":
if session.state == "dead":
ui = "dead"
audio.play("death")
act.delete_save()
elif session.state == "victory":
ui = "victory"
audio.play("victory")
act.delete_save()
elif session.state == "saved":
ui = "menu"
session = None
# render
if ui == "menu":
_draw_menu(screen, menu_idx, act.load_saved() is not None, title_f, opt_f)
elif ui == "howto":
_draw_howto(screen, font_f, big_f)
else:
if session is not None:
camera.update((session.player.x, session.player.y))
offset = camera.offset_for((SCREEN_W, SCREEN_H), (session.player.x, session.player.y))
renderer.render(screen, session, camera_xy=offset)
if ui == "dead":
_draw_endcard(screen, session, "dead", big_f, font_f)
elif ui == "victory":
_draw_endcard(screen, session, "victory", big_f, font_f)
else:
ui = "menu"
_draw_menu(screen, menu_idx, False, title_f, opt_f)
pygame.display.flip()
if max_frames and frame >= max_frames:
running = False
frame += 1
clock.tick(60)
pygame.quit()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))