(Underdepths) Pass 7
This commit is contained in:
40 files changed
+8023
-35
No files matched your search
@@ -0,0 +1,901 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from typing import Final
|
||||
|
||||
import pygame
|
||||
|
||||
from data.constants import (
|
||||
ANIM_ATTACK_MS,
|
||||
ANIM_HIT_FLASH_MS,
|
||||
BOTTOMBAR_HEIGHT,
|
||||
COLORS,
|
||||
Color,
|
||||
FPS,
|
||||
GAME_TITLE,
|
||||
HOW_TO_PLAY,
|
||||
HP_BAR,
|
||||
HP_BAR_LOW,
|
||||
LOG_COMBAT,
|
||||
LOG_DAMAGE,
|
||||
LOG_DEFAULT,
|
||||
LOG_GOOD,
|
||||
LOG_INFO,
|
||||
LOG_ITEM,
|
||||
SIDEBAR_WIDTH,
|
||||
TILE_SIZE,
|
||||
TOPBAR_HEIGHT,
|
||||
UI_BORDER,
|
||||
UI_BORDER_DARK,
|
||||
UI_PANEL,
|
||||
UI_PANEL_LIGHT,
|
||||
UI_TEXT_DIM,
|
||||
VIEWPORT_TILES_H,
|
||||
VIEWPORT_TILES_W,
|
||||
WINDOW_HEIGHT,
|
||||
WINDOW_WIDTH,
|
||||
XP_BAR,
|
||||
XP_THRESHOLDS,
|
||||
)
|
||||
from data.sprites import TILE_SPRITES, player_layers
|
||||
from engine.actions import main_menu_entries, overlay_entries
|
||||
from engine.game_state import (
|
||||
OVERLAY_EQUIPMENT,
|
||||
OVERLAY_HELP,
|
||||
OVERLAY_INVENTORY,
|
||||
OVERLAY_QUAFF,
|
||||
OVERLAY_READ,
|
||||
STATE_DEAD,
|
||||
STATE_MENU,
|
||||
STATE_VICTORY,
|
||||
GameSession,
|
||||
)
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Player
|
||||
from render.effects import (
|
||||
Camera,
|
||||
FloatingTexts,
|
||||
Particles,
|
||||
ScreenShake,
|
||||
explored_light_alpha,
|
||||
explored_tint,
|
||||
light_tile,
|
||||
vignette,
|
||||
visible_light_alpha,
|
||||
)
|
||||
from render.sprites import sprite_surface
|
||||
|
||||
MAP_AREA: Final[pygame.Rect] = pygame.Rect(
|
||||
0, TOPBAR_HEIGHT, VIEWPORT_TILES_W * TILE_SIZE, VIEWPORT_TILES_H * TILE_SIZE
|
||||
)
|
||||
SIDEBAR_AREA: Final[pygame.Rect] = pygame.Rect(
|
||||
VIEWPORT_TILES_W * TILE_SIZE,
|
||||
TOPBAR_HEIGHT,
|
||||
SIDEBAR_WIDTH,
|
||||
VIEWPORT_TILES_H * TILE_SIZE,
|
||||
)
|
||||
PIXELS_PER_CELL: Final = TILE_SIZE // 16
|
||||
LOG_ROWS: Final = 8
|
||||
OVERLAY_PANEL: Final[pygame.Rect] = pygame.Rect(0, 0, 660, 404)
|
||||
OVERLAY_PANEL.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
|
||||
OVERLAY_ROWS: Final = 12
|
||||
END_PRESS_KEY: Final = "Press any key to return to the menu"
|
||||
|
||||
_OVERLAY_TITLES: Final[dict[str, str]] = {
|
||||
OVERLAY_INVENTORY: "Inventory",
|
||||
OVERLAY_EQUIPMENT: "Equipment",
|
||||
OVERLAY_QUAFF: "Quaff a potion",
|
||||
OVERLAY_READ: "Read a scroll",
|
||||
}
|
||||
|
||||
_DAMAGE_TEXT: Final[Color] = (255, 96, 84)
|
||||
_HEAL_TEXT: Final[Color] = (150, 240, 160)
|
||||
|
||||
_shadows: dict[int, pygame.Surface] = {}
|
||||
_glows: dict[int, pygame.Surface] = {}
|
||||
|
||||
|
||||
def _shadow(width: int) -> pygame.Surface:
|
||||
cached = _shadows.get(width)
|
||||
if cached is not None:
|
||||
return cached
|
||||
surface = pygame.Surface((width, width // 3), pygame.SRCALPHA)
|
||||
pygame.draw.ellipse(surface, (0, 0, 0, 105), surface.get_rect())
|
||||
_shadows[width] = surface
|
||||
return surface
|
||||
|
||||
|
||||
def _glow(size: int, color: Color) -> pygame.Surface:
|
||||
cached = _glows.get(size)
|
||||
if cached is not None:
|
||||
return cached
|
||||
surface = pygame.Surface((size, size), pygame.SRCALPHA)
|
||||
half = size // 2
|
||||
for ring in range(half, 0, -2):
|
||||
alpha = int(80 * (1.0 - ring / half))
|
||||
if alpha <= 0:
|
||||
continue
|
||||
pygame.draw.circle(surface, (*color, alpha), (half, half), ring)
|
||||
_glows[size] = surface
|
||||
return surface
|
||||
|
||||
|
||||
def _log_color(message: str) -> Color:
|
||||
if "hits you" in message or "You died" in message:
|
||||
return LOG_DAMAGE
|
||||
if (
|
||||
"reach level" in message
|
||||
or "defeated" in message
|
||||
or "conquered" in message
|
||||
or "feel better" in message
|
||||
or "slew" in message
|
||||
):
|
||||
return LOG_GOOD
|
||||
if (
|
||||
"pick up" in message
|
||||
or "equip" in message
|
||||
or "quaff" in message
|
||||
or "read the" in message
|
||||
or "remove the" in message
|
||||
or "pack is full" in message
|
||||
):
|
||||
return LOG_ITEM
|
||||
if "descend" in message or "stairs" in message or "unfurls" in message or "splits" in message:
|
||||
return LOG_INFO
|
||||
if "hit" in message or "miss" in message or "damage" in message:
|
||||
return LOG_COMBAT
|
||||
return LOG_DEFAULT
|
||||
|
||||
|
||||
def _xp_fraction(player: Player) -> float:
|
||||
if player.level > len(XP_THRESHOLDS):
|
||||
return 1.0
|
||||
next_threshold = XP_THRESHOLDS[player.level - 1]
|
||||
previous = XP_THRESHOLDS[player.level - 2] if player.level >= 2 else 0
|
||||
span = next_threshold - previous
|
||||
if span <= 0:
|
||||
return 1.0
|
||||
return min(1.0, max(0.0, (player.xp - previous) / span))
|
||||
|
||||
|
||||
def _death_burst_kind(sprite_key: str) -> str:
|
||||
if "slime" in sprite_key:
|
||||
return "slime"
|
||||
if sprite_key == "wraith":
|
||||
return "ash"
|
||||
return "blood"
|
||||
|
||||
|
||||
class Renderer:
|
||||
"""Pure composition of the whole frame: reads GameSession, draws, mutates
|
||||
nothing but its own view state (camera, particles, timers)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
screen: pygame.Surface,
|
||||
font: pygame.font.Font,
|
||||
title_font: pygame.font.Font,
|
||||
) -> None:
|
||||
self.screen = screen
|
||||
self.font = font
|
||||
self.title_font = title_font
|
||||
self.camera = Camera((MAP_AREA.width, MAP_AREA.height))
|
||||
self.particles = Particles()
|
||||
self.texts = FloatingTexts()
|
||||
self.shake = ScreenShake()
|
||||
self._rng = random.Random(60466)
|
||||
self._floor = -1
|
||||
self._log_seen = 0
|
||||
self._player_hp: int | None = None
|
||||
self._player_pos: tuple[int, int] | None = None
|
||||
self._face_dx = 0
|
||||
self._face_dy = 1
|
||||
self._facing_up = False
|
||||
self._flip_x = False
|
||||
self._hurt_ms = -10_000
|
||||
self._attack_ms = -10_000
|
||||
self._enemy_state: dict[int, tuple[tuple[int, int], int, str]] = {}
|
||||
|
||||
# ---- frame ----
|
||||
|
||||
def draw(
|
||||
self,
|
||||
session: GameSession,
|
||||
*,
|
||||
muted: bool = False,
|
||||
dt: float = 1.0 / FPS,
|
||||
now_ms: int = 0,
|
||||
) -> None:
|
||||
self.screen.fill(COLORS["background"])
|
||||
if session.state == STATE_MENU:
|
||||
self._draw_menu(session, muted)
|
||||
elif session.state in (STATE_DEAD, STATE_VICTORY):
|
||||
self._draw_end(session)
|
||||
else:
|
||||
self._observe(session, now_ms)
|
||||
self.particles.update(dt)
|
||||
self.texts.update(dt)
|
||||
self.shake.update(dt)
|
||||
self._draw_world(session, now_ms, dt)
|
||||
self._draw_topbar(session)
|
||||
self._draw_sidebar(session)
|
||||
self._draw_bottombar(session, muted)
|
||||
self._draw_context_chip(session)
|
||||
if session.overlay is not None:
|
||||
self._draw_overlay(session)
|
||||
|
||||
# ---- juice observation (reads only) ----
|
||||
|
||||
def _observe(self, session: GameSession, now_ms: int) -> None:
|
||||
player = session.player
|
||||
game_map = session.current_map
|
||||
|
||||
if session.current_floor != self._floor:
|
||||
self._floor = session.current_floor
|
||||
self.particles.clear()
|
||||
self.texts.clear()
|
||||
self._enemy_state.clear()
|
||||
self.camera.clamp_bounds(game_map.width, game_map.height, TILE_SIZE)
|
||||
self.camera.snap((player.x + 0.5) * TILE_SIZE, (player.y + 0.5) * TILE_SIZE)
|
||||
|
||||
player_center = self._center(player.position)
|
||||
if self._player_hp is not None and player.hp < self._player_hp:
|
||||
damage = self._player_hp - player.hp
|
||||
self.shake.add(min(0.65, 0.25 + damage / 40.0))
|
||||
self.particles.burst(*player_center, "blood", 8)
|
||||
self.texts.add(f"-{damage}", _DAMAGE_TEXT, player_center[0], player_center[1] - 6)
|
||||
self._hurt_ms = now_ms
|
||||
elif self._player_hp is not None and player.hp > self._player_hp:
|
||||
gained = player.hp - self._player_hp
|
||||
self.particles.burst(*player_center, "heal", 5)
|
||||
self.texts.add(f"+{gained}", _HEAL_TEXT, player_center[0], player_center[1] - 6)
|
||||
self._player_hp = player.hp
|
||||
|
||||
position = player.position
|
||||
if self._player_pos is not None and position != self._player_pos:
|
||||
dx, dy = position[0] - self._player_pos[0], position[1] - self._player_pos[1]
|
||||
if dx:
|
||||
self._face_dx, self._face_dy = (1 if dx > 0 else -1), 0
|
||||
self._flip_x = dx < 0
|
||||
self._facing_up = False
|
||||
if dy:
|
||||
self._face_dx, self._face_dy = 0, (1 if dy > 0 else -1)
|
||||
self._facing_up = dy < 0
|
||||
self._flip_x = False
|
||||
self._player_pos = position
|
||||
|
||||
alive: dict[int, Enemy] = {}
|
||||
for entity in game_map.entities:
|
||||
if isinstance(entity, Enemy) and entity.alive:
|
||||
alive[id(entity)] = entity
|
||||
for entity_id, entity in alive.items():
|
||||
previous = self._enemy_state.get(entity_id)
|
||||
if previous is not None and entity.hp < previous[1]:
|
||||
damage = previous[1] - entity.hp
|
||||
center = self._center(entity.position)
|
||||
kind = "slime" if "slime" in entity.sprite_key else "hit"
|
||||
self.particles.burst(*center, kind, 6 + min(6, damage))
|
||||
self.texts.add(f"-{damage}", LOG_COMBAT, center[0], center[1] - 4)
|
||||
self._enemy_state[entity_id] = (entity.position, entity.hp, entity.sprite_key)
|
||||
for entity_id, (last_pos, _hp, sprite_key) in list(self._enemy_state.items()):
|
||||
if entity_id not in alive:
|
||||
self.particles.burst(*self._center(last_pos), _death_burst_kind(sprite_key), 12)
|
||||
del self._enemy_state[entity_id]
|
||||
|
||||
log = session.log
|
||||
if len(log) > self._log_seen:
|
||||
fresh = log[self._log_seen :]
|
||||
elif log:
|
||||
fresh = [log[-1]] # the log wrapped past its cap; the tail is unheard
|
||||
else:
|
||||
fresh = []
|
||||
self._log_seen = len(log)
|
||||
for message in fresh:
|
||||
if "reach level" in message:
|
||||
self.particles.burst(*player_center, "stars", 14)
|
||||
elif "pick up" in message:
|
||||
self.particles.burst(*player_center, "sparkle", 8)
|
||||
elif "Critical hit" in message:
|
||||
self._attack_ms = now_ms
|
||||
self.particles.burst(*player_center, "crit", 12)
|
||||
elif "You hit" in message:
|
||||
self._attack_ms = now_ms
|
||||
|
||||
@staticmethod
|
||||
def _center(tile: tuple[int, int]) -> tuple[float, float]:
|
||||
return (tile[0] + 0.5) * TILE_SIZE, (tile[1] + 0.5) * TILE_SIZE
|
||||
|
||||
# ---- world ----
|
||||
|
||||
def _draw_world(self, session: GameSession, now_ms: int, dt: float) -> None:
|
||||
game_map = session.current_map
|
||||
player = session.player
|
||||
px, py = player.position
|
||||
|
||||
self.camera.clamp_bounds(game_map.width, game_map.height, TILE_SIZE)
|
||||
self.camera.update((px + 0.5) * TILE_SIZE, (py + 0.5) * TILE_SIZE, dt)
|
||||
cam_x, cam_y = self.camera.offset
|
||||
shake_x, shake_y = self.shake.offset()
|
||||
ox, oy = cam_x + shake_x, cam_y + shake_y
|
||||
|
||||
x0 = max(0, ox // TILE_SIZE)
|
||||
y0 = max(0, oy // TILE_SIZE)
|
||||
x1 = min(game_map.width, -(-(ox + MAP_AREA.width) // TILE_SIZE) + 1)
|
||||
y1 = min(game_map.height, -(-(oy + MAP_AREA.height) // TILE_SIZE) + 1)
|
||||
flicker = 10.0 * math.sin(now_ms / 173.0) + 6.0 * math.sin(now_ms / 97.0)
|
||||
|
||||
self.screen.set_clip(MAP_AREA)
|
||||
floor_seed = game_map.floor_index * 5
|
||||
for y in range(y0, y1):
|
||||
tiles_row = game_map.tiles[y]
|
||||
explored_row = game_map.explored[y]
|
||||
visible_row = game_map.visible[y]
|
||||
for x in range(x0, x1):
|
||||
if not explored_row[x]:
|
||||
continue
|
||||
variants = TILE_SPRITES[tiles_row[x]]
|
||||
variant = variants[(x * 7 + y * 13 + floor_seed) % len(variants)]
|
||||
topleft = (x * TILE_SIZE - ox, TOPBAR_HEIGHT + y * TILE_SIZE - oy)
|
||||
self.screen.blit(
|
||||
sprite_surface(variant, PIXELS_PER_CELL), topleft
|
||||
)
|
||||
if visible_row[x]:
|
||||
distance = math.hypot(x - px, y - py)
|
||||
darkening = light_tile(
|
||||
visible_light_alpha(distance, flicker), TILE_SIZE
|
||||
)
|
||||
else:
|
||||
darkening = light_tile(
|
||||
explored_light_alpha(), TILE_SIZE, explored_tint()
|
||||
)
|
||||
self.screen.blit(darkening, topleft)
|
||||
|
||||
self._draw_stairs(session, ox, oy, now_ms)
|
||||
for entity in game_map.entities:
|
||||
if not game_map.visible[entity.y][entity.x]:
|
||||
continue
|
||||
if isinstance(entity, Item):
|
||||
self._draw_sprite(
|
||||
entity.sprite_key, entity.position, ox, oy, now_ms, shadow=True
|
||||
)
|
||||
elif isinstance(entity, Enemy):
|
||||
self._draw_sprite(
|
||||
entity.sprite_key, entity.position, ox, oy, now_ms, shadow=True
|
||||
)
|
||||
if entity.hp < entity.max_hp:
|
||||
self._draw_hp_bar(entity, ox, oy)
|
||||
|
||||
hurt = now_ms - self._hurt_ms < ANIM_HIT_FLASH_MS
|
||||
weapon = player.equipped_weapon
|
||||
armor = player.equipped_armor
|
||||
boots = player.equipped_boots
|
||||
layers = player_layers(
|
||||
weapon.key if weapon else None,
|
||||
armor.key if armor else None,
|
||||
boots.key if boots else None,
|
||||
facing_up=self._facing_up,
|
||||
)
|
||||
lunge_x = lunge_y = 0
|
||||
attack_age = now_ms - self._attack_ms
|
||||
if 0 <= attack_age < ANIM_ATTACK_MS:
|
||||
decay = 1.0 - attack_age / ANIM_ATTACK_MS
|
||||
lunge_x = int(self._face_dx * 4 * decay)
|
||||
lunge_y = int(self._face_dy * 4 * decay)
|
||||
bob = int(round(1.5 * math.sin(now_ms / 380.0)))
|
||||
center_x = player.x * TILE_SIZE - ox + lunge_x
|
||||
center_y = TOPBAR_HEIGHT + player.y * TILE_SIZE - oy - bob
|
||||
shadow = _shadow(TILE_SIZE)
|
||||
self.screen.blit(
|
||||
shadow, (center_x + 2, center_y + TILE_SIZE - shadow.get_height() - 1)
|
||||
)
|
||||
self.screen.blit(
|
||||
sprite_surface(
|
||||
layers,
|
||||
PIXELS_PER_CELL,
|
||||
tint=(255, 255, 255) if hurt else None,
|
||||
flip_x=self._flip_x,
|
||||
),
|
||||
(center_x, center_y),
|
||||
)
|
||||
|
||||
self.particles.draw(self.screen, ox, oy - TOPBAR_HEIGHT)
|
||||
self.texts.draw(self.screen, self.font, ox, oy - TOPBAR_HEIGHT)
|
||||
self.screen.blit(vignette((MAP_AREA.width, MAP_AREA.height)), MAP_AREA.topleft)
|
||||
self.screen.set_clip(None)
|
||||
|
||||
def _draw_stairs(
|
||||
self, session: GameSession, ox: int, oy: int, now_ms: int
|
||||
) -> None:
|
||||
stairs = session.current_map.stairs_down
|
||||
if stairs is None or not session.current_map.explored[stairs[1]][stairs[0]]:
|
||||
return
|
||||
lit = bool(session.current_map.visible[stairs[1]][stairs[0]])
|
||||
center_x = stairs[0] * TILE_SIZE - ox + TILE_SIZE // 2
|
||||
center_y = TOPBAR_HEIGHT + stairs[1] * TILE_SIZE - oy + TILE_SIZE // 2
|
||||
glow = _glow(TILE_SIZE * 3, COLORS["stairs"])
|
||||
if lit:
|
||||
pulse = 0.5 + 0.5 * math.sin(now_ms / 240.0)
|
||||
glow.set_alpha(int(80 + 90 * pulse))
|
||||
if self._rng.random() < 0.08:
|
||||
self.particles.burst(center_x, center_y - 4, "stairs", 1)
|
||||
else:
|
||||
glow.set_alpha(55)
|
||||
self.screen.blit(
|
||||
glow, (center_x - glow.get_width() // 2, center_y - glow.get_height() // 2)
|
||||
)
|
||||
shadow = _shadow(TILE_SIZE)
|
||||
self.screen.blit(
|
||||
shadow,
|
||||
(stairs[0] * TILE_SIZE - ox + 2, center_y + TILE_SIZE // 2 - shadow.get_height()),
|
||||
)
|
||||
self.screen.blit(
|
||||
sprite_surface("stairs", PIXELS_PER_CELL),
|
||||
(stairs[0] * TILE_SIZE - ox, TOPBAR_HEIGHT + stairs[1] * TILE_SIZE - oy),
|
||||
)
|
||||
|
||||
def _draw_sprite(
|
||||
self,
|
||||
key: str,
|
||||
tile: tuple[int, int],
|
||||
ox: int,
|
||||
oy: int,
|
||||
now_ms: int,
|
||||
*,
|
||||
shadow: bool = False,
|
||||
) -> None:
|
||||
phase = (tile[0] * 13 + tile[1] * 7) * 40
|
||||
bob = int(round(1.5 * math.sin((now_ms + phase) / 380.0)))
|
||||
x = tile[0] * TILE_SIZE - ox
|
||||
y = TOPBAR_HEIGHT + tile[1] * TILE_SIZE - oy - bob
|
||||
if shadow:
|
||||
blob = _shadow(TILE_SIZE)
|
||||
self.screen.blit(blob, (x + 2, y + TILE_SIZE - blob.get_height() - 1))
|
||||
self.screen.blit(sprite_surface(key, PIXELS_PER_CELL), (x, y))
|
||||
|
||||
def _draw_hp_bar(self, enemy: Enemy, ox: int, oy: int) -> None:
|
||||
x = enemy.x * TILE_SIZE - ox + 1
|
||||
y = TOPBAR_HEIGHT + enemy.y * TILE_SIZE - oy - 4
|
||||
rect = pygame.Rect(x, y, TILE_SIZE - 2, 3)
|
||||
pygame.draw.rect(self.screen, (90, 20, 20), rect)
|
||||
fill = rect.copy()
|
||||
fill.width = max(1, int(rect.width * enemy.hp / enemy.max_hp))
|
||||
pygame.draw.rect(self.screen, (110, 210, 110), fill)
|
||||
|
||||
# ---- panels ----
|
||||
|
||||
def _panel(self, rect: pygame.Rect) -> None:
|
||||
pygame.draw.rect(self.screen, UI_PANEL, rect)
|
||||
pygame.draw.rect(self.screen, UI_BORDER, rect, 1)
|
||||
pygame.draw.line(
|
||||
self.screen, UI_BORDER_DARK, rect.bottomleft, rect.bottomright
|
||||
)
|
||||
pygame.draw.line(
|
||||
self.screen, UI_PANEL_LIGHT, (rect.x + 2, rect.y + 2), (rect.right - 3, rect.y + 2)
|
||||
)
|
||||
|
||||
def _bar(
|
||||
self, rect: pygame.Rect, fraction: float, fill: Color, low: Color | None = None
|
||||
) -> None:
|
||||
pygame.draw.rect(self.screen, (10, 10, 16), rect)
|
||||
color = fill
|
||||
if low is not None and fraction <= 0.3:
|
||||
color = low
|
||||
inner = rect.copy()
|
||||
inner.x += 1
|
||||
inner.y += 1
|
||||
inner.width = max(0, rect.width - 2)
|
||||
inner.height = rect.height - 2
|
||||
fill_rect = inner.copy()
|
||||
fill_rect.width = max(0, int(inner.width * min(1.0, max(0.0, fraction))))
|
||||
if fill_rect.width:
|
||||
pygame.draw.rect(self.screen, color, fill_rect)
|
||||
pygame.draw.rect(self.screen, UI_BORDER_DARK, rect, 1)
|
||||
|
||||
def _text(
|
||||
self,
|
||||
message: str,
|
||||
color: Color,
|
||||
position: tuple[int, int],
|
||||
font: pygame.font.Font | None = None,
|
||||
) -> None:
|
||||
self.screen.blit((font or self.font).render(message, False, color), position)
|
||||
|
||||
def _truncated(self, message: str, width: int) -> str:
|
||||
result = message
|
||||
while result and self.font.size(result)[0] > width:
|
||||
result = result[:-1]
|
||||
return result or " "
|
||||
|
||||
# ---- HUD ----
|
||||
|
||||
def _draw_topbar(self, session: GameSession) -> None:
|
||||
player = session.player
|
||||
self._panel(pygame.Rect(0, 0, WINDOW_WIDTH, TOPBAR_HEIGHT))
|
||||
|
||||
heart = sprite_surface("icon_heart", 2)
|
||||
self.screen.blit(heart, (10, 8))
|
||||
self._text(
|
||||
f"HP {player.hp}/{player.max_hp}", COLORS["text"], (30, 7)
|
||||
)
|
||||
self._bar(pygame.Rect(30, 26, 150, 10), player.hp / player.max_hp, HP_BAR, HP_BAR_LOW)
|
||||
|
||||
map_center = (WINDOW_WIDTH - SIDEBAR_WIDTH) // 2
|
||||
floor_label = f"Floor {session.current_floor + 1}/10"
|
||||
label_surface = self.font.render(floor_label, False, COLORS["stairs"])
|
||||
self.screen.blit(label_surface, (map_center - label_surface.get_width() // 2, 9))
|
||||
turn_label = f"Turn {session.turn}"
|
||||
turn_surface = self.font.render(turn_label, False, UI_TEXT_DIM)
|
||||
self.screen.blit(turn_surface, (map_center - turn_surface.get_width() // 2, 27))
|
||||
|
||||
star = sprite_surface("icon_star", 2)
|
||||
x = WINDOW_WIDTH - SIDEBAR_WIDTH - 210
|
||||
self.screen.blit(star, (x, 8))
|
||||
self._text(f"Lv {player.level}", COLORS["text"], (x + 20, 7))
|
||||
self._bar(pygame.Rect(x + 20, 26, 130, 10), _xp_fraction(player), XP_BAR)
|
||||
|
||||
def _draw_sidebar(self, session: GameSession) -> None:
|
||||
self._panel(SIDEBAR_AREA)
|
||||
self._text("Messages", COLORS["stairs"], (SIDEBAR_AREA.x + 12, SIDEBAR_AREA.y + 8))
|
||||
messages = session.log[-LOG_ROWS:]
|
||||
if not messages:
|
||||
messages = ["(the depths are quiet)"]
|
||||
width = SIDEBAR_AREA.width - 24
|
||||
for index, message in enumerate(messages):
|
||||
self._text(
|
||||
self._truncated(message, width),
|
||||
_log_color(message),
|
||||
(
|
||||
SIDEBAR_AREA.x + 12,
|
||||
SIDEBAR_AREA.y + 30 + (LOG_ROWS - len(messages) + index) * 22,
|
||||
),
|
||||
)
|
||||
|
||||
def _draw_bottombar(self, session: GameSession, muted: bool) -> None:
|
||||
player = session.player
|
||||
top = WINDOW_HEIGHT - BOTTOMBAR_HEIGHT
|
||||
self._panel(pygame.Rect(0, top, WINDOW_WIDTH, BOTTOMBAR_HEIGHT))
|
||||
|
||||
for index, (label, equipped) in enumerate(
|
||||
(
|
||||
("Weapon", player.equipped_weapon),
|
||||
("Armor", player.equipped_armor),
|
||||
("Boots", player.equipped_boots),
|
||||
)
|
||||
):
|
||||
x = 12 + index * 175
|
||||
box = pygame.Rect(x, top + 10, 26, 26)
|
||||
pygame.draw.rect(self.screen, (16, 16, 26), box)
|
||||
pygame.draw.rect(self.screen, UI_BORDER_DARK, box, 1)
|
||||
if equipped is not None:
|
||||
icon = sprite_surface(equipped.sprite_key, PIXELS_PER_CELL)
|
||||
self.screen.blit(
|
||||
icon, (box.centerx - icon.get_width() // 2, box.centery - icon.get_height() // 2)
|
||||
)
|
||||
else:
|
||||
self._text("-", UI_TEXT_DIM, (box.centerx - 3, box.centery - 8))
|
||||
self._text(label, UI_TEXT_DIM, (x + 32, top + 10))
|
||||
name = equipped.name if equipped is not None else "none"
|
||||
self._text(
|
||||
self._truncated(name, 130), COLORS["text"], (x + 32, top + 26)
|
||||
)
|
||||
|
||||
effects_x = 12 + 3 * 175
|
||||
for index, effect in enumerate(player.effects[-3:]):
|
||||
if effect.kind == "strength":
|
||||
label = f"STR +{effect.power_bonus} ({effect.turns_left})"
|
||||
else:
|
||||
label = f"INVISIBLE ({effect.turns_left})"
|
||||
self._text(label, LOG_ITEM, (effects_x, top + 10 + index * 17))
|
||||
|
||||
right = WINDOW_WIDTH - 14
|
||||
sound = sprite_surface("icon_sound_off" if muted else "icon_sound_on", 2)
|
||||
self.screen.blit(sound, (right - sound.get_width(), top + 38))
|
||||
hint_x = right
|
||||
if player.can_run:
|
||||
run = sprite_surface("icon_run", 2)
|
||||
hint_x -= run.get_width() + 6
|
||||
self.screen.blit(run, (hint_x, top + 34))
|
||||
hint_x -= self.font.size("HOLD")[0] + 2
|
||||
self._text("HOLD", LOG_ITEM, (hint_x, top + 36))
|
||||
hint_x -= 24
|
||||
if player.has_bow:
|
||||
bow = sprite_surface("w_bow", PIXELS_PER_CELL)
|
||||
hint_x -= bow.get_width() + 4
|
||||
self.screen.blit(bow, (hint_x, top + 32))
|
||||
self._text("B: Fire", LOG_ITEM, (hint_x - 62, top + 36))
|
||||
|
||||
def _draw_context_chip(self, session: GameSession) -> None:
|
||||
prompt = session.context_prompt()
|
||||
if prompt is None:
|
||||
return
|
||||
text_surface = self.font.render(prompt, False, COLORS["stairs"])
|
||||
chip = pygame.Rect(
|
||||
0,
|
||||
0,
|
||||
text_surface.get_width() + 28,
|
||||
text_surface.get_height() + 10,
|
||||
)
|
||||
chip.centerx = (WINDOW_WIDTH - SIDEBAR_WIDTH) // 2
|
||||
chip.bottom = WINDOW_HEIGHT - BOTTOMBAR_HEIGHT - 6
|
||||
self._panel(chip)
|
||||
pygame.draw.rect(self.screen, COLORS["stairs"], chip, 1)
|
||||
self.screen.blit(text_surface, (chip.x + 14, chip.y + 5))
|
||||
|
||||
# ---- full-screen states ----
|
||||
|
||||
def _draw_menu(self, session: GameSession, muted: bool) -> None:
|
||||
dragon = sprite_surface("ancient_dragon", 4)
|
||||
self.screen.blit(dragon, (WINDOW_WIDTH - 360, 130))
|
||||
self._text(GAME_TITLE, COLORS["stairs"], (64, 84), font=self.title_font)
|
||||
self._text("Descend. Slay the dragon below.", COLORS["text"], (68, 140))
|
||||
|
||||
entries = main_menu_entries(session)
|
||||
selected = session.menu_index % len(entries)
|
||||
for index, label in enumerate(entries):
|
||||
marker = "> " if index == selected else " "
|
||||
color = COLORS["stairs"] if index == selected else COLORS["text"]
|
||||
self._text(f"{marker}{label}", color, (84, 200 + index * 32))
|
||||
footer = f"Arrows: choose Enter: confirm M: sound {'off' if muted else 'on'}"
|
||||
self._text(footer, UI_TEXT_DIM, (64, WINDOW_HEIGHT - 40))
|
||||
|
||||
def _draw_end(self, session: GameSession) -> None:
|
||||
won = session.state == STATE_VICTORY
|
||||
if won:
|
||||
dragon = sprite_surface("ancient_dragon", 5)
|
||||
self.screen.blit(
|
||||
dragon,
|
||||
(WINDOW_WIDTH // 2 - dragon.get_width() // 2, 150),
|
||||
)
|
||||
self._text("VICTORY", COLORS["stairs"], (64, 60), font=self.title_font)
|
||||
self._text(
|
||||
"You slew the Ancient Dragon! You conquered Underdepths.",
|
||||
COLORS["text"],
|
||||
(68, 110),
|
||||
)
|
||||
else:
|
||||
skull = sprite_surface("icon_skull", 6)
|
||||
self.screen.blit(
|
||||
skull, (WINDOW_WIDTH // 2 - skull.get_width() // 2, 160)
|
||||
)
|
||||
self._text("YOU DIED", (220, 80, 80), (64, 60), font=self.title_font)
|
||||
if session.log:
|
||||
self._text(session.log[-1], COLORS["text"], (68, 110))
|
||||
self._text(END_PRESS_KEY, UI_TEXT_DIM, (64, WINDOW_HEIGHT - 40))
|
||||
|
||||
def _draw_overlay(self, session: GameSession) -> None:
|
||||
veil = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA)
|
||||
veil.fill((0, 0, 0, 150))
|
||||
self.screen.blit(veil, (0, 0))
|
||||
panel = OVERLAY_PANEL.copy()
|
||||
self._panel(panel)
|
||||
overlay = session.overlay
|
||||
|
||||
if overlay == OVERLAY_HELP:
|
||||
self._text("How to Play", COLORS["stairs"], (panel.x + 16, panel.y + 12), font=self.title_font)
|
||||
for index, line in enumerate(HOW_TO_PLAY):
|
||||
self._text(
|
||||
self._truncated(line, panel.width - 32),
|
||||
COLORS["text"],
|
||||
(panel.x + 16, panel.y + 58 + index * 24),
|
||||
)
|
||||
else:
|
||||
title = _OVERLAY_TITLES.get(overlay, overlay or "")
|
||||
self._text(title, COLORS["stairs"], (panel.x + 16, panel.y + 12), font=self.title_font)
|
||||
entries = overlay_entries(session)
|
||||
if entries:
|
||||
first = max(0, min(session.overlay_index - OVERLAY_ROWS // 2, len(entries) - OVERLAY_ROWS))
|
||||
for row, (name, detail) in enumerate(entries[first : first + OVERLAY_ROWS]):
|
||||
index = first + row
|
||||
y = panel.y + 58 + row * 26
|
||||
marker = ">" if index == session.overlay_index else " "
|
||||
letter = chr(ord("a") + index) if index < 26 else " "
|
||||
color = COLORS["text"] if index == session.overlay_index else UI_TEXT_DIM
|
||||
self._text(f"{marker} {letter}) {name}", color, (panel.x + 16, y))
|
||||
self._text(
|
||||
self._truncated(detail, panel.width - 260),
|
||||
LOG_INFO,
|
||||
(panel.x + 240, y),
|
||||
)
|
||||
else:
|
||||
self._text("(nothing here)", UI_TEXT_DIM, (panel.x + 16, panel.y + 58))
|
||||
self._text(
|
||||
"Esc: close Enter: use a-z: pick", UI_TEXT_DIM,
|
||||
(panel.x + 16, panel.bottom - 26),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run from the repo root: python -m render.renderer
|
||||
import os
|
||||
|
||||
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
|
||||
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
|
||||
renderer = Renderer(screen, pygame.font.SysFont(None, 16), pygame.font.SysFont(None, 32))
|
||||
|
||||
from data.constants import TILE_FLOOR
|
||||
from engine.game_state import STATE_PLAYING, new_game
|
||||
|
||||
def snapshot(state: GameSession) -> tuple:
|
||||
return (
|
||||
state.turn, state.current_floor, state.overlay, state.menu_index,
|
||||
state.player.hp, state.player.x, state.player.y,
|
||||
state.player.level, state.player.xp, len(state.player.inventory),
|
||||
len(state.log), len(state.current_map.entities) if state.dungeon else 0,
|
||||
)
|
||||
|
||||
# every reachable screen state renders without raising
|
||||
menu = GameSession.for_menu(save_available=True)
|
||||
renderer.draw(menu, muted=True, now_ms=0)
|
||||
menu.overlay = OVERLAY_HELP
|
||||
renderer.draw(menu, now_ms=16)
|
||||
menu.overlay = None
|
||||
menu.state = STATE_VICTORY
|
||||
renderer.draw(menu, now_ms=32)
|
||||
menu.state = STATE_DEAD
|
||||
renderer.draw(menu, now_ms=48)
|
||||
|
||||
session = new_game(seed=3)
|
||||
for overlay in (None, OVERLAY_HELP, OVERLAY_INVENTORY, OVERLAY_EQUIPMENT, OVERLAY_QUAFF, OVERLAY_READ):
|
||||
session.overlay = overlay
|
||||
renderer.draw(session, muted=False, dt=0.0, now_ms=64)
|
||||
session.overlay = None
|
||||
session.state = STATE_DEAD
|
||||
renderer.draw(session, now_ms=80)
|
||||
session.state = STATE_VICTORY
|
||||
renderer.draw(session, now_ms=96)
|
||||
session.state = STATE_PLAYING
|
||||
|
||||
# boss floor: no stairs, arena smaller than the viewport — must not crash
|
||||
session.current_floor = 9
|
||||
session.player.x, session.player.y = session.current_map.spawn
|
||||
session.refresh_fov()
|
||||
renderer.draw(session, dt=1.0, now_ms=112)
|
||||
renderer.draw(session, dt=1.0, now_ms=128)
|
||||
session.current_floor = 0
|
||||
|
||||
# rendering is pure: the session survives every draw untouched
|
||||
session.player.x, session.player.y = session.current_map.spawn
|
||||
session.refresh_fov()
|
||||
before = snapshot(session)
|
||||
renderer.draw(session, dt=1.0, now_ms=144)
|
||||
renderer.draw(session, dt=1.0, now_ms=160)
|
||||
assert snapshot(session) == before, "renderer mutated game state"
|
||||
|
||||
def region_colors(rect: pygame.Rect) -> set[tuple[int, int, int]]:
|
||||
return {
|
||||
screen.get_at((x, y))[:3]
|
||||
for x in range(rect.x, rect.right, 2)
|
||||
for y in range(rect.y, rect.bottom, 2)
|
||||
}
|
||||
|
||||
def tile_rect(tile: tuple[int, int], ox: int, oy: int) -> pygame.Rect:
|
||||
return pygame.Rect(
|
||||
tile[0] * TILE_SIZE - ox,
|
||||
TOPBAR_HEIGHT + tile[1] * TILE_SIZE - oy,
|
||||
TILE_SIZE,
|
||||
TILE_SIZE,
|
||||
)
|
||||
|
||||
# stairs visibly rendered: view them unobstructed from a neighboring tile
|
||||
game_map = session.current_map
|
||||
stairs = game_map.stairs_down
|
||||
assert stairs is not None
|
||||
floor_neighbors = [
|
||||
(stairs[0] + dx, stairs[1] + dy)
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))
|
||||
if game_map.tile_at(stairs[0] + dx, stairs[1] + dy) == TILE_FLOOR
|
||||
]
|
||||
assert floor_neighbors, "stairs must have a walkable neighbor"
|
||||
session.player.x, session.player.y = floor_neighbors[0]
|
||||
session.refresh_fov()
|
||||
renderer.draw(session, dt=1.0, now_ms=176)
|
||||
renderer.draw(session, dt=1.0, now_ms=192)
|
||||
ox, oy = renderer.camera.offset
|
||||
rect = tile_rect(stairs, ox, oy)
|
||||
assert rect.colliderect(MAP_AREA)
|
||||
stair_colors = region_colors(rect)
|
||||
assert any(
|
||||
r > 200 and g > 170 and b < 180 for r, g, b in stair_colors
|
||||
), f"stairs sprite not visibly rendered: {sorted(stair_colors)}"
|
||||
|
||||
# FOV lighting: unexplored is black; explored-not-visible is dimmer than visible
|
||||
def on_screen(tile: tuple[int, int]) -> bool:
|
||||
margin = 2
|
||||
return (
|
||||
ox // TILE_SIZE + margin <= tile[0] <= (ox + MAP_AREA.width) // TILE_SIZE - margin
|
||||
and oy // TILE_SIZE + margin <= tile[1] <= (oy + MAP_AREA.height) // TILE_SIZE - margin
|
||||
)
|
||||
|
||||
def brightness(tile: tuple[int, int]) -> int:
|
||||
x, y = tile_rect(tile, ox, oy).center
|
||||
r, g, b = screen.get_at((x, y))[:3]
|
||||
return r + g + b
|
||||
|
||||
unexplored = next(
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.explored)
|
||||
for x, seen in enumerate(row)
|
||||
if not seen and on_screen((x, y))
|
||||
)
|
||||
assert brightness(unexplored) < 45, "unexplored tiles must stay dark"
|
||||
from array import array as _array
|
||||
|
||||
for row in game_map.explored:
|
||||
row[:] = _array("b", b"\x01" * game_map.width)
|
||||
session.refresh_fov()
|
||||
renderer.draw(session, dt=1.0, now_ms=208)
|
||||
ox, oy = renderer.camera.offset
|
||||
player = session.player
|
||||
lit = min(
|
||||
(
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.visible)
|
||||
for x, seen in enumerate(row)
|
||||
if seen and game_map.tiles[y][x] == TILE_FLOOR and (x, y) != player.position
|
||||
),
|
||||
key=lambda tile: abs(tile[0] - player.x) + abs(tile[1] - player.y),
|
||||
)
|
||||
dim = next(
|
||||
(x, y)
|
||||
for y, row in enumerate(game_map.visible)
|
||||
for x, seen in enumerate(row)
|
||||
if not seen and game_map.tiles[y][x] == TILE_FLOOR and on_screen((x, y))
|
||||
)
|
||||
assert brightness(lit) > brightness(dim) + 25, "explored tiles must be dimmer"
|
||||
|
||||
# equipment visibly changes the on-screen player sprite
|
||||
bare = region_colors(tile_rect(player.position, ox, oy).clamp(MAP_AREA))
|
||||
categories = {
|
||||
"hunters_bow": "weapon",
|
||||
"plate_armor": "armor",
|
||||
"shoes_of_hermes": "boots",
|
||||
}
|
||||
for key, category in categories.items():
|
||||
item = Item(key=key, name=key, sprite_key=f"item_{key}", category=category)
|
||||
assert player.add_item(item)
|
||||
player.equip(item)
|
||||
assert player.equipped_weapon and player.equipped_armor and player.equipped_boots
|
||||
renderer.draw(session, dt=1.0, now_ms=224)
|
||||
ox, oy = renderer.camera.offset
|
||||
geared = region_colors(tile_rect(player.position, ox, oy).clamp(MAP_AREA))
|
||||
assert geared != bare and len(geared) >= len(bare), "equipment must change the sprite"
|
||||
|
||||
# HUD bars: HP fill at full health, XP fill once xp is gained
|
||||
assert HP_BAR in region_colors(pygame.Rect(0, 0, WINDOW_WIDTH, TOPBAR_HEIGHT))
|
||||
player.gain_xp(15)
|
||||
renderer.draw(session, dt=1.0, now_ms=240)
|
||||
assert XP_BAR in region_colors(pygame.Rect(0, 0, WINDOW_WIDTH, TOPBAR_HEIGHT))
|
||||
|
||||
# context prompt chip while standing on stairs
|
||||
session.player.x, session.player.y = stairs
|
||||
session.refresh_fov()
|
||||
renderer.draw(session, dt=1.0, now_ms=248)
|
||||
chip_strip = pygame.Rect(0, MAP_AREA.bottom - 30, MAP_AREA.width, 30)
|
||||
assert any(
|
||||
r > 200 and g > 160 and b < 140 for r, g, b in region_colors(chip_strip)
|
||||
), "context prompt must be visibly styled"
|
||||
|
||||
# juice: damage spawns particles, player damage shakes the screen
|
||||
goblin = Enemy(
|
||||
x=floor_neighbors[0][0], y=floor_neighbors[0][1],
|
||||
key="goblin", sprite_key="goblin", hp=15, max_hp=15,
|
||||
)
|
||||
game_map.entities.append(goblin)
|
||||
session.refresh_fov()
|
||||
renderer.draw(session, dt=1.0 / FPS, now_ms=256)
|
||||
assert not renderer.particles.items
|
||||
goblin.hp -= 7
|
||||
renderer.draw(session, dt=1.0 / FPS, now_ms=272)
|
||||
assert len(renderer.particles) > 0 and renderer.texts.items
|
||||
goblin.hp = 0
|
||||
game_map.entities.remove(goblin)
|
||||
player.hp -= 12
|
||||
renderer.draw(session, dt=1.0 / FPS, now_ms=288)
|
||||
assert renderer.shake.trauma > 0.0
|
||||
assert snapshot(session)[10] == len(session.log), "renderer must not write the log"
|
||||
|
||||
print("render.renderer self-check: PASS")
|
||||
Reference in new issue
Block a user