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

507 lines
23 KiB
Python

"""Pure renderer: composes map tiles, entities, lighting, juice, and UI.
Reads ``GameSession`` and draws — never mutates game state. Visibility for
lighting is DERIVED here via FOV (read-only) so a freshly-built session renders
correctly even before the action layer has ticked. Stairs are ALWAYS blitted on
``stairs_down`` when in view/remembered (invisible stairs make the game
unwinnable).
"""
from __future__ import annotations
from typing import Any
import math
import pygame
from data.constants import (
TILE, SIGHT_RADIUS, COLORS, MAP_W, MAP_H,
)
from engine.fov import compute_fov
from render.sprites import get_tile_sprite
from render.effects import Particles, Shake, vignette, torch_factor
_BG = COLORS["bg"]
_FONT_STACK = "monospace,consolas,couriernew,dejavusans"
# Sprites rendered larger than one tile (centered on their tile).
_BIG_SPRITES = frozenset({"ancient_dragon"})
def _dim(color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
return (int(color[0] * factor), int(color[1] * factor), int(color[2] * factor))
def _hash2(x: int, y: int) -> int:
return (x * 73856093 ^ y * 19349663) & 0xFF
class Renderer:
def __init__(self) -> None:
self.particles = Particles()
self.shake = Shake()
self._anim = 0.0
self._last_hp: int | None = None
self._last_log_len = 0
self._font_big: pygame.font.Font | None = None
self._font_small: pygame.font.Font | None = None
self._font: pygame.font.Font | None = None
self._fonts_ok = True
self._torch: pygame.Surface | None = None
self._glow_surf: pygame.Surface | None = None
self._shadow_cache: dict[int, pygame.Surface] = {}
# --------------------------------------------------------------- fonts
def _fonts(self) -> None:
if not self._fonts_ok or self._font is not None:
return
try:
self._font = pygame.font.SysFont(_FONT_STACK, 16, bold=True)
self._font_big = pygame.font.SysFont(_FONT_STACK, 22, bold=True)
self._font_small = pygame.font.SysFont(_FONT_STACK, 13, bold=True)
except Exception:
self._fonts_ok = False
def _text(self, surf: pygame.Surface, msg: str, pos: tuple[int, int],
color: tuple[int, int, int], big: bool = False,
small: bool = False) -> None:
if self._font is None:
return
f = self._font_big if big else (self._font_small if small else self._font)
try:
img = f.render(msg, True, color)
surf.blit(img, pos)
except Exception:
pass
# --------------------------------------------------------------- entry
def render(self, surface: pygame.Surface, session: Any,
camera_xy: tuple[int, int] = (0, 0)) -> None:
self._fonts()
self._anim += 0.016
self.particles.update(0.016)
gm = session.dungeon[session.current_floor]
player = session.player
vis = compute_fov(gm, (player.x, player.y), SIGHT_RADIUS)
cam_x, cam_y = camera_xy
sh_x, sh_y = self.shake.offset()
ox, oy = cam_x - sh_x, cam_y - sh_y
sw, sh = surface.get_size()
surface.fill(_BG)
x0 = max(0, ox // TILE)
y0 = max(0, oy // TILE)
x1 = min(gm.width, (ox + sw) // TILE + 1)
y1 = min(gm.height, (oy + sh) // TILE + 1)
# Visible terrain/entities are drawn to a light layer at FULL brightness,
# then a smooth radial torch gradient is multiplied in. That gives a soft
# circular falloff with no tile-sized banding. Explored-but-unseen tiles
# are drawn dim (cool blue-gray) straight onto the surface; unexplored
# stays black. Walls occlude because only FOV-visible tiles reach the
# light layer.
light = pygame.Surface((sw, sh), pygame.SRCALPHA)
# ---- terrain ----
for ty in range(y0, y1):
for tx in range(x0, x1):
px, py = tx * TILE - ox, ty * TILE - oy
visible = (tx, ty) in vis
explored = gm.explored[ty][tx]
if not (visible or explored):
continue
is_wall = not gm.walkable(tx, ty)
if visible:
if is_wall:
self._wall(light, px, py, tx, ty, 1.0)
else:
self._floor(light, px, py, tx, ty, 1.0)
else:
if is_wall:
self._wall_explored(surface, px, py, tx, ty)
else:
self._floor_explored(surface, px, py, tx, ty)
if (tx, ty) == gm.stairs_down:
target = light if visible else surface
gsh = self._shadow_surf(TILE)
target.blit(gsh, (px + (TILE - gsh.get_width()) // 2,
py + TILE - gsh.get_height()))
target.blit(get_tile_sprite("stairs"), (px, py))
# ---- entities (items under, enemies over, player on top) ----
for e in gm.entities:
if self._is_item(e):
if (e.x, e.y) in vis:
self._draw_entity(light, e, ox, oy, shadow=True)
elif gm.explored[e.y][e.x]:
self._draw_entity(surface, e, ox, oy, shadow=True)
for e in gm.entities:
if self._is_enemy(e) and (e.x, e.y) in vis:
self._draw_entity(light, e, ox, oy, shadow=True)
# player is always on-screen
self._draw_entity(light, player, ox, oy, shadow=True, is_player=True)
# keep the descent discoverable: when a sprite stands on the stairs, draw
# a translucent yellow '>' peek on top so the staircase is never hidden.
if gm.stairs_down is not None:
ssx, ssy = gm.stairs_down
on_stairs = (player.x, player.y) == (ssx, ssy) or any(
getattr(e, "x", -9) == ssx and getattr(e, "y", -9) == ssy for e in gm.entities)
if on_stairs and (ssx, ssy) in vis:
_peek = get_tile_sprite("stairs").copy()
_peek.set_alpha(150)
light.blit(_peek, (ssx * TILE - ox, ssy * TILE - oy))
# smooth radial torch: multiply the light layer by a cached gradient mask
mask = self._torch_mask()
pcx = player.x * TILE - ox + TILE // 2
pcy = player.y * TILE - oy + TILE // 2
light.blit(mask, (pcx - mask.get_width() // 2, pcy - mask.get_height() // 2),
special_flags=pygame.BLEND_RGB_MULT)
surface.blit(light, (0, 0))
# warm torch glow at the bearer's feet -> clear bright core
glow = self._glow()
surface.blit(glow, (pcx - glow.get_width() // 2, pcy - glow.get_height() // 2),
special_flags=pygame.BLEND_RGB_ADD)
self.particles.draw(surface, (ox, oy))
self._sense_events(session, vis, ox, oy)
surface.blit(vignette((sw, sh)), (0, 0))
self._ui(surface, session, sw, sh)
# --------------------------------------------------------------- tiles
def _floor(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
f: float) -> None:
base = _dim(COLORS["floor_visible"], f)
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
h = _hash2(tx, ty)
fleck = _dim(COLORS["floor_explored"], f)
# two deterministic flecks per tile for subtle texture
fx = px + (h % (TILE - 4)) + 2
fy = py + ((h >> 3) % (TILE - 4)) + 2
pygame.draw.rect(surf, fleck, (fx, fy, 2, 2))
fx2 = px + ((h >> 2) % (TILE - 4)) + 2
fy2 = py + ((h >> 5) % (TILE - 4)) + 2
pygame.draw.rect(surf, _dim(COLORS["floor_visible"], f * 1.15), (fx2, fy2, 2, 2))
def _wall(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
f: float = 1.0) -> None:
pygame.draw.rect(surf, _dim(COLORS["wall_visible"], f), (px, py, TILE, TILE))
pygame.draw.rect(surf, _dim(COLORS["wall_top"], f), (px, py, TILE, 4)) # lit top edge
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py + TILE - 4, TILE, 4)) # shaded base
# brick seams via per-tile hash
h = _hash2(tx, ty)
seam = COLORS["wall_explored"]
if h & 1:
pygame.draw.rect(surf, seam, (px + TILE // 2, py + 4, 1, TILE - 8))
if h & 2:
pygame.draw.rect(surf, seam, (px + 4, py + TILE // 2, TILE - 8, 1))
def _floor_explored(self, surf: pygame.Surface, px: int, py: int,
tx: int, ty: int) -> None:
base = COLORS["floor_explored"]
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
h = _hash2(tx, ty)
pygame.draw.rect(surf, _dim(base, 0.7),
(px + (h % (TILE - 4)) + 2, py + ((h >> 3) % (TILE - 4)) + 2, 2, 2))
pygame.draw.rect(surf, _dim(base, 1.3),
(px + ((h >> 2) % (TILE - 4)) + 2, py + ((h >> 5) % (TILE - 4)) + 2, 2, 2))
def _wall_explored(self, surf: pygame.Surface, px: int, py: int,
tx: int, ty: int) -> None:
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py, TILE, TILE))
pygame.draw.rect(surf, _dim(COLORS["wall_explored"], 1.35), (px, py, TILE, 3)) # faint top edge
def _torch_mask(self) -> pygame.Surface:
"""Cached smooth radial brightness mask (white core -> gray rim).
Built tiny then smooth-scaled so the falloff is bilinear-smooth with no
tile-sized bands. Multiplied (BLEND_RGB_MULT) onto the light layer.
"""
if self._torch is not None:
return self._torch
diam = (SIGHT_RADIUS * TILE + TILE) * 2 # covers the whole FOV disc + rim
s = 64
small = pygame.Surface((s, s), pygame.SRCALPHA)
c = (s - 1) / 2
for yy in range(s):
for xx in range(s):
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
b = 0.45 + 0.55 * (1.0 - t) ** 1.5 # 1.0 core -> ~0.45 rim
g = int(b * 255)
small.set_at((xx, yy), (g, g, g, 255))
self._torch = pygame.transform.smoothscale(small, (diam, diam))
return self._torch
def _glow(self) -> pygame.Surface:
"""Cached warm radial glow added (BLEND_RGB_ADD) at the torch core so the
bright center reads clearly against the dimmer rim."""
if self._glow_surf is not None:
return self._glow_surf
diam = SIGHT_RADIUS * TILE * 2
s = 48
small = pygame.Surface((s, s), pygame.SRCALPHA)
c = (s - 1) / 2
for yy in range(s):
for xx in range(s):
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
a = int(78 * (1.0 - t) ** 2.2) # warm add, concentrated at center
small.set_at((xx, yy), (a, int(a * 0.85), int(a * 0.4), 255))
self._glow_surf = pygame.transform.smoothscale(small, (diam, diam))
return self._glow_surf
def _shadow_surf(self, size: int) -> pygame.Surface:
"""Cached soft elliptical ground shadow (~90% tile wide) drawn under an
entity/stairs so sprites read as grounded. Built from concentric ellipses
with rising alpha toward the center for a feathered edge."""
s = self._shadow_cache.get(size)
if s is not None:
return s
w = max(10, int(size * 0.92))
h = max(5, int(size * 0.32))
surf = pygame.Surface((w, h), pygame.SRCALPHA)
for frac, alpha in ((1.0, 95), (0.78, 150), (0.52, 215)):
rw = max(2, int(w * frac))
rh = max(2, int(h * frac))
rect = pygame.Rect((w - rw) // 2, (h - rh) // 2, rw, rh)
pygame.draw.ellipse(surf, (0, 0, 0, alpha), rect)
self._shadow_cache[size] = surf
return surf
# --------------------------------------------------------------- entities
def _draw_entity(self, surf: pygame.Surface, e: Any, ox: int, oy: int,
shadow: bool, is_player: bool = False) -> None:
key = self._sprite_key(e)
px = e.x * TILE - ox
py = e.y * TILE - oy
scale = 2 if key in _BIG_SPRITES else 1
size = TILE * scale
# big sprites (the dragon boss) center on the entity tile as a 2x2
spx = px - TILE // 2 if scale > 1 else px
spy = py - TILE // 2 if scale > 1 else py
bob = 0 if is_player else int((1 if scale > 1 else 2) *
(0.5 + 0.5 * math.sin(self._anim * 3 + e.x)))
if shadow:
sh = self._shadow_surf(size)
surf.blit(sh, (spx + (size - sh.get_width()) // 2,
spy + size - sh.get_height() - (0 if scale > 1 else 1)))
sprite = get_tile_sprite(key, size)
surf.blit(sprite, (spx, spy - bob))
if is_player and getattr(e, "effect_timers", {}).get("invisibility", 0) > 0:
veil = pygame.Surface((size, size), pygame.SRCALPHA)
veil.fill((90, 140, 220, 90))
surf.blit(veil, (spx, spy - bob))
# HP pip for hurt enemies
if self._is_enemy(e) and 0 < e.hp < e.max_hp:
frac = max(0.0, e.hp / e.max_hp)
bw = size - 4
pygame.draw.rect(surf, (40, 20, 20), (spx + 2, spy - 6, bw, 3))
pygame.draw.rect(surf, COLORS["hp_full"], (spx + 2, spy - 6, int(bw * frac), 3))
@staticmethod
def _sprite_key(e: Any) -> str:
key = getattr(e, "sprite_key", "") or ""
if key:
return key
if getattr(e, "behavior", ""): # enemy without sprite_key
return getattr(e, "kind", "goblin") or "goblin"
return "player"
@staticmethod
def _is_enemy(e: Any) -> bool:
return bool(getattr(e, "behavior", "")) and getattr(e, "hp", 1) > 0
@staticmethod
def _is_item(e: Any) -> bool:
return getattr(e, "category", "") != "" and not getattr(e, "behavior", "")
# --------------------------------------------------------------- juice sense
def _sense_events(self, session: Any, vis: set, ox: int, oy: int) -> None:
p = session.player
cx = p.x * TILE - ox + TILE // 2
cy = p.y * TILE - oy + TILE // 2
# player took damage since last frame
hp = getattr(p, "hp", None)
if self._last_hp is not None and hp is not None and hp < self._last_hp:
self.shake.trigger(6.0)
self.particles.burst(cx, cy, COLORS["hp_empty"], count=10, speed=80)
if hp <= 0:
self.particles.burst(cx, cy, (220, 220, 220), count=22, speed=120, life=0.7)
self._last_hp = hp
# new log lines -> spawn flavor at the player
new_lines = session.log[self._last_log_len:]
self._last_log_len = len(session.log)
for line in new_lines:
low = line.lower()
if "critical" in low:
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=110)
elif "you hit" in low:
self.particles.burst(cx, cy, COLORS["player"], count=5, speed=70) # hit sparks
elif "defeated" in low or "slew" in low:
self.particles.burst(cx, cy, COLORS["hp_empty"], count=16, speed=100, life=0.6)
elif "reach level" in low:
self.particles.burst(cx, cy, COLORS["xp_bar"], count=18, speed=90, life=0.8)
elif "pick up" in low or "pickup" in low:
self.particles.burst(cx, cy, COLORS["stairs"], count=10, speed=60)
elif "descend" in low:
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=70)
# --------------------------------------------------------------- UI
def _ui(self, surf: pygame.Surface, session: Any, sw: int, sh: int) -> None:
p = session.player
# ---- top bar ----
self._panel(surf, (0, 0, sw, 28))
floor_n = session.current_floor + 1
self._text(surf, f"Floor {floor_n}/10", (6, 6), COLORS["text"])
# HP: pixel-art heart icon + red track / green fill
hx, hy, hw = 156, 8, 140
self._heart(surf, 134, 6)
pygame.draw.rect(surf, COLORS["hp_empty"], (hx, hy, hw, 12))
frac = max(0.0, p.hp / max(1, p.max_hp))
pygame.draw.rect(surf, COLORS["hp_full"], (hx, hy, int(hw * frac), 12))
pygame.draw.rect(surf, COLORS["panel_border"], (hx, hy, hw, 12), 1)
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + hw + 5, 6), COLORS["text"])
# Level/XP: star icon + Lv + XP bar (right side)
star_x = sw - 252
self._star(surf, star_x, 6)
self._text(surf, f"Lv {p.level}", (star_x + 16, 6), COLORS["text"])
xx, xw = sw - 170, 112
pygame.draw.rect(surf, (30, 30, 40), (xx, 10, xw, 8))
lvl = min(max(1, p.level), 9)
need = [30, 70, 140, 250, 400, 600, 850, 1150, 1500][lvl - 1]
prev = [0, 30, 70, 140, 250, 400, 600, 850, 1150][lvl - 1]
xpfrac = max(0.0, min(1.0, (p.xp - prev) / max(1, need - prev)))
pygame.draw.rect(surf, COLORS["xp_bar"], (xx, 10, int(xw * xpfrac), 8))
pygame.draw.rect(surf, COLORS["panel_border"], (xx, 10, xw, 8), 1)
# ---- right log panel: full-height side panel, color-coded, no clipping ----
panel_x, panel_w, line_h = sw - 262, 258, 14
panel_top, panel_bottom = 34, sh - 34
self._panel(surf, (panel_x, panel_top, panel_w, panel_bottom - panel_top))
self._text(surf, "Messages", (panel_x + 6, panel_top + 4), COLORS["text_dim"], small=True)
text_x, max_w = panel_x + 6, panel_w - 12
# newest at the bottom; word-wrap long lines so nothing is cut off
shown = session.log[-8:]
wrapped: list[tuple[str, tuple[int, int, int]]] = []
for line in shown:
wrapped.extend((w, self._log_color(line)) for w in self._wrap(line, max_w))
y = panel_bottom - 6 - line_h * len(wrapped)
for msg, col in wrapped:
if y >= panel_top + 20:
self._text(surf, msg, (text_x, y), col, small=True)
y += line_h
# ---- bottom equipment bar: icon slots, not bare text ----
self._panel(surf, (0, sh - 30, sw, 30))
slot_y = sh - 27
nx = self._equip_slot(surf, 6, slot_y, p.equipped_weapon)
nx = self._equip_slot(surf, nx + 8, slot_y, p.equipped_armor)
self._text(surf, f"Pack: {len(p.inventory)}", (nx + 10, sh - 22), COLORS["text_dim"])
eff = ", ".join(f"{k}:{v}" for k, v in p.effect_timers.items())
if eff:
self._text(surf, f"[{eff}]", (sw // 2 - 40, sh - 22), COLORS["xp_bar"])
# ---- styled context prompt ----
prompt = self._context_prompt(session)
if prompt:
pw = self._font.size(prompt)[0] if self._font else 130
pill = pygame.Surface((pw + 16, 19), pygame.SRCALPHA)
pygame.draw.rect(pill, (18, 16, 22, 215), pill.get_rect(), border_radius=4)
pygame.draw.rect(pill, (*COLORS["stairs"], 190), pill.get_rect(), 1, border_radius=4)
surf.blit(pill, (4, sh - 53))
self._text(surf, prompt, (12, sh - 50), COLORS["stairs"])
# --------------------------------------------------------------- UI helpers
@staticmethod
def _log_color(line: str) -> tuple[int, int, int]:
low = line.lower()
if any(w in low for w in ("slain", "died", "wound", "damage to you", "fizzle")):
return COLORS["log_bad"] # damage-taken / death -> red
if any(w in low for w in ("reach level", "defeated", "slew", "level up")):
return COLORS["log_good"] # level-up / kill -> green
if any(w in low for w in ("pick up", "pickup", "descend", "quaff",
"you read", "equip", "stairs", "reveals")):
return COLORS["stairs"] # items / stairs -> yellow
return COLORS["text"] # combat / hit / miss / crit -> white
def _fit_text(self, text: str, max_w: int, small: bool = False) -> str:
f = self._font_small if small else self._font
if f is None or f.size(text)[0] <= max_w:
return text
ell = "…"
while text and f.size(text + ell)[0] > max_w:
text = text[:-1]
return (text + ell) if text else ""
def _wrap(self, text: str, max_w: int) -> list[str]:
"""Word-wrap text to <= max_w px per line (greedy). Returns >=1 line."""
f = self._font_small
if f is None:
return [text]
words = text.split()
lines: list[str] = []
cur = ""
for w in words:
trial = w if not cur else cur + " " + w
if f.size(trial)[0] <= max_w or not cur:
cur = trial
else:
lines.append(cur)
cur = w
if cur:
lines.append(cur)
return lines or [""]
@staticmethod
def _heart(surf: pygame.Surface, x: int, y: int) -> None:
c = COLORS["heart"]
pygame.draw.circle(surf, c, (x + 4, y + 4), 4)
pygame.draw.circle(surf, c, (x + 10, y + 4), 4)
pygame.draw.polygon(surf, c, [(x, y + 5), (x + 14, y + 5), (x + 7, y + 13)])
surf.set_at((x + 7, y + 2), (90, 16, 20)) # top cleft
surf.set_at((x + 3, y + 3), (255, 160, 170)) # highlight
@staticmethod
def _star(surf: pygame.Surface, x: int, y: int) -> None:
cx, cy = x + 7, y + 7
pts = []
for i in range(10):
ang = -math.pi / 2 + i * math.pi / 5
rr = 7 if i % 2 == 0 else 3
pts.append((cx + rr * math.cos(ang), cy + rr * math.sin(ang)))
pygame.draw.polygon(surf, COLORS["star"], pts)
pygame.draw.polygon(surf, (120, 80, 20), pts, 1)
def _equip_slot(self, surf: pygame.Surface, x: int, y: int,
item: Any) -> int:
box = 24
pygame.draw.rect(surf, COLORS["panel"], (x, y, box, box))
pygame.draw.rect(surf, COLORS["panel_border"], (x, y, box, box), 1)
if item is not None:
kind = getattr(item, "kind", "") or getattr(item, "sprite_key", "")
surf.blit(get_tile_sprite(kind, 20), (x + 2, y + 2))
name = self._fit_text(item.name, 124)
self._text(surf, name, (x + box + 3, y + 6), COLORS["text"])
return x + box + 130
self._text(surf, "—", (x + 9, y + 5), COLORS["text_dim"])
self._text(surf, "empty", (x + box + 3, y + 6), COLORS["text_dim"])
return x + box + 52
def _context_prompt(self, session: Any) -> str:
p = session.player
gm = session.dungeon[session.current_floor]
item = next((e for e in gm.entities
if self._is_item(e) and e.x == p.x and e.y == p.y), None)
if item is not None:
return f"Press G to pick up {item.name}"
if gm.stairs_down == (p.x, p.y):
return "Press F to descend"
return ""
def _panel(self, surf: pygame.Surface, rect: tuple[int, int, int, int]) -> None:
pygame.draw.rect(surf, COLORS["panel"], rect)
pygame.draw.rect(surf, COLORS["panel_border"], rect, 1)