(Underdepths) Prepare for final pass
This commit is contained in:
53 files changed
-5020
No files matched your search
@@ -1 +0,0 @@
|
||||
"""Rendering package: pure read-and-draw of GameSession."""
|
||||
@@ -1,46 +0,0 @@
|
||||
"""Smooth easing camera that follows the player.
|
||||
|
||||
Stateless from the game's perspective: the camera keeps its own smoothed pixel
|
||||
position (view state, not game state). ``main`` owns the instance and passes the
|
||||
resulting offset to ``Renderer.render``; the renderer itself just applies it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from data.constants import MAP_W, MAP_H, TILE
|
||||
|
||||
|
||||
class Camera:
|
||||
def __init__(self, smoothing: float = 0.18) -> None:
|
||||
self.x: float = 0.0
|
||||
self.y: float = 0.0
|
||||
self.smoothing = max(0.0, min(1.0, smoothing))
|
||||
|
||||
def reset(self, player_xy: tuple[int, int]) -> None:
|
||||
self.x = float(player_xy[0] * TILE)
|
||||
self.y = float(player_xy[1] * TILE)
|
||||
|
||||
def update(self, player_xy: tuple[int, int]) -> tuple[int, int]:
|
||||
tx = player_xy[0] * TILE
|
||||
ty = player_xy[1] * TILE
|
||||
self.x += (tx - self.x) * self.smoothing
|
||||
self.y += (ty - self.y) * self.smoothing
|
||||
return int(self.x), int(self.y)
|
||||
|
||||
def offset_for(self, surface_wh: tuple[int, int], player_xy: tuple[int, int]) -> tuple[int, int]:
|
||||
"""Center the player on screen, clamped to the map bounds (pixel offset)."""
|
||||
sw, sh = surface_wh
|
||||
px = int(self.x)
|
||||
py = int(self.y)
|
||||
ox = px - sw // 2
|
||||
oy = py - sh // 2
|
||||
max_ox = MAP_W * TILE - sw
|
||||
max_oy = MAP_H * TILE - sh
|
||||
if max_ox <= 0:
|
||||
ox = (MAP_W * TILE - sw) // 2
|
||||
else:
|
||||
ox = max(0, min(max_ox, ox))
|
||||
if max_oy <= 0:
|
||||
oy = (MAP_H * TILE - sh) // 2
|
||||
else:
|
||||
oy = max(0, min(max_oy, oy))
|
||||
return ox, oy
|
||||
@@ -1,124 +0,0 @@
|
||||
"""Render-only effects: screen-shake, particles, and a vignette.
|
||||
|
||||
All state here is view state owned by the Renderer instance, never game state.
|
||||
Lighting (visible bright / explored dimmed / unexplored black + radial falloff)
|
||||
is applied per-tile inside ``renderer``; this module supplies the juice and the
|
||||
edge-darkening vignette overlay.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
import pygame
|
||||
|
||||
_MAX_PARTICLES = 160
|
||||
|
||||
|
||||
def torch_factor(dx: int, dy: int, radius: int) -> float:
|
||||
"""Radial torch brightness at a tile offset from the bearer.
|
||||
|
||||
Bright warm core (1.0) graduating smoothly to a dim rim (~0.55) at the
|
||||
sight edge — a soft gradient, not a hard disc. Quadratic falloff keeps the
|
||||
core clearly bright. Chebyshev distance matches the FOV radius so the lit
|
||||
disc stays round; walls occlude light via the visible set computed upstream.
|
||||
"""
|
||||
d = max(abs(dx), abs(dy))
|
||||
if d >= radius:
|
||||
return 0.55
|
||||
t = d / radius
|
||||
return 1.0 - 0.45 * (t * t)
|
||||
|
||||
|
||||
class Shake:
|
||||
"""Decaying screen-shake; returns a pixel offset each frame."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._mag = 0.0
|
||||
|
||||
def trigger(self, magnitude: float = 6.0) -> None:
|
||||
self._mag = min(10.0, max(self._mag, magnitude))
|
||||
|
||||
def offset(self) -> tuple[int, int]:
|
||||
if self._mag <= 0.05:
|
||||
self._mag = 0.0
|
||||
return 0, 0
|
||||
dx = random.uniform(-1, 1) * self._mag
|
||||
dy = random.uniform(-1, 1) * self._mag
|
||||
self._mag *= 0.82
|
||||
return int(dx), int(dy)
|
||||
|
||||
|
||||
class Particles:
|
||||
"""Pooled, capped particle bursts (hit sparks, blood, level-up stars, etc.)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._parts: list[dict[str, Any]] = []
|
||||
|
||||
def burst(self, x: float, y: float, color: tuple[int, int, int],
|
||||
count: int = 10, speed: float = 60.0, life: float = 0.4) -> None:
|
||||
for _ in range(count):
|
||||
if len(self._parts) >= _MAX_PARTICLES:
|
||||
break
|
||||
ang = random.uniform(0, math.tau)
|
||||
spd = speed * random.uniform(0.4, 1.0)
|
||||
self._parts.append({
|
||||
"x": x, "y": y,
|
||||
"vx": math.cos(ang) * spd, "vy": math.sin(ang) * spd,
|
||||
"life": life * random.uniform(0.7, 1.2), "age": 0.0,
|
||||
"color": color, "size": random.randint(2, 3),
|
||||
})
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
alive: list[dict[str, Any]] = []
|
||||
for p in self._parts:
|
||||
p["age"] += dt
|
||||
if p["age"] >= p["life"]:
|
||||
continue
|
||||
p["x"] += p["vx"] * dt
|
||||
p["y"] += p["vy"] * dt
|
||||
p["vy"] += 90.0 * dt # gentle gravity
|
||||
alive.append(p)
|
||||
self._parts = alive
|
||||
|
||||
def draw(self, surface: pygame.Surface, cam_xy: tuple[int, int]) -> None:
|
||||
ox, oy = cam_xy
|
||||
for p in self._parts:
|
||||
t = 1.0 - p["age"] / p["life"]
|
||||
r = max(1, int(p["size"] * t))
|
||||
c = p["color"]
|
||||
col = (int(c[0] * t), int(c[1] * t), int(c[2] * t))
|
||||
pygame.draw.circle(surface, col, (int(p["x"] - ox), int(p["y"] - oy)), r)
|
||||
|
||||
|
||||
def vignette(size: tuple[int, int]) -> pygame.Surface:
|
||||
"""Soft edge-darkening overlay (cached by size via module dict)."""
|
||||
key = size
|
||||
surf = _VIGNETTE_CACHE.get(key)
|
||||
if surf is not None:
|
||||
return surf
|
||||
w, h = size
|
||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
||||
cx, cy = w / 2, h / 2
|
||||
max_d = math.hypot(cx, cy)
|
||||
# Subtle edge-only vignette: concentric non-overlapping annuli (width=step)
|
||||
# so alpha never accumulates. Only the outer ~38% of the screen darkens; the
|
||||
# center stays clear. Max alpha is gentle so edges are never crushed to black.
|
||||
step = 8
|
||||
inner_t = 0.62 # no darkening inside 62% of the corner distance
|
||||
max_alpha = 78
|
||||
r = int(max_d)
|
||||
while r > 0:
|
||||
t = r / max_d
|
||||
if t > inner_t:
|
||||
u = (t - inner_t) / (1.0 - inner_t)
|
||||
alpha = int(max_alpha * u * u)
|
||||
if alpha > 0:
|
||||
pygame.draw.circle(surf, (0, 0, 0, alpha), (int(cx), int(cy)), r, step)
|
||||
r -= step
|
||||
_VIGNETTE_CACHE[key] = surf
|
||||
return surf
|
||||
|
||||
|
||||
_VIGNETTE_CACHE: dict[tuple[int, int], pygame.Surface] = {}
|
||||
@@ -1,506 +0,0 @@
|
||||
"""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)
|
||||
@@ -1,151 +0,0 @@
|
||||
"""Rasterize palette-key grids to cached pygame Surfaces.
|
||||
|
||||
``get_sprite(name)`` returns the native-size cached Surface; the renderer scales
|
||||
it to ``TILE`` via ``get_tile_sprite``. All art is procedural (pygame.draw /
|
||||
set_at from in-code palettes); no external image files are loaded.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pygame
|
||||
|
||||
from data import sprites as SPRITE_DATA
|
||||
from data.constants import PALETTE, TILE
|
||||
|
||||
_NATIVE: dict[str, pygame.Surface] = {}
|
||||
_SCALED: dict[str, pygame.Surface] = {}
|
||||
|
||||
|
||||
def _color(ch: str, tint: tuple[int, int, int] | None) -> tuple[int, int, int] | None:
|
||||
if ch == "a":
|
||||
return tint if tint is not None else (200, 200, 200)
|
||||
return PALETTE.get(ch)
|
||||
|
||||
|
||||
def _rasterize(grid: list[str], tint: tuple[int, int, int] | None) -> pygame.Surface:
|
||||
h = len(grid)
|
||||
w = max((len(row) for row in grid), default=1)
|
||||
w = max(1, w)
|
||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
||||
for y, row in enumerate(grid):
|
||||
for x, ch in enumerate(row):
|
||||
c = _color(ch, tint)
|
||||
if c is not None:
|
||||
surf.set_at((x, y), (c[0], c[1], c[2], 255))
|
||||
return surf
|
||||
|
||||
|
||||
def _convert(surf: pygame.Surface) -> pygame.Surface:
|
||||
try:
|
||||
return surf.convert_alpha()
|
||||
except Exception:
|
||||
return surf # no display yet (e.g. constructed before set_mode): use raw
|
||||
|
||||
|
||||
def _make_dragon() -> pygame.Surface:
|
||||
"""Procedural 2x2 boss dragon: ONE connected silhouette (wings+body+head+tail
|
||||
drawn in the same red with no internal outlines, so it reads as a single
|
||||
creature, not separate blobs), then details layered on top."""
|
||||
size = TILE * 2
|
||||
s = pygame.Surface((size, size), pygame.SRCALPHA)
|
||||
K = (16, 14, 20); n = (140, 42, 42); r = (208, 66, 54); H = (172, 54, 54)
|
||||
h = (235, 235, 235); y = (246, 206, 86); amber = (222, 156, 60)
|
||||
|
||||
def poly(col, pts):
|
||||
pygame.draw.polygon(s, col, pts)
|
||||
|
||||
def ell(col, cx, cy, rw, rh):
|
||||
pygame.draw.ellipse(s, col, pygame.Rect(cx - rw, cy - rh, rw * 2, rh * 2))
|
||||
|
||||
# ---- single connected red silhouette: wings sweep up-out, body+head capsule ----
|
||||
poly(r, [(20, 16), (5, 7), (2, 15), (7, 20), (13, 17), (20, 21)]) # left wing
|
||||
poly(r, [(20, 16), (35, 7), (38, 15), (33, 20), (27, 17), (20, 21)]) # right wing
|
||||
ell(r, 20, 22, 7, 13) # body + head capsule
|
||||
poly(r, [(17, 34), (23, 34), (27, 39), (13, 39)]) # tail
|
||||
# wing membrane shading (darker), inside the wings only
|
||||
poly(n, [(16, 15), (6, 9), (4, 14), (9, 18), (13, 16)])
|
||||
poly(n, [(24, 15), (34, 9), (36, 14), (31, 18), (27, 16)])
|
||||
pygame.draw.line(s, H, (20, 17), (6, 9), 1) # finger bones
|
||||
pygame.draw.line(s, H, (20, 17), (13, 16), 1)
|
||||
pygame.draw.line(s, H, (20, 17), (34, 9), 1)
|
||||
pygame.draw.line(s, H, (20, 17), (27, 16), 1)
|
||||
# ---- details ----
|
||||
for sx in (16, 20, 24): # dorsal spines
|
||||
poly(H, [(sx - 1, 10), (sx + 1, 10), (sx, 5)])
|
||||
ell(y, 20, 28, 4, 5) # fiery belly
|
||||
for by in (26, 29, 32):
|
||||
pygame.draw.line(s, amber, (17, by), (23, by), 1)
|
||||
poly(h, [(15, 10), (10, 2), (13, 2), (17, 9)]) # horns
|
||||
poly(h, [(25, 10), (30, 2), (27, 2), (23, 9)])
|
||||
pygame.draw.line(s, H, (14, 14), (17, 14), 1) # brows
|
||||
pygame.draw.line(s, H, (23, 14), (26, 14), 1)
|
||||
pygame.draw.circle(s, y, (17, 16), 2) # eyes
|
||||
pygame.draw.circle(s, y, (23, 16), 2)
|
||||
pygame.draw.line(s, K, (17, 15), (17, 17), 1)
|
||||
pygame.draw.line(s, K, (23, 15), (23, 17), 1)
|
||||
pygame.draw.circle(s, K, (19, 19), 1) # nostrils
|
||||
pygame.draw.circle(s, K, (21, 19), 1)
|
||||
poly(h, [(18, 18), (17, 21), (19, 19)]) # fangs
|
||||
poly(h, [(22, 18), (23, 21), (21, 19)])
|
||||
for fx in (16, 24): # claws
|
||||
pygame.draw.line(s, h, (fx - 2, 35), (fx - 2, 38), 1)
|
||||
pygame.draw.line(s, h, (fx, 35), (fx, 38), 1)
|
||||
pygame.draw.line(s, h, (fx + 2, 35), (fx + 2, 38), 1)
|
||||
return s
|
||||
|
||||
|
||||
def get_sprite(name: str) -> pygame.Surface:
|
||||
"""Native-size cached sprite for ``name`` (transparent background)."""
|
||||
if name in _NATIVE:
|
||||
return _NATIVE[name]
|
||||
if name == "ancient_dragon":
|
||||
surf = _convert(_make_dragon())
|
||||
_NATIVE[name] = surf
|
||||
return surf
|
||||
grid = SPRITE_DATA.GRIDS.get(name)
|
||||
if grid is None:
|
||||
grid = SPRITE_DATA.GRIDS["player"] # safe fallback
|
||||
tint = SPRITE_DATA.TINTS.get(name)
|
||||
surf = _convert(_rasterize(grid, tint))
|
||||
_NATIVE[name] = surf
|
||||
return surf
|
||||
|
||||
|
||||
def get_tile_sprite(name: str, size: int = TILE) -> pygame.Surface:
|
||||
"""Sprite scaled to ``size`` (cached per name+size)."""
|
||||
key = f"{name}@{size}"
|
||||
if key in _SCALED:
|
||||
return _SCALED[key]
|
||||
native = get_sprite(name)
|
||||
scaled = pygame.transform.scale(native, (size, size))
|
||||
_SCALED[key] = scaled
|
||||
return scaled
|
||||
|
||||
|
||||
def clear_cache() -> None:
|
||||
_NATIVE.clear()
|
||||
_SCALED.clear()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pygame.init()
|
||||
pygame.display.set_mode((16, 16))
|
||||
s = get_sprite("stairs")
|
||||
opaque = yellow = 0
|
||||
for yy in range(s.get_height()):
|
||||
for xx in range(s.get_width()):
|
||||
c = s.get_at((xx, yy))
|
||||
if c.a == 0:
|
||||
continue
|
||||
opaque += 1
|
||||
if c.r > 120 and c.g > 100 and c.b < 110:
|
||||
yellow += 1
|
||||
print(f"stairs {s.get_size()} opaque={opaque} yellow={yellow}")
|
||||
assert opaque > 0 and yellow > 0, "stairs sprite not yellow/opaque"
|
||||
for n in ("player", "rat", "goblin", "skeleton_archer", "orc_warrior",
|
||||
"wraith", "green_slime", "ancient_dragon", "healing_potion", "war_hammer"):
|
||||
g = get_sprite(n)
|
||||
assert g.get_width() >= 4 and g.get_height() >= 4, n
|
||||
print("sprites self-check: OK")
|
||||
pygame.quit()
|
||||
Reference in new issue
Block a user