403 lines
17 KiB
Python
403 lines
17 KiB
Python
"""Drawing: map viewport, entities and UI panels.
|
|
|
|
Pure rendering — the renderer only ever reads from :class:`GameSession`. The
|
|
window is divided into:
|
|
* a top status bar (floor, HP bar, level, XP bar),
|
|
* a 50x30 camera-followed map viewport of 16x16 tiles,
|
|
* a right-hand colour-coded message log,
|
|
* a bottom bar (equipment + sound state) plus a context prompt.
|
|
|
|
It is headless-safe: it draws onto whatever surface ``main`` supplies, so it
|
|
runs identically under ``SDL_VIDEODRIVER=dummy``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from data.constants import COLORS, LEVEL_XP, TILE_FLOOR, TILE_WALL
|
|
from entities.enemy import Enemy
|
|
from entities.item import Item
|
|
from render.camera import Camera, compute_camera
|
|
|
|
__all__ = ["Renderer", "Layout", "TILE", "VIEW_W", "VIEW_H"]
|
|
|
|
TILE = 16
|
|
VIEW_W = 50 # viewport width in tiles
|
|
VIEW_H = 30 # viewport height in tiles
|
|
|
|
MAP_PIX_W = VIEW_W * TILE # 800
|
|
MAP_PIX_H = VIEW_H * TILE # 480
|
|
PANEL_W = 360
|
|
TOP_H = 44
|
|
BOT_H = 96
|
|
SCREEN_W = MAP_PIX_W + PANEL_W # 1160
|
|
SCREEN_H = TOP_H + MAP_PIX_H + BOT_H # 620
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class Layout:
|
|
screen_w: int = SCREEN_W
|
|
screen_h: int = SCREEN_H
|
|
|
|
|
|
class Renderer:
|
|
"""Caches fonts and draws a full frame from a session."""
|
|
|
|
def __init__(self) -> None:
|
|
import pygame
|
|
self._pygame = pygame
|
|
self._font_big = pygame.font.SysFont(None, 30)
|
|
self._font = pygame.font.SysFont(None, 22)
|
|
self._font_sm = pygame.font.SysFont(None, 18)
|
|
|
|
# -- entry point ---------------------------------------------------------
|
|
def draw(self, screen, session, audio=None, overlay=None) -> None:
|
|
"""Render one frame. ``overlay`` is an optional menu/help dict."""
|
|
pygame = self._pygame
|
|
screen.fill((0, 0, 0))
|
|
floor = session.floor
|
|
cam = compute_camera(session.player.x, session.player.y,
|
|
floor.width, floor.height, VIEW_W, VIEW_H)
|
|
|
|
self._draw_map(screen, floor, cam)
|
|
self._draw_entities(screen, floor, cam, session)
|
|
self._draw_top_bar(screen, session)
|
|
self._draw_log_panel(screen, session)
|
|
self._draw_bottom_bar(screen, session, audio)
|
|
|
|
# Context prompt on the map: pickup / descent hints.
|
|
prompt = context_prompt(session)
|
|
if prompt:
|
|
self._blit_text(screen, prompt, (8, TOP_H + MAP_PIX_H - 24),
|
|
(250, 240, 200), self._font)
|
|
|
|
if overlay:
|
|
self._draw_overlay(screen, overlay)
|
|
|
|
# -- map -----------------------------------------------------------------
|
|
def _draw_map(self, screen, floor, cam: Camera) -> None:
|
|
pygame = self._pygame
|
|
for row in range(VIEW_H):
|
|
my = cam.y + row
|
|
if my < 0 or my >= floor.height:
|
|
continue
|
|
vrow = floor.visible[my]
|
|
erow = floor.explored[my]
|
|
trow = floor.tiles[my]
|
|
py = TOP_H + row * TILE
|
|
for col in range(VIEW_W):
|
|
mx = cam.x + col
|
|
if mx < 0 or mx >= floor.width:
|
|
continue
|
|
if not erow[mx]:
|
|
continue
|
|
if trow[mx] == TILE_WALL:
|
|
color = COLORS["wall_visible"] if vrow[mx] else COLORS["wall_explored"]
|
|
else:
|
|
color = COLORS["floor_visible"] if vrow[mx] else COLORS["floor_explored"]
|
|
px = col * TILE
|
|
pygame.draw.rect(screen, color, (px, py, TILE, TILE))
|
|
|
|
# Stairs (only if explored at all; bright when visible).
|
|
if floor.stairs_down is not None:
|
|
sx, sy = floor.stairs_down
|
|
if 0 <= sy < floor.height and 0 <= sx < floor.width and floor.explored[sy][sx]:
|
|
col = sx - cam.x
|
|
row = sy - cam.y
|
|
if 0 <= col < VIEW_W and 0 <= row < VIEW_H:
|
|
px = col * TILE
|
|
py = TOP_H + row * TILE
|
|
lit = floor.visible[sy][sx]
|
|
base = COLORS["stairs"] if lit else (120, 110, 30)
|
|
pygame.draw.rect(screen, base, (px, py, TILE, TILE))
|
|
self._blit_text(screen, ">", (px + 3, py), (0, 0, 0), self._font_big)
|
|
|
|
def _draw_entities(self, screen, floor, cam: Camera, session) -> None:
|
|
pygame = self._pygame
|
|
# Items first (under actors).
|
|
for e in floor.entities:
|
|
if not isinstance(e, Item):
|
|
continue
|
|
if not self._visible(floor, e.x, e.y):
|
|
continue
|
|
self._draw_at(screen, e.x - cam.x, e.y - cam.y,
|
|
self._item_color(e), shape="diamond")
|
|
# Enemies.
|
|
for e in floor.entities:
|
|
if not isinstance(e, Enemy) or not getattr(e, "is_alive", True):
|
|
continue
|
|
if not self._visible(floor, e.x, e.y):
|
|
continue
|
|
color = COLORS.get(e.kind, getattr(e, "color", (200, 200, 200)))
|
|
self._draw_at(screen, e.x - cam.x, e.y - cam.y, color, shape="rect")
|
|
# Player always drawn on top.
|
|
self._draw_at(screen, session.player.x - cam.x, session.player.y - cam.y,
|
|
COLORS["player"], shape="circle")
|
|
|
|
@staticmethod
|
|
def _visible(floor, x: int, y: int) -> bool:
|
|
if 0 <= y < floor.height and 0 <= x < floor.width:
|
|
return floor.visible[y][x]
|
|
return False
|
|
|
|
def _draw_at(self, screen, col: int, row: int, color, shape: str) -> None:
|
|
pygame = self._pygame
|
|
if not (0 <= col < VIEW_W and 0 <= row < VIEW_H):
|
|
return
|
|
px = col * TILE
|
|
py = TOP_H + row * TILE
|
|
if shape == "circle":
|
|
pygame.draw.circle(screen, color, (px + TILE // 2, py + TILE // 2), TILE // 2 - 1)
|
|
elif shape == "diamond":
|
|
cx, cy = px + TILE // 2, py + TILE // 2
|
|
pygame.draw.polygon(screen, color,
|
|
[(cx, py + 2), (px + TILE - 2, cy),
|
|
(cx, py + TILE - 2), (px + 2, cy)])
|
|
else:
|
|
pygame.draw.rect(screen, color, (px + 1, py + 1, TILE - 2, TILE - 2))
|
|
|
|
@staticmethod
|
|
def _item_color(item) -> tuple:
|
|
cat = getattr(item, "category", None)
|
|
key = {"weapon": "weapon", "armor": "armor_item",
|
|
"potion": "potion", "scroll": "scroll"}.get(cat)
|
|
return COLORS.get(key, getattr(item, "color", (200, 200, 200)))
|
|
|
|
# -- top bar -------------------------------------------------------------
|
|
def _draw_top_bar(self, screen, session) -> None:
|
|
pygame = self._pygame
|
|
pygame.draw.rect(screen, (16, 16, 20), (0, 0, SCREEN_W, TOP_H))
|
|
pygame.draw.line(screen, (60, 60, 70), (0, TOP_H - 1), (SCREEN_W, TOP_H - 1))
|
|
|
|
p = session.player
|
|
floor_n = session.current_floor + 1
|
|
total = len(session.dungeon)
|
|
self._blit_text(screen, f"Floor {floor_n}/{total}", (8, 12),
|
|
(220, 220, 220), self._font)
|
|
|
|
# HP bar
|
|
bar_x, bar_y, bar_w, bar_h = 130, 12, 180, 16
|
|
pygame.draw.rect(screen, (60, 20, 20), (bar_x, bar_y, bar_w, bar_h))
|
|
frac = max(0.0, min(1.0, p.hp / max(1, p.max_hp)))
|
|
hp_color = (60, 200, 70) if frac > 0.3 else (220, 70, 60)
|
|
pygame.draw.rect(screen, hp_color, (bar_x, bar_y, int(bar_w * frac), bar_h))
|
|
pygame.draw.rect(screen, (110, 110, 120), (bar_x, bar_y, bar_w, bar_h), 1)
|
|
self._blit_text(screen, f"HP {p.hp}/{p.max_hp}", (bar_x + 6, bar_y),
|
|
(255, 255, 255), self._font_sm)
|
|
|
|
# Level + XP bar
|
|
lvl_x = 340
|
|
self._blit_text(screen, f"Lvl {p.level}", (lvl_x, 12),
|
|
(220, 220, 220), self._font)
|
|
xp_x, xp_y, xp_w, xp_h = 400, 14, 160, 14
|
|
pygame.draw.rect(screen, (20, 30, 60), (xp_x, xp_y, xp_w, xp_h))
|
|
lo = LEVEL_XP[p.level - 1] if 0 < p.level <= len(LEVEL_XP) else 0
|
|
hi = LEVEL_XP[p.level] if p.level < len(LEVEL_XP) else max(1, p.xp)
|
|
xp_frac = 0.0
|
|
if hi > lo:
|
|
xp_frac = max(0.0, min(1.0, (p.xp - lo) / (hi - lo)))
|
|
pygame.draw.rect(screen, (80, 140, 230), (xp_x, xp_y, int(xp_w * xp_frac), xp_h))
|
|
pygame.draw.rect(screen, (110, 110, 120), (xp_x, xp_y, xp_w, xp_h), 1)
|
|
self._blit_text(screen, f"XP {p.xp}", (xp_x + 6, xp_y - 1),
|
|
(255, 255, 255), self._font_sm)
|
|
|
|
self._blit_text(screen, f"Turn {session.turn}", (SCREEN_W - PANEL_W - 80, 12),
|
|
(170, 170, 170), self._font_sm)
|
|
|
|
# -- log panel -----------------------------------------------------------
|
|
def _draw_log_panel(self, screen, session) -> None:
|
|
pygame = self._pygame
|
|
x0 = MAP_PIX_W
|
|
pygame.draw.rect(screen, (14, 14, 18), (x0, TOP_H, PANEL_W, SCREEN_H - TOP_H))
|
|
pygame.draw.line(screen, (60, 60, 70), (x0, TOP_H), (x0, SCREEN_H))
|
|
self._blit_text(screen, "Messages", (x0 + 10, TOP_H + 8),
|
|
(200, 200, 210), self._font)
|
|
|
|
lines = session.log[-8:]
|
|
y = TOP_H + 36
|
|
for line in lines:
|
|
color = log_color(line)
|
|
# Wrap long lines naively to the panel width.
|
|
for wrapped in self._wrap(line, 44):
|
|
self._blit_text(screen, wrapped, (x0 + 10, y), color, self._font_sm)
|
|
y += 18
|
|
if y > SCREEN_H - 16:
|
|
return
|
|
|
|
# -- bottom bar ----------------------------------------------------------
|
|
def _draw_bottom_bar(self, screen, session, audio) -> None:
|
|
pygame = self._pygame
|
|
y0 = TOP_H + MAP_PIX_H
|
|
pygame.draw.rect(screen, (16, 16, 20), (0, y0, MAP_PIX_W, BOT_H))
|
|
pygame.draw.line(screen, (60, 60, 70), (0, y0), (MAP_PIX_W, y0))
|
|
|
|
p = session.player
|
|
weapon = p.weapon.name if p.weapon is not None else "(empty)"
|
|
armor = p.armor_item.name if p.armor_item is not None else "(empty)"
|
|
self._blit_text(screen, f"Weapon: {weapon}", (8, y0 + 8),
|
|
COLORS["weapon"], self._font_sm)
|
|
self._blit_text(screen, f"Armor: {armor}", (8, y0 + 30),
|
|
COLORS["armor_item"], self._font_sm)
|
|
pwr = p.total_power()
|
|
arm = p.total_armor()
|
|
self._blit_text(screen, f"Power {pwr} Armor {arm} Acc {p.accuracy} Evas {p.total_evasion():.0f}",
|
|
(8, y0 + 54), (210, 210, 210), self._font_sm)
|
|
|
|
effects = self._effects_summary(p)
|
|
self._blit_text(screen, effects, (8, y0 + 74), (180, 220, 200), self._font_sm)
|
|
|
|
sound_state = self._sound_label(audio)
|
|
self._blit_text(screen, sound_state, (MAP_PIX_W - 160, y0 + 74),
|
|
(180, 180, 190), self._font_sm)
|
|
inv_count = len(p.inventory)
|
|
self._blit_text(screen, f"Inv {inv_count} (i)", (MAP_PIX_W - 160, y0 + 8),
|
|
(200, 200, 200), self._font_sm)
|
|
self._blit_text(screen, "? help g pickup > descend S save m mute Esc menu",
|
|
(MAP_PIX_W - 460, y0 + 30), (150, 150, 160), self._font_sm)
|
|
|
|
@staticmethod
|
|
def _effects_summary(p) -> str:
|
|
parts = []
|
|
s = int(p.effects.get("strength", 0))
|
|
inv = int(p.effects.get("invisibility", 0))
|
|
if s > 0:
|
|
parts.append(f"Strength({s})")
|
|
if inv > 0:
|
|
parts.append(f"Invisible({inv})")
|
|
return "Effects: " + (" ".join(parts) if parts else "none")
|
|
|
|
@staticmethod
|
|
def _sound_label(audio) -> str:
|
|
if audio is None:
|
|
return "Sound: n/a"
|
|
if not getattr(audio, "enabled", False):
|
|
return "Sound: off"
|
|
return "Sound: muted" if getattr(audio, "muted", False) else "Sound: on"
|
|
|
|
# -- main menu ----------------------------------------------------------
|
|
def draw_main_menu(self, screen, title: str, items, selected: int,
|
|
footer: str = "", subtitle: str = "") -> None:
|
|
"""Draw the top-level menu. ``items`` is a list of ``(label, enabled)``."""
|
|
pygame = self._pygame
|
|
screen.fill((8, 8, 12))
|
|
# Faint dungeon backdrop.
|
|
for y in range(0, SCREEN_H, TILE):
|
|
for x in range(0, SCREEN_W, TILE):
|
|
if (x // TILE + y // TILE) % 2 == 0:
|
|
pygame.draw.rect(screen, (16, 14, 18), (x, y, TILE, TILE))
|
|
cx = SCREEN_W // 2
|
|
self._blit_text(screen, title, (cx - 180, 90), (240, 200, 90), self._font_big)
|
|
if subtitle:
|
|
self._blit_text(screen, subtitle, (cx - 200, 140), (170, 170, 180), self._font)
|
|
y = 220
|
|
for i, (label, enabled) in enumerate(items):
|
|
color = (240, 230, 160) if i == selected and enabled else (200, 200, 205)
|
|
if not enabled:
|
|
color = (90, 90, 95)
|
|
marker = "> " if i == selected and enabled else " "
|
|
text = f"{marker}{label}" + ("" if enabled else " (no save)")
|
|
self._blit_text(screen, text, (cx - 120, y), color, self._font_big)
|
|
y += 46
|
|
if footer:
|
|
self._blit_text(screen, footer, (40, SCREEN_H - 40), (150, 150, 160), self._font_sm)
|
|
self._blit_text(screen, "Underdepths", (SCREEN_W - 150, SCREEN_H - 40),
|
|
(110, 90, 40), self._font_sm)
|
|
|
|
# -- end screen ----------------------------------------------------------
|
|
def draw_end_screen(self, screen, title: str, lines, hint: str,
|
|
color=(235, 70, 70)) -> None:
|
|
pygame = self._pygame
|
|
veil = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
|
|
veil.fill((0, 0, 0, 170))
|
|
screen.blit(veil, (0, 0))
|
|
cx = SCREEN_W // 2
|
|
self._blit_text(screen, title, (cx - 240, SCREEN_H // 2 - 90), color, self._font_big)
|
|
y = SCREEN_H // 2 - 30
|
|
for line in lines:
|
|
for wrapped in self._wrap(line, 70):
|
|
self._blit_text(screen, wrapped, (cx - 280, y), (225, 225, 230), self._font)
|
|
y += 30
|
|
self._blit_text(screen, hint, (cx - 160, SCREEN_H - 110),
|
|
(190, 190, 200), self._font_sm)
|
|
|
|
# -- overlay (menus / help) ---------------------------------------------
|
|
def _draw_overlay(self, screen, overlay) -> None:
|
|
pygame = self._pygame
|
|
title = overlay.get("title", "")
|
|
body = overlay.get("body", []) or []
|
|
hint = overlay.get("hint", "Esc to close")
|
|
w, h = SCREEN_W - 160, SCREEN_H - 120
|
|
x, y = 80, 60
|
|
panel = pygame.Surface((w, h), pygame.SRCALPHA)
|
|
panel.fill((10, 10, 14, 235))
|
|
screen.blit(panel, (x, y))
|
|
pygame.draw.rect(screen, (90, 90, 110), (x, y, w, h), 2)
|
|
|
|
self._blit_text(screen, title, (x + 20, y + 16), (240, 230, 160), self._font_big)
|
|
ty = y + 56
|
|
for line in body:
|
|
for wrapped in self._wrap(line, 78):
|
|
self._blit_text(screen, wrapped, (x + 20, ty), (220, 220, 225), self._font_sm)
|
|
ty += 20
|
|
if ty > y + h - 36:
|
|
break
|
|
if ty > y + h - 36:
|
|
break
|
|
self._blit_text(screen, hint, (x + 20, y + h - 30), (170, 170, 180), self._font_sm)
|
|
|
|
# -- helpers -------------------------------------------------------------
|
|
def _blit_text(self, screen, text, pos, color, font) -> None:
|
|
try:
|
|
surf = font.render(str(text), True, color)
|
|
screen.blit(surf, pos)
|
|
except Exception:
|
|
pass
|
|
|
|
@staticmethod
|
|
def _wrap(text: str, width: int) -> list:
|
|
text = str(text)
|
|
if len(text) <= width:
|
|
return [text]
|
|
out, line = [], ""
|
|
for word in text.split(" "):
|
|
if line and len(line) + 1 + len(word) > width:
|
|
out.append(line)
|
|
line = word
|
|
else:
|
|
line = f"{line} {word}".strip()
|
|
if line:
|
|
out.append(line)
|
|
return out or [text]
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# standalone helpers
|
|
# --------------------------------------------------------------------------- #
|
|
def context_prompt(session) -> str:
|
|
"""Return the contextual action hint for the tile under the player."""
|
|
floor = session.floor
|
|
px, py = session.player.x, session.player.y
|
|
for e in floor.entities:
|
|
if isinstance(e, Item) and e.x == px and e.y == py:
|
|
return f"Press G to pick up {e.name}"
|
|
if floor.stairs_down is not None and tuple(floor.stairs_down) == (px, py):
|
|
return "Press > (Shift+.) to descend"
|
|
return ""
|
|
|
|
|
|
def log_color(line: str) -> tuple:
|
|
"""Colour-code a log line by rough keyword classification."""
|
|
low = line.lower()
|
|
if any(k in low for k in ("you have died", "defeats you", "slays you")):
|
|
return (235, 70, 70)
|
|
if "you for" in low or "fires at you" in low or "projectile hits" in low or "breath" in low:
|
|
return (235, 110, 90)
|
|
if "level" in low or "reach level" in low:
|
|
return (110, 220, 120)
|
|
if any(k in low for k in ("pick up", "equip", "unequip", "drink", "recover", "gain", "blink", "sears", "mapping")):
|
|
return (225, 205, 90)
|
|
if "critical" in low:
|
|
return (255, 200, 120)
|
|
return (220, 220, 225)
|