(Underdepth) Prepare for Pass 5
This commit is contained in:
32 files changed
+31
-4892
No files matched your search
Whitespace-only changes.
@@ -1,27 +0,0 @@
|
||||
"""Viewport camera that eases toward the player each frame (plan.md Juice)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
|
||||
class Camera:
|
||||
"""Pixel-space camera top-left. Eases toward its target; can snap."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.x: float = 0.0
|
||||
self.y: float = 0.0
|
||||
self._tx: float = 0.0
|
||||
self._ty: float = 0.0
|
||||
|
||||
def set_target(self, px: float, py: float) -> None:
|
||||
self._tx = px
|
||||
self._ty = py
|
||||
|
||||
def snap(self, px: float, py: float) -> None:
|
||||
self.x = self._tx = px
|
||||
self.y = self._ty = py
|
||||
|
||||
def update(self, dt: float, ease: float = 7.0) -> None:
|
||||
k = 1.0 - math.exp(-ease * dt)
|
||||
self.x += (self._tx - self.x) * k
|
||||
self.y += (self._ty - self.y) * k
|
||||
@@ -1,181 +0,0 @@
|
||||
"""Procedural visual effects: particles, floating combat text, screen shake,
|
||||
lighting helpers (torch falloff, vignette). All drawn from state; none mutate it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Particles — pooled and capped.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class Particles:
|
||||
def __init__(self, cap: int = 260) -> None:
|
||||
self._pool: list[dict] = []
|
||||
self._cap = cap
|
||||
|
||||
def clear(self) -> None:
|
||||
self._pool.clear()
|
||||
|
||||
def burst(self, x: float, y: float, color, n: int = 10, speed: float = 70.0,
|
||||
life: float = 0.45, gravity: float = 0.0, size: int = 2) -> None:
|
||||
for _ in range(n):
|
||||
if len(self._pool) >= self._cap:
|
||||
self._pool.pop(0)
|
||||
ang = random.random() * math.tau
|
||||
spd = random.uniform(speed * 0.25, speed)
|
||||
self._pool.append(dict(
|
||||
x=x, y=y, vx=math.cos(ang) * spd, vy=math.sin(ang) * spd,
|
||||
life=life, max=life, color=color, g=gravity, size=size))
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
drag = max(0.0, 1.0 - 2.2 * dt)
|
||||
for p in self._pool:
|
||||
p["life"] -= dt
|
||||
if p["life"] <= 0:
|
||||
continue
|
||||
p["x"] += p["vx"] * dt
|
||||
p["y"] += p["vy"] * dt
|
||||
p["vy"] += p["g"] * dt
|
||||
p["vx"] *= drag
|
||||
p["vy"] *= drag
|
||||
out.append(p)
|
||||
self._pool = out
|
||||
|
||||
def draw(self, surf, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for p in self._pool:
|
||||
frac = max(0.0, p["life"] / p["max"])
|
||||
a = max(0, min(255, int(255 * frac)))
|
||||
r = max(1, int(p["size"] * (0.6 + 0.4 * frac)))
|
||||
sx = int(p["x"] - cam[0])
|
||||
sy = int(p["y"] - cam[1])
|
||||
if -8 <= sx <= surf.get_width() + 8 and -8 <= sy <= surf.get_height() + 8:
|
||||
s = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
|
||||
pygame.draw.rect(s, (*p["color"], a), (0, 0, r * 2, r * 2))
|
||||
surf.blit(s, (sx - r, sy - r))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Floating combat text.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class FloatText:
|
||||
def __init__(self) -> None:
|
||||
self._items: list[dict] = []
|
||||
|
||||
def clear(self) -> None:
|
||||
self._items.clear()
|
||||
|
||||
def add(self, x: float, y: float, text: str, color, big: bool = False) -> None:
|
||||
self._items.append(dict(
|
||||
x=x, y=y, text=text, color=color, life=0.95, max=0.95,
|
||||
vy=-30.0, big=big))
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
for it in self._items:
|
||||
it["life"] -= dt
|
||||
if it["life"] <= 0:
|
||||
continue
|
||||
it["y"] += it["vy"] * dt
|
||||
it["vy"] *= max(0.0, 1.0 - 1.6 * dt)
|
||||
out.append(it)
|
||||
self._items = out
|
||||
|
||||
def draw(self, surf, font, font_big, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for it in self._items:
|
||||
frac = max(0.0, it["life"] / it["max"])
|
||||
a = max(0, min(255, int(255 * (frac ** 0.6))))
|
||||
f = font_big if it["big"] else font
|
||||
txt = f.render(it["text"], True, it["color"])
|
||||
txt.set_alpha(a)
|
||||
surf.blit(txt, (int(it["x"] - cam[0] - txt.get_width() // 2),
|
||||
int(it["y"] - cam[1])))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Screen shake — decaying random offset.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class Shake:
|
||||
def __init__(self) -> None:
|
||||
self.mag: float = 0.0
|
||||
|
||||
def trigger(self, mag: float = 6.0) -> None:
|
||||
self.mag = max(self.mag, mag)
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
self.mag *= math.exp(-dt * 6.5)
|
||||
if self.mag < 0.25:
|
||||
self.mag = 0.0
|
||||
|
||||
def offset(self):
|
||||
if self.mag <= 0.0:
|
||||
return (0.0, 0.0)
|
||||
return (random.uniform(-self.mag, self.mag),
|
||||
random.uniform(-self.mag, self.mag))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Lighting helpers.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def torch_factor(dist: float, radius: int) -> float:
|
||||
"""Brightness 1.0 at the player fading to ~0.22 at the sight edge.
|
||||
|
||||
A lower edge floor than before so the step from the last visible tile to
|
||||
black unexplored space is less jarring; the smooth radial torch glow
|
||||
(see make_torch) layered on top supplies the soft circular falloff.
|
||||
"""
|
||||
if radius <= 0:
|
||||
return 1.0
|
||||
f = 1.0 - max(0.0, dist) / radius
|
||||
return max(0.22, min(1.0, 0.22 + 0.78 * f))
|
||||
|
||||
|
||||
def make_torch(radius_px: int):
|
||||
"""Cached smooth radial torch glow (warm, additive) centred on the player.
|
||||
|
||||
Returns a Surface of side 2*radius_px whose RGB falls smoothly from a warm
|
||||
yellow-white at the centre to black at the edge; the renderer blits it with
|
||||
BLEND_RGB_ADD so it lays a soft circular light pool over the per-tile grid,
|
||||
hiding the tile-aligned FOV boundary. Rendered small then smooth-scaled up.
|
||||
"""
|
||||
if pygame is None:
|
||||
return None
|
||||
d = max(8, radius_px * 2)
|
||||
sw = max(28, d // 3)
|
||||
s = pygame.Surface((sw, sw), pygame.SRCALPHA)
|
||||
c = sw / 2
|
||||
for y in range(sw):
|
||||
for x in range(sw):
|
||||
dist = math.hypot(x - c, y - c) / c
|
||||
if dist >= 1.0:
|
||||
continue
|
||||
f = (1.0 - dist) ** 1.3
|
||||
s.set_at((x, y), (int(150 * f), int(132 * f), int(96 * f), 255))
|
||||
return pygame.transform.smoothscale(s, (d, d))
|
||||
|
||||
|
||||
def make_vignette(w: int, h: int):
|
||||
"""Cached radial darkening overlay (transparent centre, dark corners)."""
|
||||
if pygame is None:
|
||||
return None
|
||||
sw, sh = max(2, w // 4), max(2, h // 4)
|
||||
s = pygame.Surface((sw, sh), pygame.SRCALPHA)
|
||||
cx, cy = sw / 2, sh / 2
|
||||
maxd = math.hypot(cx, cy)
|
||||
for y in range(sh):
|
||||
for x in range(sw):
|
||||
d = math.hypot(x - cx, y - cy) / maxd
|
||||
a = int(min(165, max(0, (d - 0.52)) * 370))
|
||||
s.set_at((x, y), (0, 0, 0, a))
|
||||
return pygame.transform.smoothscale(s, (w, h))
|
||||
@@ -1,520 +0,0 @@
|
||||
"""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)"
|
||||
@@ -1,55 +0,0 @@
|
||||
"""Rasterize palette-key sprite grids to cached pygame Surfaces (plan.md Rendering).
|
||||
|
||||
`get(name, frame, tile)` builds a Surface once (keyed by name+frame+tile) and
|
||||
caches it. The renderer blits the cached surface directly. Pixel-art is kept
|
||||
crisp with nearest-neighbour `transform.scale` (never smoothscale).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
from data import sprites as S
|
||||
from data.constants import PALETTE, TILE as _TILE
|
||||
|
||||
_cache: dict = {}
|
||||
|
||||
|
||||
def get(name: str, frame: int = 0, tile: int = _TILE):
|
||||
"""Return the cached Surface for `name` scaled to `tile`x`tile`."""
|
||||
if pygame is None:
|
||||
return None
|
||||
key = (name, frame, tile)
|
||||
cached = _cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
grid = S.grid(name, frame)
|
||||
h = len(grid)
|
||||
w = max(len(r) for r in grid) if grid else 1
|
||||
w = max(1, w)
|
||||
cell = 3 # fixed >=2 internal px/cell; crisp nearest-scale to any tile size
|
||||
surf = pygame.Surface((w * cell, h * cell), pygame.SRCALPHA)
|
||||
for y, row in enumerate(grid):
|
||||
for x, ch in enumerate(row):
|
||||
col = PALETTE.get(ch)
|
||||
if col is not None:
|
||||
pygame.draw.rect(surf, col, (x * cell, y * cell, cell, cell))
|
||||
if (w * cell, h * cell) != (tile, tile):
|
||||
surf = pygame.transform.scale(surf, (tile, tile))
|
||||
_cache[key] = surf
|
||||
return surf
|
||||
|
||||
|
||||
def frame_count(name: str) -> int:
|
||||
return S.frames_count(name)
|
||||
|
||||
|
||||
def warm(tile: int = _TILE) -> None:
|
||||
"""Pre-rasterize every sprite frame so the first frame is hitch-free."""
|
||||
if pygame is None:
|
||||
return
|
||||
for name in S.NAMES:
|
||||
for f in range(S.frames_count(name)):
|
||||
get(name, f, tile)
|
||||
Reference in new issue
Block a user