"""Pure renderer: composes the world + UI from a GameSession (never mutates it). Layout (module constants, derived from C.TILE): +---------------------------------------------+---- | TOP BAR floor | HP bar | level | XP bar | } SIDE panel +---------------------------------------------+ ) (log) | | ) | MAP VIEWPORT (camera follows player)| ) | | ) +---------------------------------------------+---- | BOTTOM BAR equipment | effects | sound | prompt| +---------------------------------------------+ """ from __future__ import annotations import math try: import pygame except Exception: # pragma: no cover pygame = None # type: ignore from data import constants as C from data import sprites as S from render import sprites as RS from render.camera import Camera from render.effects import ( FloatText, Particles, Shake, make_torch, make_vignette, torch_factor, ) TILE: int = C.TILE VIEW_TW: int = 48 VIEW_TH: int = 28 MAP_W_PX: int = VIEW_TW * TILE MAP_H_PX: int = VIEW_TH * TILE TOP_H: int = 34 BOT_H: int = 50 SIDE_W: int = 230 WIN_W: int = MAP_W_PX + SIDE_W WIN_H: int = TOP_H + MAP_H_PX + BOT_H MAP_X: int = 0 MAP_Y: int = TOP_H COL = C.COLORS WALL_V = COL["wall_visible"] WALL_E = COL["wall_explored"] FLOOR_V = COL["floor_visible"] FLOOR_E = COL["floor_explored"] VOID = COL["void"] def _shade(color, f: float): return (max(0, min(255, int(color[0] * f))), max(0, min(255, int(color[1] * f))), max(0, min(255, int(color[2] * f)))) def _hash(tx: int, ty: int) -> float: n = (tx * 73856093) ^ (ty * 19349663) n = (n ^ (n >> 13)) * 1274126177 & 0xFFFFFFFF n = (n ^ (n >> 16)) & 0xFFFFFFFF return n / 0xFFFFFFFF def _log_color(line: str): low = line.lower() if any(k in low for k in ("level", "defeated", "conquered", "slew")): return COL["log_levelup"] if any(k in low for k in ("you", "miss")) and "miss" in low and "you miss" in low: return COL["log_miss"] if any(k in low for k in ("hits you", "damage", "died", "burn", "critically", "shoots")): return COL["log_damage"] if any(k in low for k in ("pick up", "equip", "unequip", "quaff", "scroll", "potion", "teleport", "map", "surge", "fade")): return COL["log_item"] if "miss" in low: return COL["log_miss"] return COL["log_combat"] # armor sprite_key -> pauldron color cue shown on the player _ARMOR_TINT = { "armor_leather": COL["floor_visible"], "armor_chain": COL["armor"], "armor_plate": (210, 210, 220), } class Renderer: def __init__(self, size, audio) -> None: self.W, self.H = size self.audio = audio self.cam = Camera() self.particles = Particles() self.floats = FloatText() self.shake = Shake() self._dt = 0.0 self._cam_world = (0.0, 0.0) self._fx_cam = (0.0, 0.0) fname = "dejavusans,arial,helvetica,sans" self.font = pygame.font.SysFont(fname, 13) self.font_s = pygame.font.SysFont(fname, 11) self.font_b = pygame.font.SysFont(fname, 15, bold=True) self.font_l = pygame.font.SysFont(fname, 30, bold=True) self.font_xl = pygame.font.SysFont(fname, 46, bold=True) self.vignette = make_vignette(MAP_W_PX, MAP_H_PX) self.torch = make_torch(C.SIGHT_RADIUS * TILE) # ------------------------------------------------------------------ # def update(self, dt: float) -> None: self._dt = max(0.001, dt) self.particles.update(dt) self.floats.update(dt) def world_px(self, tx: int, ty: int): """Screen-pixel center of a world tile (for spawning effects).""" cx, cy = self._cam_world wx = tx * TILE + TILE / 2 wy = ty * TILE + TILE / 2 return (wx - cx + MAP_X, wy - cy + MAP_Y) # ------------------------------------------------------------------ # # World # ------------------------------------------------------------------ # def render_world(self, screen, session, t: float) -> None: floor = session.dungeon[session.current_floor] p = session.player map_pw = C.MAP_WIDTH * TILE map_ph = C.MAP_HEIGHT * TILE tgt_x = p.x * TILE + TILE / 2 - MAP_W_PX / 2 tgt_y = p.y * TILE + TILE / 2 - MAP_H_PX / 2 tgt_x = max(0.0, min(tgt_x, max(0.0, map_pw - MAP_W_PX))) tgt_y = max(0.0, min(tgt_y, max(0.0, map_ph - MAP_H_PX))) if self.cam.x == 0.0 and self.cam.y == 0.0: self.cam.snap(tgt_x, tgt_y) self.cam.set_target(tgt_x, tgt_y) self.cam.update(self._dt) self.shake.update(self._dt) sox, soy = self.shake.offset() cx, cy = self.cam.x, self.cam.y self._cam_world = (cx - sox, cy - soy) self._fx_cam = (cx - sox, cy - soy - MAP_Y) screen.fill(VOID) vis = floor.visible expl = floor.explored tx0 = max(0, int(cx // TILE) - 1) tx1 = min(C.MAP_WIDTH - 1, int((cx + MAP_W_PX) // TILE) + 1) ty0 = max(0, int(cy // TILE) - 1) ty1 = min(C.MAP_HEIGHT - 1, int((cy + MAP_H_PX) // TILE) + 1) px, py = p.x, p.y for ty in range(ty0, ty1 + 1): row_v = vis[ty] row_e = expl[ty] row_t = floor.tiles[ty] sy = round(ty * TILE - cy + soy) + MAP_Y for tx in range(tx0, tx1 + 1): if not row_e[tx] and not row_v[tx]: continue sx = round(tx * TILE - cx + sox) + MAP_X if row_v[tx]: light = torch_factor(math.hypot(tx - px, ty - py), C.SIGHT_RADIUS) if row_t[tx] == 0: self._wall(screen, sx, sy, tx, ty, light) else: self._floor(screen, sx, sy, tx, ty, light) else: col = WALL_E if row_t[tx] == 0 else FLOOR_E pygame.draw.rect(screen, col, (sx, sy, TILE, TILE)) if row_t[tx] == 0: pygame.draw.rect(screen, _shade(col, 0.7), (sx, sy + TILE - 3, TILE, 3)) if self.torch is not None: ts = self.torch.get_width() gx = round(px * TILE + TILE / 2 - (cx - sox)) + MAP_X - ts // 2 gy = round(py * TILE + TILE / 2 - (cy - soy)) + MAP_Y - ts // 2 screen.blit(self.torch, (gx, gy), special_flags=pygame.BLEND_RGB_ADD) self._draw_entities(screen, floor, p, cx - sox, cy - soy, t) if self.vignette is not None: screen.blit(self.vignette, (MAP_X, MAP_Y)) self.particles.draw(screen, self._fx_cam) self.floats.draw(screen, self.font_s, self.font_b, self._fx_cam) self._ui_top(screen, session) self._ui_log(screen, session) self._ui_bottom(screen, session) def _wall(self, surf, sx, sy, tx, ty, light) -> None: h = _hash(tx, ty) h2 = _hash(tx + 101, ty - 57) bevel = max(2, TILE // 7) # per-tile base shade so no two walls read identically pygame.draw.rect(surf, _shade(WALL_V, light * (0.82 + 0.36 * h)), (sx, sy, TILE, TILE)) pygame.draw.rect(surf, _shade(WALL_V, light * 1.45), (sx, sy, TILE, bevel)) # lit top bevel pygame.draw.rect(surf, _shade(WALL_V, light * 0.5), (sx, sy + TILE - bevel, TILE, bevel)) # shadow base # brick mortar: horizontal seam mid-wall + offset vertical seams per row mid = sy + TILE // 2 pygame.draw.rect(surf, _shade(WALL_V, light * 0.58), (sx, mid, TILE, 1)) v1 = int(h2 * (TILE // 2)) pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v1, sy + bevel, 1, mid - sy - bevel)) v2 = (int(h * (TILE // 2)) + TILE // 2) % (TILE - 1) pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v2, mid + 1, 1, sy + TILE - bevel - mid - 1)) # stable speckles (highlight + grit) for k in range(4): fx = sx + int((h * (97 + k * 53)) % (TILE - 1)) fy = sy + bevel + int((h2 * (31 + k * 29)) % (TILE - 2 * bevel)) f = 1.4 if ((h * (k + 2)) % 1) > 0.5 else 0.55 pygame.draw.rect(surf, _shade(WALL_V, light * f), (fx, fy, 1, 1)) def _floor(self, surf, sx, sy, tx, ty, light) -> None: h = _hash(tx, ty) pygame.draw.rect(surf, _shade(FLOOR_V, light * (0.86 + 0.28 * h)), (sx, sy, TILE, TILE)) # subtle checkerboard dither (stable per tile parity) if (tx + ty) & 1: pygame.draw.rect(surf, _shade(FLOOR_V, light * 1.16), (sx, sy, 2, 2)) pygame.draw.rect(surf, _shade(FLOOR_V, light * 0.8), (sx + TILE - 2, sy + TILE - 2, 2, 2)) # flecks / specular grit for k in range(5): fx = sx + int((h * (97 + k * 31)) % (TILE - 1)) fy = sy + int((h * (53 + k * 17)) % (TILE - 1)) f = 1.4 if ((h * (k + 1)) % 1) > 0.5 else 0.62 pygame.draw.rect(surf, _shade(FLOOR_V, light * f), (fx, fy, 1, 1)) def _draw_entities(self, surf, floor, player, cx, cy, t) -> None: from entities.enemy import Enemy from entities.item import Item vis = floor.visible # ground features first (remembered on explored tiles) ground = [e for e in floor.entities if isinstance(e, Item) or (not isinstance(e, Enemy) and getattr(e, "sprite_key", "") == "stairs")] for e in ground: if not (vis[e.y][e.x] or floor.explored[e.y][e.x]): continue self._blit_entity(surf, e, cx, cy, t, shadow=True) # actors: visible enemies + the player, sorted by y for overlap actors = [e for e in floor.entities if isinstance(e, Enemy) and e.hp > 0 and vis[e.y][e.x]] actors.append(player) actors.sort(key=lambda e: e.y) for e in actors: self._blit_entity(surf, e, cx, cy, t, shadow=True, is_actor=True) def _blit_entity(self, surf, e, cx, cy, t, shadow=False, is_actor=False) -> None: from entities.enemy import Enemy sx = round(e.x * TILE - cx) + MAP_X sy = round(e.y * TILE - cy) + MAP_Y if shadow: sh = pygame.Surface((TILE - 4, 5), pygame.SRCALPHA) pygame.draw.ellipse(sh, (0, 0, 0, 90), sh.get_rect()) surf.blit(sh, (sx + 2, sy + TILE - 5)) name = e.sprite_key if name == "player": name = "player_" + getattr(e, "facing", "down") if name not in S.SPRITES: name = "player_down" frame = int(t * 2.5 + (e.x * 7 + e.y * 13)) % max(1, RS.frame_count(name)) bob = -1 if (frame == 1 and is_actor) else 0 spr = RS.get(name, frame, TILE) if spr is not None: surf.blit(spr, (sx, sy + bob)) if isinstance(e, Enemy) and e.hp < e.max_hp: self._hp_pip(surf, sx, sy - 3, e.hp / max(1, e.max_hp)) if getattr(e, "sprite_key", "") == "player": self._player_gear(surf, e, sx, sy) def _hp_pip(self, surf, sx, sy, frac) -> None: w = TILE - 6 pygame.draw.rect(surf, (30, 12, 12), (sx + 3, sy, w, 3)) fw = max(0, int(w * frac)) col = (90, 200, 90) if frac > 0.5 else ((220, 180, 60) if frac > 0.25 else (210, 70, 60)) pygame.draw.rect(surf, col, (sx + 3, sy, fw, 3)) def _player_gear(self, surf, player, sx, sy) -> None: # held weapon icon at the lower-right wpn = player.equipped.get("weapon") if wpn is not None: ico = RS.get(wpn.sprite_key, 0, TILE // 2 + 2) if ico is not None: surf.blit(ico, (sx + TILE - 8, sy + 6)) # armor pauldron tint on the shoulders arm = player.equipped.get("armor") if arm is not None: tint = _ARMOR_TINT.get(arm.sprite_key, (180, 180, 180)) pygame.draw.rect(surf, tint, (sx + 3, sy + int(TILE * 0.30), 3, 4)) pygame.draw.rect(surf, tint, (sx + TILE - 6, sy + int(TILE * 0.30), 3, 4)) # ------------------------------------------------------------------ # # UI # ------------------------------------------------------------------ # def _panel(self, surf, rect, fill=None) -> None: fill = fill or COL["ui_panel"] pygame.draw.rect(surf, fill, rect) pygame.draw.rect(surf, COL["ui_border"], rect, 1) pygame.draw.line(surf, COL["ui_border_hi"], (rect[0] + 1, rect[1] + 1), (rect[0] + rect[2] - 2, rect[1] + 1)) # top bevel def _text(self, surf, s, pos, font=None, color=None) -> None: color = color or COL["log_combat"] surf.blit((font or self.font).render(s, True, color), pos) def _bar(self, surf, rect, frac, full, back, icon=None) -> None: x, y, w, h = rect pygame.draw.rect(surf, back, (x, y, w, h)) fw = max(0, int(w * max(0.0, min(1.0, frac)))) if fw: pygame.draw.rect(surf, full, (x, y, fw, h)) pygame.draw.rect(surf, COL["ui_border"], (x, y, w, h), 1) if icon is not None: surf.blit(icon, (x - 2, y - 2)) def _heart(self, size=12): s = pygame.Surface((size, size), pygame.SRCALPHA) col = (200, 60, 65) r = size // 4 pygame.draw.circle(s, col, (size // 2 - r, size // 3), r) pygame.draw.circle(s, col, (size // 2 + r, size // 3), r) pygame.draw.polygon(s, col, [(0, size // 3 + 1), (size, size // 3 + 1), (size // 2, size - 1)]) return s def _ui_top(self, surf, session) -> None: p = session.player self._panel(surf, (0, 0, WIN_W, TOP_H), COL["ui_bg"]) self._text(surf, f"Floor {session.current_floor + 1}/{C.FLOORS}", (8, 9), self.font_b, COL["prompt"]) # HP bar hx = 150 self._bar(surf, (hx, 10, 240, 14), p.hp / max(1, p.max_hp), COL["hp_full"], COL["hp_back"], icon=self._heart()) self._text(surf, f"{p.hp}/{p.max_hp}", (hx + 246, 9), self.font_s) # Level + XP self._text(surf, f"Lv {p.level}", (hx + 320, 9), self.font_b, COL["prompt"]) xp_next = C.XP_THRESHOLDS.get(min(p.level + 1, C.MAX_LEVEL), p.xp) xp_cur = C.XP_THRESHOLDS.get(p.level, 0) frac = (p.xp - xp_cur) / max(1, xp_next - xp_cur) if xp_next > xp_cur else 1.0 self._bar(surf, (WIN_W - SIDE_W - 150, 10, 130, 14), frac, COL["xp_full"], COL["xp_back"]) self._text(surf, "XP", (WIN_W - SIDE_W - 172, 9), self.font_s, COL["xp_full"]) def _ui_log(self, surf, session) -> None: x = MAP_W_PX y = TOP_H self._panel(surf, (x, y, SIDE_W, MAP_H_PX), COL["ui_bg"]) self._text(surf, "Messages", (x + 8, y + 6), self.font_b, COL["prompt"]) pygame.draw.line(surf, COL["ui_border"], (x + 4, y + 24), (x + SIDE_W - 4, y + 24)) lines = session.log[-9:] ly = y + MAP_H_PX - 12 for line in reversed(lines): txt = self._crop(line, _log_color(line), SIDE_W - 16) surf.blit(txt, (x + 8, ly - txt.get_height())) ly -= txt.get_height() + 1 def _crop(self, text, color, maxw): full = self.font_s.render(text, True, color) if full.get_width() <= maxw: return full keep = max(3, int(len(text) * maxw / full.get_width()) - 1) return self.font_s.render(text[:keep] + "...", True, color) def _ui_bottom(self, surf, session) -> None: p = session.player y = WIN_H - BOT_H self._panel(surf, (0, y, WIN_W, BOT_H), COL["ui_bg"]) # equipment slots self._text(surf, "WPN", (8, y + 6), self.font_s, COL["weapon"]) wpn = p.equipped.get("weapon") self._slot(surf, 8, y + 20, wpn) self._text(surf, "ARM", (42, y + 6), self.font_s, COL["armor"]) self._slot(surf, 42, y + 20, p.equipped.get("armor")) # active effect timers ex = 90 self._text(surf, "Effects", (ex, y + 6), self.font_s, COL["prompt"]) if p.effects: tx = ex for eff in p.effects: label = ("STR" if eff.kind == "strength" else "INV") col = COL["weapon"] if eff.kind == "strength" else COL["wraith"] self._text(surf, f"{label} {eff.duration}", (tx, y + 22), self.font_s, col) tx += 52 else: self._text(surf, "-", (ex, y + 22), self.font_s, (90, 90, 100)) # sound icon self._text(surf, "[m] sound " + ("OFF" if self.audio.muted else "ON"), (WIN_W - SIDE_W - 110, y + 22), self.font_s, (120, 120, 130) if self.audio.muted else COL["log_levelup"]) # context prompt prompt = self._context(session) if prompt: self._text(surf, prompt, (8, y + BOT_H - 16), self.font_b, COL["prompt"]) def _slot(self, surf, x, y, item) -> None: rect = (x, y, 28, 22) pygame.draw.rect(surf, COL["ui_panel"], rect) pygame.draw.rect(surf, COL["ui_border"], rect, 1) if item is not None: ico = RS.get(item.sprite_key, 0, 20) if ico is not None: surf.blit(ico, (x + 4, y + 1)) def _context(self, session) -> str: from entities.item import Item p = session.player floor = session.dungeon[session.current_floor] for e in floor.entities: if isinstance(e, Item) and e.x == p.x and e.y == p.y: return f"Press G to pick up {e.name}" if (p.x, p.y) == floor.stairs_down and session.current_floor < C.FLOORS - 1: return "Press F to descend" return "" # ------------------------------------------------------------------ # # Screens # ------------------------------------------------------------------ # def render_menu(self, screen, index, has_save, t) -> None: screen.fill(VOID) bob = math.sin(t * 2.0) * 4 self._text(screen, "UNDERDEPTHS", (WIN_W // 2 - 150, 90 + bob), self.font_xl, COL["prompt"]) self._text(screen, "A turn-based roguelike descent", (WIN_W // 2 - 110, 150 + bob), self.font, (150, 140, 120)) dragon = RS.get("ancient_dragon", int(t * 2.5) % 2, 96) if dragon is not None: screen.blit(dragon, (WIN_W // 2 - 48, 190)) options = ["New Game"] if has_save: options.append("Continue") options += ["How to Play", "Quit"] oy = 320 for i, opt in enumerate(options): sel = (i == index) col = COL["highlight"] if sel else (170, 160, 150) prefix = "> " if sel else " " self._text(screen, prefix + opt, (WIN_W // 2 - 90, oy + i * 30), self.font_b, col) self._text(screen, "arrows/hjkl select - enter confirm", (WIN_W // 2 - 130, WIN_H - 40), self.font_s, (110, 105, 100)) _HELP_LINES = [ ("HOW TO PLAY", COL["prompt"], True), ("", None, False), ("Move / attack: Arrows or H J K L (walk into an enemy to hit)", COL["log_combat"], False), ("Pick up item: stand on it, press G", COL["log_item"], False), ("Descend: stand on the yellow > stairs, press F", COL["prompt"], False), ("Inventory: I Equipment: E", COL["log_combat"], False), ("Quaff potion: Q Read scroll: R", COL["log_combat"], False), ("Save & quit: S Help: ? Mute: M Cancel: Esc", COL["log_combat"], False), ("", None, False), ("Slay the Ancient Dragon on floor 10 to win. Permadeath: die and the", (170, 160, 150), False), ("run ends. Explore, loot, level up, and descend.", (170, 160, 150), False), ("", None, False), ("Press any key to return.", COL["prompt"], False), ] def render_help(self, screen, t) -> None: screen.fill(VOID) self._panel(screen, (WIN_W // 2 - 290, 70, 580, 460), COL["ui_bg"]) y = 96 for line, col, big in self._HELP_LINES: self._text(screen, line, (WIN_W // 2 - 270, y), self.font_l if big else self.font, col or COL["log_combat"]) y += 40 if big else 26 def render_end(self, screen, session, kind, t) -> None: screen.fill(VOID) p = session.player if kind == "victory": self._text(screen, "VICTORY", (WIN_W // 2 - 130, 150), self.font_xl, COL["log_levelup"]) self._text(screen, "You slew the Ancient Dragon!", (WIN_W // 2 - 150, 230), self.font_b, COL["prompt"]) self._text(screen, "You conquered Underdepths.", (WIN_W // 2 - 130, 260), self.font_b, COL["prompt"]) else: self._text(screen, "YOU DIED", (WIN_W // 2 - 120, 150), self.font_xl, COL["hp_full"]) self._text(screen, f"You died on floor {session.current_floor + 1}.", (WIN_W // 2 - 130, 230), self.font_b, COL["log_combat"]) self._text(screen, f"You reached level {p.level}.", (WIN_W // 2 - 110, 290), self.font_b, COL["log_levelup"]) self._text(screen, "Press any key to return to the menu.", (WIN_W // 2 - 150, WIN_H - 90), self.font, (150, 140, 120)) def render_inventory(self, screen, session, mode, t) -> None: p = session.player # main.py passes overlay modes 'inv' | 'equip' | 'quaff' | 'read' title = {"inv": "Inventory", "equip": "Equipment", "quaff": "Quaff a Potion", "read": "Read a Scroll"}.get(mode, "Inventory") def wanted(it): if mode == "quaff": return it.item_type == "potion" if mode == "read": return it.item_type == "scroll" return True items = [it for it in p.inventory if wanted(it)] pw, ph = WIN_W - 160, WIN_H - 160 px, py = 80, 80 self._panel(screen, (px, py, pw, ph), COL["ui_bg"]) self._text(screen, title, (px + 16, py + 12), self.font_l, COL["prompt"]) if mode == "equip": self._text(screen, f"Weapon: {_name(p.equipped.get('weapon'))}", (px + 16, py + 60), self.font, COL["weapon"]) self._text(screen, f"Armor: {_name(p.equipped.get('armor'))}", (px + 16, py + 82), self.font, COL["armor"]) self._text(screen, "Equip from inventory (I).", (px + 16, py + 110), self.font_s, (150, 140, 120)) ly = py + 64 if mode != "equip" else py + 150 if mode != "equip" and not items: self._text(screen, "(empty)", (px + 16, ly), self.font, (130, 125, 120)) for i, it in enumerate(items): letter = chr(ord("a") + i) if i < 26 else str(i) ico = RS.get(it.sprite_key, 0, 20) row_y = ly + i * 26 if ico is not None: screen.blit(ico, (px + 16, row_y - 2)) kind = it.item_type.capitalize() self._text(screen, f"[{letter}] {it.name}", (px + 42, row_y), self.font, COL["log_item"]) self._text(screen, kind, (px + pw - 130, row_y), self.font_s, (150, 140, 120)) hint = "press a letter to use/equip - Esc closes" if mode != "equip" else "Esc closes" self._text(screen, hint, (px + 16, py + ph - 28), self.font_s, (130, 125, 120)) def _name(item) -> str: return item.name if item is not None else "(none)"