Compare commits

...
2 Commits
Author SHA1 Message Date
AlexKucera 2eb2a44fa9 (Underdepths) Pass 5 2026-08-14 09:46:04 +02:00
AlexKucera 4a549d002f (Underdepth) Prepare for Pass 5 2026-08-13 18:26:55 +02:00
54 changed files with 4465 additions and 4306 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
4
-14
View File
@@ -1,14 +0,0 @@
# Python
__pycache__/
*.py[cod]
*.egg-info/
# Runtime / build artifacts
save.json
.build_state
.pipeline.pid
logs/
.pi/
# OS
.DS_Store
+37
View File
@@ -0,0 +1,37 @@
[18:40:07] Underdepths pipeline starting. Last completed phase: 0
[18:40:07] ===== PHASE 1: build (attempt 1) =====
[18:40:07] dispatch: pi -p (<2064 chars>) TTL=3000s
[18:47:15] dispatch returned rc=0
[18:47:15] GATE --phase 1: PASS
[18:47:15] phase 1 COMPLETE (.build_state -> 1)
[18:47:15] ===== PHASE 2: build (attempt 1) =====
[18:47:15] dispatch: pi -p (<1021 chars>) TTL=3000s
[18:51:56] dispatch returned rc=0
[18:51:56] dispatch: pi -p (<954 chars>) TTL=3000s
[18:54:22] dispatch returned rc=0
[18:54:22] dispatch: pi -p (<1196 chars>) TTL=3000s
[18:56:18] dispatch returned rc=0
[18:56:18] dispatch: pi -p (<1090 chars>) TTL=3000s
[19:08:31] dispatch returned rc=0
[19:08:31] GATE --phase 2: PASS
[19:08:31] phase 2 COMPLETE (.build_state -> 2)
[19:08:31] ===== PHASE 3: build (attempt 1) =====
[19:08:31] dispatch: pi -p (<1969 chars>) TTL=3000s
[19:13:33] dispatch returned rc=0
[19:13:33] GATE --phase 3: PASS
[19:13:33] phase 3 COMPLETE (.build_state -> 3)
[19:13:33] ===== PHASE 4: build (attempt 1) =====
[19:13:33] dispatch: pi -p (<1210 chars>) TTL=3000s
[19:27:37] dispatch returned rc=0
[19:27:37] dispatch: pi -p (<1919 chars>) TTL=3000s
[20:08:13] dispatch returned rc=0
[20:08:13] dispatch: pi -p (<1633 chars>) TTL=3000s
[20:12:14] dispatch returned rc=0
[20:12:14] GATE --phase 4: PASS
[20:12:14] phase 4 COMPLETE (.build_state -> 4)
[20:12:14] ===== GOAL BACKSTOP =====
[20:12:15] GATE --goal: PASS
[20:12:15] ============================================================
[20:12:15] BUILD COMPLETE: all 4 phases + goal backstop PASS.
[20:12:15] Play it: python main.py
[20:12:15] ============================================================
+22
View File
@@ -0,0 +1,22 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
All edits landed cleanly. Phase 4c rendering is complete and verified.
## Summary
The render layer was already built by a prior dispatch and **passed the phase-4 gate**. I audited it against the full spec (not just the smoke minimum) and closed one genuine gap:
**Fixed — radial torch-light falloff** (explicitly required, a plan.md judging criterion; `effects.py`'s own docstring claimed it but the renderer did binary bright/dim):
- `render/effects.py`: added `torch_factor(dx,dy,radius)` → 1.0 at the bearer's feet, fading to ~0.55 at the sight rim (Chebyshev distance, matches FOV radius).
- `render/renderer.py`: visible tiles now dim by distance from the player; `_wall` now honors the factor (it previously ignored it); added normal "hit sparks" particle burst (plan.md lists it but only crit/death/level/pickup/stairs triggered before).
**Verified already-compliant:**
- `data/sprites.py` — distinct 14×15 grids for stairs, player, all 7 enemies, small_slime, items (per-kind tints).
- `render/sprites.py` — `get_sprite()` cached; stairs = `(245,215,70)` → R>120,G>100,B<110; self-check confirms 87 opaque/87 yellow pixels.
- `render/renderer.py` — blits the stairs sprite on **every** `stairs_down` tile (visible or explored); pure read of state.
- `render/camera.py` — smooth easing follow with map-bounds clamp.
- explored-dimmed tiles, wall occlusion (via FOV), vignette, pooled particles, screen-shake.
**Gate result:** `phase 4: PASS` (incl. stairs-rendered pixel assertion + dragon-kill→victory), `phases 1–3: PASS`, `goal: PASS` — no regressions.
Skipped: torch flicker animation — falloff already sells the torch feel; add only if it reads too static.
+1
View File
@@ -0,0 +1 @@
49976 49976
+40
View File
@@ -0,0 +1,40 @@
[18:40:07] Underdepths pipeline starting. Last completed phase: 0
[18:40:07] ===== PHASE 1: build (attempt 1) =====
[18:40:07] dispatch: pi -p (<2064 chars>) TTL=3000s
[18:47:15] dispatch returned rc=0
[18:47:15] GATE --phase 1: PASS
[18:47:15] phase 1 COMPLETE (.build_state -> 1)
[18:47:15] ===== PHASE 2: build (attempt 1) =====
[18:47:15] dispatch: pi -p (<1021 chars>) TTL=3000s
[18:51:56] dispatch returned rc=0
orchestrate.sh: line 174: blocked: command not found
[18:51:56] dispatch: pi -p (<954 chars>) TTL=3000s
[18:54:22] dispatch returned rc=0
[18:54:22] dispatch: pi -p (<1196 chars>) TTL=3000s
[18:56:18] dispatch returned rc=0
orchestrate.sh: line 199: visible: command not found
[18:56:18] dispatch: pi -p (<1090 chars>) TTL=3000s
[19:08:31] dispatch returned rc=0
[19:08:31] GATE --phase 2: PASS
[19:08:31] phase 2 COMPLETE (.build_state -> 2)
[19:08:31] ===== PHASE 3: build (attempt 1) =====
[19:08:31] dispatch: pi -p (<1969 chars>) TTL=3000s
[19:13:33] dispatch returned rc=0
[19:13:33] GATE --phase 3: PASS
[19:13:33] phase 3 COMPLETE (.build_state -> 3)
[19:13:33] ===== PHASE 4: build (attempt 1) =====
orchestrate.sh: line 242: visible: command not found
[19:13:33] dispatch: pi -p (<1210 chars>) TTL=3000s
[19:27:37] dispatch returned rc=0
[19:27:37] dispatch: pi -p (<1919 chars>) TTL=3000s
[20:08:13] dispatch returned rc=0
[20:08:13] dispatch: pi -p (<1633 chars>) TTL=3000s
[20:12:14] dispatch returned rc=0
[20:12:14] GATE --phase 4: PASS
[20:12:14] phase 4 COMPLETE (.build_state -> 4)
[20:12:14] ===== GOAL BACKSTOP =====
[20:12:15] GATE --goal: PASS
[20:12:15] ============================================================
[20:12:15] BUILD COMPLETE: all 4 phases + goal backstop PASS.
[20:12:15] Play it: python main.py
[20:12:15] ============================================================
+1
View File
@@ -0,0 +1 @@
37587 37587
+1
View File
@@ -0,0 +1 @@
68252 68252
+2
View File
@@ -0,0 +1,2 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
+38
View File
@@ -0,0 +1,38 @@
Underdepths (pygame roguelike) had a visual polish pass. Most criteria now PASS
(textured walls/floor, visible yellow stairs, prominent dragon, radial torch
lighting with dim explored tiles). A second visual review flagged these REMAINING
gaps. Fix ONLY these, in render/* and data/sprites.py and data/constants.py. Do
NOT change game logic or signatures; keep all gates green.
Viewport is 960x600 at TILE=20. Procedural pixel-art via pygame.draw only.
1. SKELETON ARCHER and ORC WARRIOR look too similar — make them unmistakably
DIFFERENT silhouettes:
- skeleton_archer: white/gray BONES (ribcage, skull), a DRAWN BOW, a quiver,
glowing eye sockets. Thin, skeletal.
- orc_warrior: dark-red HULKING brute, heavy plate shoulder, big TUSKS, a
large blade/club. Broad, muscular.
They must not read as the same shape recolored.
2. GREEN SLIME and ITEM sprites are too tiny. Make them fill ~75-85% of the tile
and be clearly shaped:
- green_slime: a glossy domed BLOB with a highlight, two eyes, a drip.
- items: weapon = a clear BLADE/sword shape; armor = a SHIELD/breastplate;
potion = a FLASK; scroll = a rolled PAPER. Each with its category accent
color dominant. No more 2-pixel specks.
3. ENTITY DROP-SHADOWS are barely perceptible. Make the soft ellipse shadow under
every entity + the stairs clearly visible (darker, slightly larger) so sprites
feel grounded.
4. EQUIPMENT ICONS in the bottom bar are unclear. Draw crisp pixel-art icons: a
weapon icon next to the equipped weapon name, an armor icon next to the armor
name. Make them read at a glance.
5. Make sure the top bar clearly shows "Floor N/10" and the bottom bar shows the
context prompt. When the player STANDS ON the stairs, the prompt must read
"Press F to descend"; when standing on an item, "Press G to pick up <name>".
After changes run: python tests/smoke.py (all phases + goal MUST still PASS).
The goal: every enemy type + item reads as a distinct, recognizable shape at a
glance, sprites are grounded by visible shadows, and the UI icons are crisp.
+8
View File
@@ -0,0 +1,8 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
+57
View File
@@ -0,0 +1,57 @@
Underdepths (a pygame roguelike) is FUNCTIONALLY COMPLETE — every gate in
tests/smoke.py passes. But a visual review of rendered frames judged the art
UNFINISHED. Your job: improve RENDERING ONLY. Do NOT change game logic and do
NOT break any gate. Read these files first: render/renderer.py, render/sprites.py,
data/sprites.py, render/effects.py, data/constants.py, plan.md (Rendering section).
The viewport is 960x600 at TILE=20 (48x30 tiles visible). All art is procedural
pixel-art via pygame.draw — NO external image/font/audio files.
Fix these SPECIFIC problems found by visual review:
1. UI IS TEXT-ONLY AND UNPOLISHED. plan.md requires a polished UI:
- HP bar must have a HEART ICON (pixel-art heart) next to a green/red fill.
- Equipment slots must be drawn as PIXEL-ART ICONS (a tiny weapon icon, an
armor icon), not just text names.
- Add a small icon for XP/level (e.g. a star) by the XP bar.
- The message log must be FULLY on-screen, never clipped, and color-coded:
combat/hit white, damage-taken/death red, level-up green, items/stairs
yellow. Verify text isn't running off the panel.
- Keep the bordered panels and the styled "Press G to pick up <name>" /
"Press F to descend" context prompt.
2. ITEM SPRITES ARE GENERIC SPECKS. Make weapon/armor/potion/scroll sprites
DISTINCT and recognizable at TILE=20: a sword/blade shape, a shield, a
flask, a scroll — each with its category accent color (yellow/blue/red/cyan)
as the dominant hue, not a 2-pixel dot.
3. LIGHTING READS AS A HARSH CUTOFF INTO NEAR-TOTAL BLACK. Smooth it:
- Make the radial torch falloff clearly visible: bright core graduating to
dim at the sight rim, NOT a hard disc edge.
- Explored-but-currently-unseen tiles MUST be clearly VISIBLE but dimmed
(dark blue-gray), so the player sees the remembered layout — they must NOT
be near-black. Unexplored tiles can be black.
- Walls must occlude light (derived from FOV).
- The vignette must be SUBTLE — do not crush the screen edges to black.
The screen in an explored area must look like a lit dungeon, not empty
black space.
4. THE BOSS DRAGON MUST BE VISUALLY PROMINENT. It is the Ancient Dragon —
draw it LARGER than one tile (e.g. a 2x2 sprite) and unmistakably a big
multi-hue red dragon: horns, spread wings, scales, fangs. It should read
as a boss at a glance.
5. Confirm every one of the 7 enemies + player + items + stairs is a DISTINCT
shape, not a recolor of one blob. (rat / goblin / skeleton_archer /
orc_warrior / wraith / green_slime / ancient_dragon / small_slime.)
HARD CONSTRAINTS:
- Procedural pixel-art via pygame.draw only; no external assets.
- Do NOT change signatures in engine/, entities/, ai/, data/enemies.py,
data/items.py. You may edit render/*, data/sprites.py, data/constants.py.
- After your changes, run: python tests/smoke.py
ALL phases (1-4) + goal MUST still print PASS. Fix anything you broke.
When done, the game should look like a polished retro roguelike: a player by
glowing yellow stairs with an item and a goblin nearby, torch-lit with dimmed
remembered rooms, a heart-icon HP bar, equipment icons, and a Press G/F prompt.
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Comprehensive demo frame: equipped player, all 7 enemies, combat log, on stairs.
Gives vision a fair read and serves as the recording reference pose."""
from __future__ import annotations
import os, sys
os.environ.setdefault("SDL_VIDEODRIVER", "dummy"); os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); sys.path.insert(0, ROOT)
import pygame; pygame.init()
from main import new_game, SCREEN_W, SCREEN_H
from data import enemies as E, items as I
from engine import actions as act
from render.renderer import Renderer
from render.camera import Camera
SHOTS = os.path.join(ROOT, ".shots"); os.makedirs(SHOTS, exist_ok=True)
R = Renderer(); cam = Camera()
def reveal(gm):
for y in range(gm.height):
for x in range(gm.width): gm.explored[y][x] = True
def shoot(s, name):
surf = pygame.Surface((SCREEN_W, SCREEN_H)); cam.reset((s.player.x, s.player.y))
off = cam.offset_for((SCREEN_W, SCREEN_H), (s.player.x, s.player.y)); R.render(surf, s, camera_xy=off)
p = os.path.join(SHOTS, name); pygame.image.save(surf, p); print(" saved", p)
s = new_game(seed=5); gm = s.dungeon[3]; s.current_floor = 3; reveal(gm)
# gear up so equipment ICONS are populated
s.player.equip(I.make_item("war_hammer", 0, 0))
s.player.equip(I.make_item("plate_armor", 0, 0))
# place player ON the stairs (-> "Press F to descend") with an item adjacent
sx, sy = gm.stairs_down
s.player.x, s.player.y = sx, sy
# sprinkle all 7 enemy kinds in a cluster around the player (within sight)
kinds = ["rat","goblin","skeleton_archer","orc_warrior","wraith","green_slime","small_slime"]
spots = [(2,0),(-2,0),(0,2),(0,-2),(2,2),(-2,-2),(2,-2)]
for k,(dx,dy) in zip(kinds, spots):
tx, ty = sx+dx, sy+dy
if 0<=tx<gm.width and 0<=ty<gm.height and gm.walkable(tx,ty):
gm.entities.append(E.make_enemy(k, tx, ty))
# an item on a near tile
for (ix,iy) in [(sx+1,sy),(sx-1,sy),(sx,sy+1)]:
if gm.walkable(ix,iy): gm.entities.append(I.make_item("healing_potion", ix, iy)); break
# generate colored combat log lines by attacking a couple of adjacent enemies
for _ in range(4): act.apply_input(s, "left")
act.apply_input(s, "right")
# return the player ONTO the stairs so the F-prompt + translucent stairs-peek show
s.player.x, s.player.y = sx, sy
shoot(s, "demo_full.png")
print(f" equipped: {s.player.equipped_weapon.name}, {s.player.equipped_armor.name}; log lines: {len(s.log)}")
print(" last log:", s.log[-3:] if s.log else [])
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Headless playthrough + screenshot capture for visual verification.
Exercises the full action surface (move, fight, pickup, descend, save/load)
and renders frames to .shots/*.png for vision-delegate inspection.
"""
from __future__ import annotations
import os, sys, random, traceback
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
import pygame
pygame.init()
from main import new_game, SCREEN_W, SCREEN_H
from engine import actions as act
from engine import serializers as ser
from engine import combat as cb
from data import enemies as E, items as I
from render.renderer import Renderer
from render.camera import Camera
SHOTS = os.path.join(ROOT, ".shots")
os.makedirs(SHOTS, exist_ok=True)
renderer = Renderer()
camera = Camera()
def shoot(session, name):
surf = pygame.Surface((SCREEN_W, SCREEN_H))
camera.reset((session.player.x, session.player.y))
off = camera.offset_for((SCREEN_W, SCREEN_H), (session.player.x, session.player.y))
renderer.render(surf, session, camera_xy=off)
path = os.path.join(SHOTS, name)
pygame.image.save(surf, path)
print(f" saved {path}")
steps_ok = 0
steps_fail = []
def step(desc, fn):
global steps_ok
try:
fn(); steps_ok += 1
except Exception as ex:
steps_fail.append(f"{desc}: {ex!r}")
print("=== headless playthrough ===")
s = new_game(seed=2024)
print(f"new_game: floor {s.current_floor}, state={s.state}, "
f"player hp {s.player.hp}/{s.player.max_hp} lv{s.player.level}")
# explore floor 0
step("move around floor 0", lambda: [act.apply_input(s, d) for d in
("right","right","down","down","right","up","left","down","down","right","right")])
shoot(s, "floor0_explore.png")
# force a combat frame: place a goblin next to the player and attack it
def combat():
g = E.make_enemy("goblin", s.player.x + 1, s.player.y)
s.dungeon[s.current_floor].entities.append(g)
act.apply_input(s, "right") # move into goblin = attack
combat(); steps_ok += 1
shoot(s, "floor0_combat.png")
print(f" after combat: log tail = {s.log[-2:] if s.log else []}")
# pickup: drop an item under player, press g
def pickup():
it = I.make_item("healing_potion", s.player.x, s.player.y)
s.dungeon[s.current_floor].entities.append(it)
act.apply_input(s, "g")
step("pickup g", pickup)
print(f" inventory size = {len(s.player.inventory)}")
# descend a few floors
def descend():
for _ in range(3):
gm = s.dungeon[s.current_floor]
if gm.stairs_down:
s.player.x, s.player.y = gm.stairs_down
act.apply_input(s, "f")
descend(); steps_ok += 1
print(f" descended to floor {s.current_floor}")
shoot(s, f"floor{s.current_floor}_descended.png")
# save -> load -> continue (round trip)
def saveload():
d = ser.session_to_dict(s)
s2 = ser.session_from_dict(d)
assert ser.session_to_dict(s2) == d, "save/load not stable"
step("save/load round-trip", saveload)
# floor 9 dragon arena frame
def dragon():
s.current_floor = 9
camera.reset((s.player.x, s.player.y))
dragon(); steps_ok += 1
shoot(s, "floor9_dragon.png")
# how-to-play / mute / menu keys must not crash
for k in ("?","m","i","e","escape"):
step(f"key {k!r}", (lambda kk=k: act.apply_input(s, kk)))
print(f"\n=== {steps_ok} steps OK, {len(steps_fail)} failed ===")
for f in steps_fail:
print(" FAIL:", f)
print("\nshots:", sorted(os.listdir(SHOTS)))
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Fairly-framed screenshots for visual verification of the polish pass.
Reveals each floor (so explored-dim vs torch-lit is visible) and positions the
player within sight of the key features (stairs, item+enemy, dragon).
"""
from __future__ import annotations
import os, sys
os.environ.setdefault("SDL_VIDEODRIVER", "dummy"); os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); sys.path.insert(0, ROOT)
import pygame; pygame.init()
from main import new_game, SCREEN_W, SCREEN_H
from data import enemies as E, items as I
from engine.fov import compute_fov
from data.constants import SIGHT_RADIUS
from render.renderer import Renderer
from render.camera import Camera
SHOTS = os.path.join(ROOT, ".shots"); os.makedirs(SHOTS, exist_ok=True)
R = Renderer(); cam = Camera()
def reveal(gm):
for y in range(gm.height):
for x in range(gm.width):
gm.explored[y][x] = True
def shoot(s, name):
surf = pygame.Surface((SCREEN_W, SCREEN_H))
cam.reset((s.player.x, s.player.y))
off = cam.offset_for((SCREEN_W, SCREEN_H), (s.player.x, s.player.y))
R.render(surf, s, camera_xy=off)
p = os.path.join(SHOTS, name); pygame.image.save(surf, p); print(" saved", p)
# --- Scene 1: floor 0, player next to stairs, an item at feet, a goblin nearby ---
s = new_game(seed=7); gm = s.dungeon[0]; reveal(gm)
sx, sy = gm.stairs_down
# stand on a walkable neighbor of stairs
for (nx, ny) in ((sx-1, sy), (sx+1, sy), (sx, sy-1), (sx, sy+1)):
if gm.walkable(nx, ny): s.player.x, s.player.y = nx, ny; break
# place item under player + a goblin 2 tiles away
gm.entities.append(I.make_item("short_sword", s.player.x, s.player.y))
gx, gy = s.player.x, s.player.y
for (ex, ey) in ((gx+2, gy), (gx-2, gy), (gx, gy+2)):
if gm.walkable(ex, ey): gm.entities.append(E.make_enemy("goblin", ex, ey)); break
shoot(s, "scene_stairs.png")
# --- Scene 2: a mid floor with a couple of distinct enemy types + an item ---
s2 = new_game(seed=21); gm2 = s2.dungeon[4]; reveal(gm2); s2.current_floor = 4
# center player on a walkable tile near middle
px = py = 0
for y in range(gm2.height):
for x in range(gm2.width):
if gm2.walkable(x, y): px, py = x, y; break
if px: break
s2.player.x, s2.player.y = px, py
for i, (k, dx, dy) in enumerate([("skeleton_archer",2,0),("orc_warrior",-2,0),("wraith",0,2),("green_slime",0,-2)]):
tx, ty = px+dx, py+dy
if gm2.walkable(tx, ty): gm2.entities.append(E.make_enemy(k, tx, ty))
gm2.entities.append(I.make_item("healing_potion", px, py))
shoot(s2, "scene_enemies.png")
# --- Scene 3: floor 9 dragon, player within sight radius ---
s3 = new_game(seed=3); gm3 = s3.dungeon[9]; reveal(gm3); s3.current_floor = 9
dragon = next((e for e in gm3.entities if getattr(e, "kind","")=="ancient_dragon"), None)
if dragon is None:
dragon = E.make_enemy("ancient_dragon", 10, 7); gm3.entities.append(dragon)
# place player within sight radius of the dragon
for (dx, dy) in [(-5,0),(-6,0),(-4,0),(0,-5),(0,-6)]:
tx, ty = dragon.x+dx, dragon.y+dy
if 0<=tx<gm3.width and 0<=ty<gm3.height and gm3.walkable(tx, ty):
s3.player.x, s3.player.y = tx, ty; break
shoot(s3, "scene_dragon.png")
print("done.")
Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+10 -2
View File
@@ -82,7 +82,8 @@ Write `orchestrate.sh`, `tests/smoke.py` (stub with phase functions), and
- Build: `data/constants.py`, `entities/entity.py`, `engine/map_gen.py`, - Build: `data/constants.py`, `entities/entity.py`, `engine/map_gen.py`,
`entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop. `entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop.
- Gate: generate 5 maps, assert each has ≥3 rooms, all rooms reachable via - Gate: generate 5 maps, assert each has ≥3 rooms, all rooms reachable via
flood fill, no room overlaps. Print ASCII render to confirm. flood fill, no room overlaps, and (floors 0–8) `stairs_down` is a floor tile
reachable from the spawn room. Print ASCII render to confirm.
**Phase 2 — Core Systems (parallelizable):** **Phase 2 — Core Systems (parallelizable):**
FOV, A*, and combat are independent. Dispatch them as separate `pi -p` FOV, A*, and combat are independent. Dispatch them as separate `pi -p`
@@ -108,7 +109,7 @@ calls that can run concurrently:
- A visible How to Play screen, contextual pickup/stairs prompts, and simple generated sound effects with graceful silent fallback - A visible How to Play screen, contextual pickup/stairs prompts, and simple generated sound effects with graceful silent fallback
- Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering (`data/sprites.py`, `render/sprites.py`, `render/effects.py`) - Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering (`data/sprites.py`, `render/sprites.py`, `render/effects.py`)
- This phase is large — split it into sequential sub-dispatches (e.g. 4a persistence+audio, 4b actions+render+sprites+main) that run BEFORE the single phase gate, if one dispatch cannot finish within the TTL - This phase is large — split it into sequential sub-dispatches (e.g. 4a persistence+audio, 4b actions+render+sprites+main) that run BEFORE the single phase gate, if one dispatch cannot finish within the TTL
- Gate: save → load → assert state equality; all menu states reachable; simulated `g` pickup and `f` descent work; audio-disabled mode does not crash. - Gate: save → load → assert state equality; all menu states reachable; simulated `g` pickup and `f` descent work; audio-disabled mode does not crash; **stairs are visibly rendered** (the renderer blits a distinct stairs sprite on `stairs_down` — assert this, since invisible stairs make the game unwinnable).
### Goal backstop ### Goal backstop
@@ -173,6 +174,13 @@ When you believe you are done:
`Press F to descend`. Automated tests must exercise both actions. `Press F to descend`. Automated tests must exercise both actions.
- **Systems that don't actually work.** If A* is there but enemies walk into - **Systems that don't actually work.** If A* is there but enemies walk into
walls, the judge sees that. Each system must be genuinely functional. walls, the judge sees that. Each system must be genuinely functional.
- **Unwinnable floors.** Every floor 0–8 MUST have stairs on a floor tile
reachable from spawn AND visibly rendered (the `>` staircase) so the player
can find it and press `f` to descend. Floor 9 is won by slaying a dragon the
player can actually damage with floor-9 gear. Missing, unreachable, or
invisible stairs — or an unkillable boss — fail the build. The previous build
shipped stairs that existed in the map data but were never drawn, so the game
had no visible way down: do not repeat this.
- **Stopping early.** The prompt must produce a complete game. If you finish - **Stopping early.** The prompt must produce a complete game. If you finish
a phase and the acceptance criteria aren't all met, keep building. a phase and the acceptance criteria aren't all met, keep building.
- **Flat colored-square art.** Entities/tiles drawn as plain rectangles read as - **Flat colored-square art.** Entities/tiles drawn as plain rectangles read as
+362 -224
View File
@@ -1,254 +1,392 @@
"""Enemy AI: per-turn behavior dispatch (plan.md §5). """Enemy AI dispatch.
Visibility is symmetric — an enemy sees the player exactly when the player's FOV Each turn the game loop calls ``act_enemy`` once per living enemy, after the
covers the enemy's tile (and the player is not invisible). Slow enemies player acts. The function mutates ``enemy.x``/``enemy.y``/``enemy.last_known_pos``
(speed > 1) act every Nth turn via act_counter. Enemies never stack: other in place and, when adjacent, resolves a melee attack through ``engine.combat``.
blocking entities are treated as impassable. It never raises on valid game state.
""" """
from __future__ import annotations from __future__ import annotations
import random import random
from typing import Any
from engine import combat, game_state, pathfinding from engine.combat import roll_attack
from engine.map_gen import is_walkable from engine.pathfinding import find_path
from entities.enemy import Enemy from entities.enemy import Enemy
# 4-connected movement on the tile grid.
_DIRS: tuple[tuple[int, int], ...] = ((1, 0), (-1, 0), (0, 1), (0, -1))
def take_enemy_turn(enemy, session, rng=None) -> None: # Behavior tuning. Plan-defined, kept here as named constants (not magic numbers).
r = rng if rng is not None else (getattr(session, "rng", None) or random) _WANDER_MOVE_CHANCE: float = 0.5 # wander: 50/50 move vs wait
floor = session.dungeon[session.current_floor] _FLEE_HP_FRACTION: float = 0.30 # flee when hp below 30% of max
player = session.player _RANGED_KITE_DIST: int = 2 # ranged kites when player within this Chebyshev dist
_RANGED_RANGE: int = 8 # ranged can shoot out to this Chebyshev dist
_RANGED_DIST_PENALTY: float = 0.03 # per-tile hit-chance drop past the kite band
_HIT_BASE: float = 0.70
_HIT_STEP: float = 0.05
_HIT_FLOOR: float = 0.10
_HIT_CEIL: float = 0.95
if enemy.speed > 1: # ponytail: per-enemy turn parity for the "phase" behavior (acts every 2 turns).
enemy.act_counter += 1 # Enemy is a slots dataclass we may not extend here, so bookkeep in a dict keyed
if enemy.act_counter % enemy.speed != 0: # by id(). Ceiling: grows with the enemy count of one run; id() reuse after GC is
return # harmless (worst case a freshly-spawned wraith skips one extra turn). Clear on
# floor change if memory ever matters.
_PHASE_TICK: dict[int, int] = {}
player_visible = _can_see_player(floor, enemy, player)
if player_visible:
enemy.last_known_pos = (player.x, player.y)
bh = enemy.behavior def act_enemy(
if bh == "wander": enemy: Any,
_wander(enemy, floor, session, r) game_map: Any,
elif bh == "chase": player: Any,
_chase(enemy, floor, session, r, player_visible) visible: set[tuple[int, int]],
elif bh == "flee": rng: random.Random = random,
_flee(enemy, floor, session, r, player_visible) ) -> None:
elif bh == "ranged": """Resolve one enemy turn, dispatching on ``enemy.behavior``."""
_ranged(enemy, floor, session, r, player_visible) behavior = getattr(enemy, "behavior", "wander")
elif bh == "phase": if behavior == "wander":
_phase(enemy, floor, session, r, player_visible) _wander(enemy, game_map, rng)
elif bh == "split": elif behavior == "phase":
_chase(enemy, floor, session, r, player_visible) _phase(enemy, game_map, player, visible, rng)
elif behavior == "ranged":
_ranged(enemy, game_map, player, visible, rng)
elif behavior == "flee":
if _is_low_hp(enemy):
_flee(enemy, game_map, player, visible, rng)
else: else:
_wander(enemy, floor, session, r) _chase(enemy, game_map, player, visible, rng)
# --- helpers ---------------------------------------------------------------- #
def _can_see_player(floor, enemy, player) -> bool:
if getattr(player, "invisible", False):
return False
if 0 <= enemy.x < floor.width and 0 <= enemy.y < floor.height:
return floor.visible[enemy.y][enemy.x]
return False
def _occupied(floor, session, pos, ignore) -> bool:
px, py = pos
for e in floor.entities:
if e is ignore:
continue
if e.x == px and e.y == py and getattr(e, "blocks", True):
return True
return session.player.x == px and session.player.y == py
def _blocked_set(floor, ignore) -> set:
return {(e.x, e.y) for e in floor.entities
if e is not ignore and getattr(e, "blocks", True)}
def _manhattan(a, b) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def _step_to(enemy, pos, floor, session) -> bool:
if pos is None or not is_walkable(floor, pos[0], pos[1]):
return False
if _occupied(floor, session, pos, enemy):
return False
enemy.x, enemy.y = pos
return True
def _wander(enemy, floor, session, r) -> None:
if r.random() < 0.5:
return # wait
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
r.shuffle(dirs)
for dx, dy in dirs:
nx, ny = enemy.x + dx, enemy.y + dy
if is_walkable(floor, nx, ny) and not _occupied(floor, session, (nx, ny), enemy):
enemy.x, enemy.y = nx, ny
return
def _chase(enemy, floor, session, r, player_visible) -> None:
player = session.player
target = (player.x, player.y) if player_visible else enemy.last_known_pos
if target is None:
_wander(enemy, floor, session, r)
return
if player_visible and _manhattan((enemy.x, enemy.y), (player.x, player.y)) <= 1:
combat.attack(enemy, player, rng=r, log=session.log)
return
blocked = _blocked_set(floor, enemy)
path = pathfinding.astar(floor, (enemy.x, enemy.y), target, blocked=blocked)
if path and len(path) >= 2:
_step_to(enemy, path[1], floor, session)
else: else:
_wander(enemy, floor, session, r) # "chase" and "split" both pursue the player; splitting on death is a
# separate event handled by split_on_death (called from the death path).
_chase(enemy, game_map, player, visible, rng)
def _flee(enemy, floor, session, r, player_visible) -> None: # --------------------------------------------------------------------- behaviors
player = session.player
if player_visible and enemy.hp < enemy.max_hp * 0.3:
_move_away(enemy, floor, session, r, (player.x, player.y))
else:
_chase(enemy, floor, session, r, player_visible)
def _wander(enemy: Any, game_map: Any, rng: random.Random) -> None:
def _ranged(enemy, floor, session, r, player_visible) -> None: if rng.random() < _WANDER_MOVE_CHANCE:
player = session.player
if not player_visible:
_wander(enemy, floor, session, r)
return return
dist = _manhattan((enemy.x, enemy.y), (player.x, player.y)) moves = [d for d in _DIRS if game_map.walkable(enemy.x + d[0], enemy.y + d[1])]
if dist > 3: if not moves:
if enemy.ranged_power > 0:
_ranged_attack(enemy, player, r, session.log)
else:
_chase(enemy, floor, session, r, player_visible)
elif dist <= 2:
_move_away(enemy, floor, session, r, (player.x, player.y))
else:
combat.attack(enemy, player, rng=r, log=session.log)
def _phase(enemy, floor, session, r, player_visible) -> None:
player = session.player
if player_visible and _manhattan((enemy.x, enemy.y), (player.x, player.y)) <= 1:
combat.attack(enemy, player, rng=r, log=session.log)
return return
if not player_visible: dx, dy = rng.choice(moves)
_wander(enemy, floor, session, r) enemy.x += dx
enemy.y += dy
def _chase(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
px, py = player.x, player.y
player_seen = (px, py) in visible
if player_seen:
enemy.last_known_pos = (px, py)
if _chebyshev(enemy.x, enemy.y, px, py) <= 1:
_melee(enemy, player, rng)
return return
# Drift toward the player through walls, but never onto another entity. blockers = _enemy_blockers(game_map, enemy, player)
best = None _step_toward(enemy, game_map, (px, py), blockers)
best_d = _manhattan((enemy.x, enemy.y), (player.x, player.y)) return
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): # Player out of sight: move toward the last known position, else wander.
nx, ny = enemy.x + dx, enemy.y + dy lkp = enemy.last_known_pos
if not (0 <= nx < floor.width and 0 <= ny < floor.height): if lkp is None or (enemy.x, enemy.y) == lkp:
continue enemy.last_known_pos = None
if _occupied(floor, session, (nx, ny), enemy): _wander(enemy, game_map, rng)
continue return
d = _manhattan((nx, ny), (player.x, player.y)) blockers = _enemy_blockers(game_map, enemy, player)
if d < best_d: _step_toward(enemy, game_map, lkp, blockers)
best_d = d
best = (nx, ny)
if best is not None:
enemy.x, enemy.y = best
def _move_away(enemy, floor, session, r, threat) -> None: def _flee(
best = None enemy: Any,
best_d = _manhattan((enemy.x, enemy.y), threat) game_map: Any,
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)] player: Any,
r.shuffle(dirs) visible: set[tuple[int, int]],
for dx, dy in dirs: rng: random.Random,
nx, ny = enemy.x + dx, enemy.y + dy ) -> None:
if not is_walkable(floor, nx, ny) or _occupied(floor, session, (nx, ny), enemy): px, py = player.x, player.y
continue if (px, py) not in visible:
d = _manhattan((nx, ny), threat) _wander(enemy, game_map, rng)
if d > best_d: return
best_d = d _step_away(enemy, game_map, px, py)
best = (nx, ny)
if best is not None:
enemy.x, enemy.y = best
else:
_wander(enemy, floor, session, r)
def _ranged_attack(enemy, player, r, log) -> None: def _ranged(
acc = getattr(enemy, "accuracy", 0) enemy: Any,
eva = getattr(player, "evasion", 0) game_map: Any,
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05)) player: Any,
rp = enemy.ranged_power visible: set[tuple[int, int]],
if r.random() < hit_chance: rng: random.Random,
player.hp -= rp ) -> None:
if log is not None: px, py = player.x, player.y
log.append(f"{enemy.name} shoots you for {rp} damage!") if (px, py) not in visible:
elif log is not None: _wander(enemy, game_map, rng)
log.append(f"{enemy.name}'s shot misses you") return
dist = _chebyshev(enemy.x, enemy.y, px, py)
if dist <= _RANGED_KITE_DIST:
_step_away(enemy, game_map, px, py) # kite: open distance
return
if dist <= _RANGED_RANGE:
_ranged_attack(enemy, player, dist, rng)
# --------------------------------------------------------------------------- # def _phase(
# Death resolution enemy: Any,
# --------------------------------------------------------------------------- # game_map: Any,
def on_death(enemy, session) -> None: player: Any,
"""Resolve an enemy's death: split, award XP, remove corpse, check victory. visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
# Acts every 2 turns: skip on odd ticks.
key = id(enemy)
_PHASE_TICK[key] = _PHASE_TICK.get(key, 0) + 1
if _PHASE_TICK[key] % 2 == 1:
return
px, py = player.x, player.y
if _chebyshev(enemy.x, enemy.y, px, py) <= 1:
_melee(enemy, player, rng)
return
_step_through_walls(enemy, game_map, px, py)
Called by actions whenever a swing drops an enemy to <= 0 HP. A green slime
that can still split spawns two smaller, non-splitting copies before the # ------------------------------------------------------------------- death hook
corpse is removed. Slaying the dragon wins the run.
def split_on_death(enemy: Any, game_map: Any) -> list[Enemy]:
"""Spawn two smaller copies when a splitting enemy dies.
Called by the death/combat path (not by ``act_enemy``). Returns the freshly
spawned small enemies (0, 1, or 2 depending on free adjacent tiles); the
caller appends them to the floor's entities. Spawned copies never split.
""" """
player = session.player if not getattr(enemy, "can_split", False) or getattr(enemy, "hp", 1) > 0:
floor = session.dungeon[session.current_floor] return []
spawned: list[Enemy] = []
session.log.append(f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)") for dx, dy in ((1, 0), (-1, 0)):
if getattr(enemy, "can_split", False) and "slime" in enemy.name.lower():
_spawn_split_slimes(enemy, floor, session)
player.gain_xp(enemy.xp_value)
for msg in player.pending_log:
session.log.append(msg)
player.pending_log.clear()
if enemy in floor.entities:
floor.entities.remove(enemy)
if "dragon" in enemy.name.lower():
game_state.mark_victory(session)
session.log.append("You slew the Ancient Dragon! You conquered Underdepths.")
def _spawn_split_slimes(enemy, floor, session) -> None:
"""Spawn up to two half-size, non-splitting Small Slimes around the corpse."""
half_hp = max(1, enemy.max_hp // 2)
half_pow = max(1, enemy.power // 2)
spawned = 0
# The corpse's own tile is a candidate: it is freed the instant we remove
# the corpse below, so a surrounded slime can still split in place.
for dx, dy in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1),
(1, 1), (-1, 1), (1, -1), (-1, -1)):
if spawned >= 2:
break
nx, ny = enemy.x + dx, enemy.y + dy nx, ny = enemy.x + dx, enemy.y + dy
if not is_walkable(floor, nx, ny): if game_map.in_bounds(nx, ny) and game_map.walkable(nx, ny):
continue spawned.append(_small_copy(enemy, nx, ny))
if _occupied(floor, session, (nx, ny), enemy): return spawned
continue
floor.entities.append(Enemy(
x=nx, y=ny, name="Small Slime", sprite_key="small_slime", def _small_copy(parent: Any, x: int, y: int) -> Enemy:
hp=half_hp, max_hp=half_hp, power=half_pow, armor=enemy.armor, half_hp = max(1, int(parent.max_hp) // 2)
accuracy=enemy.accuracy, evasion=enemy.evasion, return Enemy(
crit_chance=enemy.crit_chance, speed=1, x=x, y=y,
behavior="split", xp_value=max(1, enemy.xp_value // 2), kind="small_slime", name="Small Slime",
hp=half_hp, max_hp=half_hp,
power=max(1, int(parent.power) // 2),
armor=int(getattr(parent, "armor", 0)),
accuracy=int(getattr(parent, "accuracy", 4)),
evasion=int(getattr(parent, "evasion", 0)),
crit_chance=float(getattr(parent, "crit_chance", 0.0)),
speed=int(getattr(parent, "speed", 1)),
behavior="chase",
xp_value=max(1, int(parent.xp_value) // 2),
last_known_pos=None,
can_split=False, can_split=False,
)) sprite_key="small_slime",
spawned += 1 )
if spawned:
session.log.append(f"The {enemy.name} splits into {spawned} smaller slimes!")
# ------------------------------------------------------------------ primitives
def _melee(enemy: Any, player: Any, rng: random.Random) -> None:
roll = roll_attack(enemy, player, rng)
if roll.hit and roll.damage > 0:
player.hp = max(0, int(player.hp) - roll.damage)
def _ranged_attack(enemy: Any, player: Any, dist: int, rng: random.Random) -> None:
ranged_power = int(getattr(enemy, "ranged_power", None) or enemy.power)
hit_chance = _HIT_BASE + (int(getattr(enemy, "accuracy", 4)) -
int(getattr(player, "evasion", 0))) * _HIT_STEP
hit_chance -= max(0, dist - _RANGED_KITE_DIST) * _RANGED_DIST_PENALTY
hit_chance = max(_HIT_FLOOR, min(_HIT_CEIL, hit_chance))
if rng.random() < hit_chance:
player.hp = max(0, int(player.hp) - ranged_power)
def _step_toward(
enemy: Any,
game_map: Any,
goal: tuple[int, int],
blockers: frozenset[tuple[int, int]] = frozenset(),
) -> bool:
"""Move one tile toward ``goal``. Returns True if the enemy moved.
Primary route is A* over walkable tiles. When A* reports no route (the goal
is genuinely walled off on a well-formed map) we try a walkable greedy step
and otherwise wait. If the map is so malformed that walkability itself raises
(never on a real GameMap, whose ``in_bounds`` guards the tile index), we fall
back to a direct beeline — boundary handling so a bad map can't crash the AI.
"""
# Detect a malformed map by probing the goal's walkability: on a well-formed
# GameMap this is a plain bool; if it raises, the goal sits outside the tile
# grid and A* cannot run, so beeline directly (boundary handling only).
try:
goal_walkable = game_map.walkable(*goal)
except Exception:
return _beeline(enemy, game_map, goal)
if not goal_walkable:
# Goal itself is non-walkable (e.g. target standing in a wall): close in
# via walkable tiles, else wait.
return _greedy_step(enemy, game_map, goal)
try:
path = find_path(game_map, (enemy.x, enemy.y), goal, blocked=blockers)
except Exception:
return _beeline(enemy, game_map, goal)
if path:
nx, ny = path[0]
enemy.x, enemy.y = nx, ny
return True
# Genuinely unreachable on an otherwise valid map: shuffle toward it or wait.
return _greedy_step(enemy, game_map, goal)
def _beeline(enemy: Any, game_map: Any, goal: tuple[int, int]) -> bool:
"""Direct step toward ``goal`` considering only bounds (no walkability).
Only reached when the pathfinder could not even evaluate the map. On a
well-formed map this is unreachable; it exists purely so a malformed map is
a degraded experience, not a crash.
"""
gx, gy = goal
best: tuple[int, int] | None = None
best_d: int | None = None
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if (nx, ny) == goal or not game_map.in_bounds(nx, ny):
continue
d = abs(nx - gx) + abs(ny - gy)
if best_d is None or d < best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
return True
return False
def _greedy_step(enemy: Any, game_map: Any, goal: tuple[int, int]) -> bool:
gx, gy = goal
best: tuple[int, int] | None = None
best_d: int | None = None
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if (nx, ny) == goal or not game_map.walkable(nx, ny):
continue
d = abs(nx - gx) + abs(ny - gy)
if best_d is None or d < best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
return True
return False
def _step_away(enemy: Any, game_map: Any, px: int, py: int) -> None:
"""Move one walkable tile that maximizes distance from (px, py)."""
best: tuple[int, int] | None = None
best_d = -1
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if not game_map.walkable(nx, ny):
continue
d = abs(nx - px) + abs(ny - py)
if d > best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
def _step_through_walls(enemy: Any, game_map: Any, px: int, py: int) -> None:
"""Phase toward the player ignoring walls (may enter wall tiles).
Prefers a floor tile at equal distance so the wraith only phases when it must.
"""
cands: list[tuple[int, int, int, int]] = []
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if not game_map.in_bounds(nx, ny) or (nx, ny) == (px, py):
continue
d = abs(nx - px) + abs(ny - py)
cands.append((d, 0 if game_map.walkable(nx, ny) else 1, nx, ny))
if cands:
cands.sort()
_, _, nx, ny = cands[0]
enemy.x, enemy.y = nx, ny
def _enemy_blockers(game_map: Any, self_enemy: Any, player: Any) -> frozenset[tuple[int, int]]:
"""Tiles occupied by other blocking entities (so enemies don't stack).
Excludes the acting enemy and the player (the player is the chase goal and is
handled by the adjacency check, not by blocking).
"""
blockers: set[tuple[int, int]] = set()
for e in getattr(game_map, "entities", []) or ():
if e is self_enemy or e is player:
continue
if not getattr(e, "blocks", True):
continue
blockers.add((e.x, e.y))
return frozenset(blockers)
def _is_low_hp(enemy: Any) -> bool:
max_hp = int(getattr(enemy, "max_hp", 1)) or 1
return int(getattr(enemy, "hp", max_hp)) < max_hp * _FLEE_HP_FRACTION
def _chebyshev(ax: int, ay: int, bx: int, by: int) -> int:
return max(abs(ax - bx), abs(ay - by))
if __name__ == "__main__":
# Self-check: a chase enemy reaches an adjacent player along an open corridor.
class _StubMap:
def __init__(self, tiles):
self.tiles = tiles
self.height = len(tiles)
self.width = len(tiles[0]) if tiles else 0
def in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def walkable(self, x, y):
return self.in_bounds(x, y) and self.tiles[y][x] == 1
class _E:
def __init__(self, x, y):
self.x, self.y = x, y
self.behavior = "chase"
self.hp = self.max_hp = 99
self.power, self.speed, self.kind = 4, 1, "goblin"
self.last_known_pos = None
self.accuracy, self.evasion, self.armor, self.crit_chance = 4, 1, 1, 0.0
class _P:
x = 18
y = 2
hp = 50
max_hp = 50
accuracy = 5
evasion = 2
armor = 0
crit_chance = 0.1
gm = _StubMap([[1 if y == 2 else 0 for _ in range(20)] for y in range(5)])
e = _E(2, 2)
p = _P()
vis = {(x, 2) for x in range(20)}
r = random.Random(5)
for _ in range(40):
act_enemy(e, gm, p, vis, r)
if max(abs(e.x - p.x), abs(e.y - p.y)) <= 1:
break
assert max(abs(e.x - p.x), abs(e.y - p.y)) <= 1, e.x
print("behaviors self-check: OK")
-207
View File
@@ -1,207 +0,0 @@
Underdepths build pipeline — state=0 ttl=3000s retries=3
===================================================================
>>> phase1-foundation (attempt 1/3) 09:29:04
===================================================================
gate: python3 tests/smoke.py --phase 1
##########.....###########.......###############################################
##########.....##############.##################################################
##########.....##############.##################################################
##########....................................##################################
##########.....##############################.##################################
##########.....##############################.##################################
##########.....##############################.##################################
############.################################.##################################
############.################################.##################################
############.################################.##################################
############.################################.##################################
############.############################.........##############################
############.############################.........##############################
############.############################.........##############################
############.############################.........##############################
############.############################.........##############################
############.############################.........##############################
############.############################.........##############################
############.#########........##################################################
############.#########........##################################################
############..................##################################################
############.#########........##################################################
############.###################################################################
############.###################################################################
############.###################################################################
############.###################################################################
########..........##############################################################
########..........##############################################################
########..........##############################################################
########..........##############################################################
########..........##############################################################
########..........##############################################################
################################################################################
################################################################################
phase 1: PASS
<<< phase1-foundation PASS
===================================================================
>>> phase2-core (attempt 1/3) 09:43:45
===================================================================
gate: python3 tests/smoke.py --phase 2
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat result dict has keys
ok: combat has hits and misses
ok: combat damage non-negative
ok: combat damage in plausible range
ok: combat crits occurred (>=1 in 1000)
ok: armor reduces average damage
ok: chase goblin closed distance along corridor
phase 2: PASS
<<< phase2-core PASS
===================================================================
>>> phase3-content (attempt 1/3) 10:25:40
===================================================================
gate: python3 tests/smoke.py --phase 3
ok: wraith armor
ok: wraith xp_value
ok: wraith behavior
ok: wraith speed
ok: green_slime hp/max_hp
ok: green_slime power
ok: green_slime armor
ok: green_slime xp_value
ok: green_slime behavior
ok: green_slime speed
ok: ancient_dragon hp/max_hp
ok: ancient_dragon power
ok: ancient_dragon armor
ok: ancient_dragon xp_value
ok: ancient_dragon speed
ok: dragon ranged_power/breath present
ok: Short Sword +4 power
ok: Battle Axe +7 power
ok: Leather Armor +2 armor
ok: Plate Armor +7 armor
ok: War Hammer +10 power
ok: level starts at 1
ok: 30 XP -> level 2
ok: level 2 max_hp 60 (+10)
ok: level 2 power 5 (+1)
ok: level 2 fully healed
ok: reaches level 10
ok: Healing Potion +30 HP (capped)
ok: Strength Potion +5 power while active
ok: Strength Potion sets a timer effect
ok: Invisibility Potion makes player hidden
ok: Scroll of Mapping reveals floor
ok: Scroll of Teleport moves player
ok: slime split produces smaller slimes
phase 3: PASS
<<< phase3-content PASS
===================================================================
>>> phase4a-persist (attempt 1/3) 11:02:00
===================================================================
gate: python3 -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK
COMPILE_OK
<<< phase4a-persist PASS
===================================================================
>>> phase4b-visuals (attempt 1/3) 11:12:32
===================================================================
./orchestrate.sh: line 51: 2851 Killed: 9 timeout --kill-after=30 "$TTL" pi -p -a --name "$name" @plan.md "$full_prompt" > "$LOG_DIR/${name}.attempt${attempt}.log" 2>&1
! dispatch timed out (rc=137); tail of log:
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
gate: python3 -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK
COMPILE_OK
<<< phase4b-visuals PASS
===================================================================
>>> phase4-gate (attempt 1/3) 12:24:38
===================================================================
gate: python3 tests/smoke.py --phase 4
===== phase 4 =====
ok: save/load player equal
ok: save/load ten floors present
ok: save/load dungeon (sans visible) equal
ok: save/load turn/log preserved
ok: serialized dict omits visible
ok: pickup returns True on item present
ok: pickup adds to inventory
ok: pickup removes item from floor
ok: descend returns True on stairs
ok: descend advances floor
ok: audio play all events without raising
ok: audio mute toggles
ok: main(max_frames=1) runs headless
phase 4: PASS
<<< phase4-gate PASS
===================================================================
>>> goal-backstop (attempt 1/3) 12:24:52
===================================================================
gate: python3 tests/smoke.py --goal
ok: Leather Armor +2 armor
ok: Plate Armor +7 armor
ok: War Hammer +10 power
ok: level starts at 1
ok: 30 XP -> level 2
ok: level 2 max_hp 60 (+10)
ok: level 2 power 5 (+1)
ok: level 2 fully healed
ok: reaches level 10
ok: Healing Potion +30 HP (capped)
ok: Strength Potion +5 power while active
ok: Strength Potion sets a timer effect
ok: Invisibility Potion makes player hidden
ok: Scroll of Mapping reveals floor
ok: Scroll of Teleport moves player
ok: slime split produces smaller slimes
[goal] phase 3 criteria: PASS
ok: save/load player equal
ok: save/load ten floors present
ok: save/load dungeon (sans visible) equal
ok: save/load turn/log preserved
ok: serialized dict omits visible
ok: pickup returns True on item present
ok: pickup adds to inventory
ok: pickup removes item from floor
ok: descend returns True on stairs
ok: descend advances floor
ok: audio play all events without raising
ok: audio mute toggles
ok: main(max_frames=1) runs headless
[goal] phase 4 criteria: PASS
ok: goal: 120-turn scripted playthrough no crash
ok: goal: GameSession state field supports dead/victory/menu/playing
[goal] ALL ACCEPTANCE CRITERIA PASS
<<< goal-backstop PASS
===================================================================
BUILD COMPLETE — all phase gates + goal backstop PASS.
Play it: python3 main.py
Verify: python3 tests/smoke.py --goal
===================================================================
+112 -119
View File
@@ -1,133 +1,126 @@
"""Tuning constants, palettes, and progression tables for Underdepths. """Tuning constants, palettes, and progression tables for Underdepths.
All magic numbers live here so balancing is a one-file edit. No magic numbers in game logic — everything tunable lives here.
""" """
from __future__ import annotations from __future__ import annotations
# --- Grid / viewport -------------------------------------------------------- # # --- viewport / grid -------------------------------------------------------
TILE: int = 24 TILE: int = 20
MAP_WIDTH: int = 80 MAP_W: int = 80
MAP_HEIGHT: int = 50 MAP_H: int = 50
SIGHT_RADIUS: int = 8 SIGHT_RADIUS: int = 8
FLOORS: int = 10 FLOOR_COUNT: int = 10
MAX_LEVEL: int = 10
# --- Base palette / colors -------------------------------------------------- # # --- dungeon generation ----------------------------------------------------
# Tiles ROOM_MIN_W: int = 4
COLORS: dict[str, tuple[int, int, int]] = { ROOM_MIN_H: int = 4
"wall_visible": (60, 60, 70), ROOM_MAX_W: int = 10
"wall_explored": (30, 30, 35), ROOM_MAX_H: int = 8
"floor_visible": (40, 35, 30), BSP_MIN_HALF: int = 12 # min half-axis before a region may split
"floor_explored": (20, 18, 15), BSP_LEAVES_MIN: int = 6
"void": (6, 5, 8), BSP_LEAVES_MAX: int = 10
# entity accent hues (dominant sprite color per type) BOSS_ROOM_W: int = 20
"player": (225, 225, 235), BOSS_ROOM_H: int = 15
"rat": (150, 110, 75), WALL: int = 0
"goblin": (95, 165, 75), FLOOR: int = 1
"skeleton_archer": (215, 215, 205),
"orc_warrior": (155, 55, 50), # --- player base stats (plan.md Core Data Model) ---------------------------
"wraith": (160, 95, 205), PLAYER_BASE: dict = {
"green_slime": (125, 205, 85), "hp": 50,
"ancient_dragon": (205, 65, 50), "max_hp": 50,
# feature / item accents "power": 4,
"stairs": (240, 220, 80), "armor": 0,
"weapon": (240, 220, 80), # yellow "accuracy": 5,
"armor": (95, 145, 230), # blue "evasion": 2,
"potion": (220, 85, 85), # red "crit_chance": 0.10,
"scroll": (95, 220, 220), # cyan "speed": 1,
# UI }
"ui_border": (150, 130, 95),
"ui_border_hi": (200, 180, 130), # --- leveling: (cumulative_xp_to_next_level, hp_gain, power_gain) ----------
"ui_bg": (15, 12, 18), LEVEL_TABLE: list[tuple[int, int, int]] = [
"ui_panel": (24, 20, 28), (30, 10, 1),
"hp_full": (190, 55, 60), (70, 10, 1),
"hp_back": (60, 22, 24), (140, 10, 1),
"xp_full": (90, 170, 230), (250, 10, 1),
"xp_back": (26, 34, 48), (400, 15, 2),
"log_combat": (235, 235, 235), (600, 15, 2),
"log_damage": (225, 90, 90), (850, 15, 2),
"log_levelup": (130, 225, 100), (1150, 15, 2),
"log_item": (240, 220, 90), (1500, 20, 3),
"log_miss": (170, 170, 170), ]
"prompt": (245, 235, 180), LEVEL_CAP: int = 10
POTION_HEAL: int = 30
STRENGTH_POTION_POWER: int = 5
# --- named colors (plan.md Colors & viewport) ------------------------------
COLORS: dict = {
"bg": (8, 7, 10),
"wall_visible": (66, 66, 80),
"wall_top": (96, 96, 112),
"wall_explored": (44, 48, 64), # remembered walls: visible dark blue-gray
"floor_visible": (72, 62, 50),
"floor_explored": (36, 40, 56), # remembered floors: visible dark blue-gray
"stairs": (245, 215, 70),
"player": (235, 235, 235),
"rat": (140, 100, 70),
"goblin": (90, 160, 70),
"skeleton_archer": (210, 210, 200),
"orc_warrior": (150, 50, 50),
"wraith": (150, 90, 200),
"green_slime": (120, 200, 90),
"ancient_dragon": (200, 60, 50),
"item_weapon": (240, 200, 80),
"item_armor": (90, 140, 220),
"item_potion": (220, 80, 80),
"item_scroll": (90, 220, 220),
"hp_full": (80, 200, 80),
"hp_empty": (60, 30, 30),
"xp_bar": (90, 160, 230),
"panel": (18, 16, 22),
"panel_border": (90, 85, 110),
"text": (220, 220, 220),
"text_dim": (150, 145, 140),
"shadow": (0, 0, 0), "shadow": (0, 0, 0),
"highlight": (255, 255, 255), "heart": (224, 64, 74), # HP heart icon
"star": (255, 214, 92), # XP / level star icon
"log_bad": (236, 96, 96), # damage / death log
"log_good": (120, 222, 116), # level-up / victory log
"empty_slot": (52, 50, 64),
} }
# Sprite-palette keys (single chars in data/sprites.py grids) -> RGB. # --- single-char palette keys for procedural pixel-art grids (render layer) -
# "." is transparent. Keys are intentionally short; phase 4 sprites use them. PALETTE: dict = {
PALETTE: dict[str, tuple[int, int, int] | None] = {
".": None, # transparent ".": None, # transparent
"K": (18, 14, 20), # dark outline " ": None,
"k": (40, 32, 38), # soft outline "K": (16, 14, 20), # darkest outline
"W": (95, 85, 72), # warm light shade (stone/skin highlight) "k": (40, 36, 46), # outline shade
"s": (62, 56, 50), # mid shade (stone/skin) "W": (60, 60, 70), # wall base
"h": (38, 33, 30), # dark shade (stone/skin shadow) "w": (82, 82, 96), # wall highlight (top edge)
"d": (24, 20, 18), # deep shadow "e": (30, 30, 35), # explored wall
"w": (245, 245, 250), # white (bone / sclera) "F": (40, 35, 30), # floor base
"g": (120, 200, 80), # green (goblin / slime) "f": (54, 48, 41), # floor fleck
"G": (70, 150, 55), # dark green "E": (20, 18, 15), # explored floor
"r": (200, 60, 50), # red (orc / dragon) "s": (245, 215, 70), # stairs / yellow glow
"R": (140, 35, 30), # dark red "y": (240, 200, 80), # yellow accent (weapons)
"p": (160, 95, 205), # purple (wraith) "b": (90, 140, 220), # blue accent (armor)
"P": (95, 55, 140), # dark purple "r": (200, 60, 50), # red accent (dragon / potions)
"b": (95, 145, 230), # blue (armor / magic) "g": (90, 200, 90), # green accent (goblin / slime)
"y": (240, 220, 80), # yellow (stairs / weapon / gold) "p": (150, 90, 200), # purple accent (wraith)
"o": (225, 150, 60), # orange (fire / accents) "c": (210, 210, 200), # bone white (skeleton)
"c": (95, 220, 220), # cyan (scroll) "C": (90, 220, 220), # cyan accent (scrolls)
"m": (220, 85, 85), # muted red (potion) "G": (172, 178, 190), # steel (weapon blades)
"e": (90, 230, 120), # eye glow green "o": (140, 100, 70), # brown (rat)
"E": (120, 200, 255), # eye glow blue "n": (150, 50, 50), # dark red (orc)
"h": (235, 235, 235), # light / player highlight
"H": (180, 60, 60), # blood / damage flash
"q": (170, 245, 245), # eerie glow (skeleton eye sockets)
} }
# --- Progression: XP and level-up tables (plan.md §7) ----------------------- # # --- combat tuning (plan.md Systems) ---------------------------------------
# Cumulative XP required to REACH a given level (keyed by level 1..10). HIT_BASE: float = 0.70
XP_THRESHOLDS: dict[int, int] = { HIT_PER_POINT: float = 0.05
1: 0, 2: 30, 3: 70, 4: 140, 5: 250, HIT_FLOOR: float = 0.10
6: 400, 7: 600, 8: 850, 9: 1150, 10: 1500, HIT_CEIL: float = 0.95
}
# Stat gains applied when leveling INTO a given level.
LEVEL_HP_GAIN: dict[int, int] = {2: 10, 3: 10, 4: 10, 5: 10, 6: 15, 7: 15, 8: 15, 9: 15, 10: 20}
LEVEL_POWER_GAIN: dict[int, int] = {2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 3}
# --- Player base stats (plan.md §7) ---------------------------------------- # # --- persistence ----------------------------------------------------------------
PLAYER_BASE: dict[str, int | float] = { SAVE_FILE: str = "save.json"
"hp": 50, "max_hp": 50, "power": 4, "armor": 0,
"accuracy": 5, "evasion": 2, "crit_chance": 0.10, "speed": 1,
}
# --- Per-floor spawn distribution (plan.md §1) ----------------------------- #
# (min, max) enemies / items per floor. Floor 9 is the boss arena.
ENEMY_COUNT: dict[int, tuple[int, int]] = {
0: (3, 4), 1: (3, 4),
2: (4, 6), 3: (4, 6),
4: (5, 7), 5: (5, 7),
6: (6, 8), 7: (6, 8),
8: (7, 9),
}
ITEM_COUNT: dict[int, tuple[int, int]] = {
0: (2, 3), 1: (2, 3),
2: (2, 3), 3: (2, 3),
4: (3, 4), 5: (3, 4),
6: (3, 4), 7: (3, 4),
8: (4, 5), 9: (2, 2),
}
# --- Key bindings (plan.md Controls) --------------------------------------- #
# Map of intent -> pygame key constant names; resolved in phase 4 input layer.
KEY_BINDINGS: dict[str, list[str]] = {
"move_n": ["K_UP", "K_k"],
"move_s": ["K_DOWN", "K_j"],
"move_w": ["K_LEFT", "K_h"],
"move_e": ["K_RIGHT", "K_l"],
"pickup": ["K_g"],
"inventory": ["K_i"],
"equipment": ["K_e"],
"quaff": ["K_q"],
"read": ["K_r"],
"descend": ["K_f"],
"save_quit": ["K_s"],
"help": ["K_QUESTION"],
"mute": ["K_m"],
"cancel": ["K_ESCAPE"],
}
+60
View File
@@ -0,0 +1,60 @@
"""Enemy roster per plan.md Enemy Roster + factory."""
from __future__ import annotations
from entities.enemy import Enemy
# Each entry is the full stat block. ``power`` is melee power; ranged enemies
# also carry ``ranged_power`` (read by the ranged AI). green_slime.can_split is
# True so its death spawns two Small Slimes; small_slime never splits.
ENEMY_DEFS: dict[str, dict] = {
"rat": dict(
name="Rat", hp=8, power=3, armor=0, speed=1,
behavior="wander", xp_value=5, accuracy=4, evasion=2, crit_chance=0.0,
),
"goblin": dict(
name="Goblin", hp=15, power=5, armor=1, speed=1,
behavior="chase", xp_value=12, accuracy=4, evasion=1, crit_chance=0.0,
),
"skeleton_archer": dict(
name="Skeleton Archer", hp=12, power=4, armor=1, speed=1,
behavior="ranged", xp_value=15, accuracy=5, evasion=1, crit_chance=0.05,
ranged_power=6,
),
"orc_warrior": dict(
name="Orc Warrior", hp=30, power=8, armor=3, speed=1,
behavior="flee", xp_value=25, accuracy=4, evasion=0, crit_chance=0.0,
),
"wraith": dict(
name="Wraith", hp=20, power=10, armor=0, speed=2,
behavior="phase", xp_value=30, accuracy=5, evasion=3, crit_chance=0.10,
),
"green_slime": dict(
name="Green Slime", hp=18, power=5, armor=1, speed=1,
behavior="split", xp_value=18, accuracy=4, evasion=0, crit_chance=0.0,
can_split=True,
),
"ancient_dragon": dict(
name="Ancient Dragon", hp=120, power=15, armor=8, speed=1,
behavior="chase", xp_value=200, accuracy=6, evasion=0, crit_chance=0.15,
),
"small_slime": dict(
name="Small Slime", hp=9, power=3, armor=0, speed=1,
behavior="chase", xp_value=9, accuracy=4, evasion=0, crit_chance=0.0,
can_split=False,
),
}
def make_enemy(kind: str, x: int, y: int) -> Enemy:
d = ENEMY_DEFS[kind]
return Enemy(
x=x, y=y, kind=kind, name=d["name"],
hp=d["hp"], max_hp=d["hp"],
power=d["power"], armor=d["armor"],
accuracy=d["accuracy"], evasion=d["evasion"],
crit_chance=d["crit_chance"], speed=d["speed"],
behavior=d["behavior"], xp_value=d["xp_value"],
last_known_pos=None, can_split=d.get("can_split", False),
ranged_power=d.get("ranged_power", 0),
sprite_key=kind,
)
+31
View File
@@ -0,0 +1,31 @@
"""Item catalog per plan.md Item catalog + factory."""
from __future__ import annotations
from entities.item import Item
# stats keys: weapons -> power (+opt crit_chance/evasion mods); armor -> armor
# (+opt evasion mod); potions/scrolls -> effect payload consumed by actions.
ITEM_DEFS: dict[str, dict] = {
"rusty_dagger": dict(name="Rusty Dagger", category="weapon", stats={"power": 2}),
"short_sword": dict(name="Short Sword", category="weapon", stats={"power": 4}),
"battle_axe": dict(name="Battle Axe", category="weapon", stats={"power": 7}),
"war_hammer": dict(name="War Hammer", category="weapon", stats={"power": 10, "crit_chance": -0.05}),
"leather_armor": dict(name="Leather Armor", category="armor", stats={"armor": 2}),
"chain_mail": dict(name="Chain Mail", category="armor", stats={"armor": 4}),
"plate_armor": dict(name="Plate Armor", category="armor", stats={"armor": 7, "evasion": -0.10}),
"healing_potion": dict(name="Healing Potion", category="potion", stats={"effect": "heal", "amount": 30}),
"strength_potion": dict(name="Strength Potion", category="potion", stats={"effect": "strength", "power": 5, "duration": 20}),
"invisibility_potion":dict(name="Invisibility Potion",category="potion",stats={"effect": "invisibility", "duration": 15}),
"fireball_scroll": dict(name="Scroll of Fireball",category="scroll", stats={"effect": "fireball", "damage": 20, "radius": 3}),
"teleport_scroll": dict(name="Scroll of Teleport",category="scroll", stats={"effect": "teleport"}),
"mapping_scroll": dict(name="Scroll of Mapping", category="scroll", stats={"effect": "mapping"}),
}
def make_item(kind: str, x: int, y: int) -> Item:
d = ITEM_DEFS[kind]
return Item(
x=x, y=y, kind=kind, name=d["name"],
category=d["category"], stats=dict(d["stats"]),
sprite_key=kind,
)
+307 -531
View File
@@ -1,535 +1,311 @@
"""Procedural pixel-art sprite definitions (plan.md Rendering). """Procedural pixel-art grids: 2D arrays of single-char palette keys.
Every entity, item, and feature is a 16x16 grid of single-char palette keys ``render/sprites.get_sprite`` rasterizes a grid to a cached Surface, mapping each
(data/constants.PALETTE: "." transparent). Grids are drawn with small canvas char to a color from ``data.constants.PALETTE``. ``.``/space = transparent. The
primitives (rect, disc, triangle, line) so the art is symmetric and marker char ``a`` is an item accent replaced at raster time by a per-kind tint
recognizable rather than hand-counted ASCII. render/sprites.py rasterizes a (``TINTS``), so one category shape recolors into distinct items. Rows may be
grid to a pygame.Surface once and caches it. ragged; the rasterizer pads short rows with transparency.
Tiles (walls/floor) are NOT here: they need seeded per-tile variation, so the
renderer draws them procedurally. This file holds the distinct, judged sprites:
player (4 facings), 7 enemies + small slime, 13 item icons, and stairs.
""" """
from __future__ import annotations from __future__ import annotations
SIZE: int = 16 # Palette keys (see data.constants.PALETTE):
# . space = transparent K = darkest outline k = outline shade
# h = light/white s = stairs yellow y = yellow b = blue
# --------------------------------------------------------------------------- # # r = red g = green p = purple c = bone white o = brown n = dark red
# Canvas primitives — operate on a mutable list[list[str]] grid of SIZE rows. # H = blood/damage a = item accent (tinted per kind)
# --------------------------------------------------------------------------- #
def _blank() -> list[list[str]]: GRIDS: dict[str, list[str]] = {
return [["." for _ in range(SIZE)] for _ in range(SIZE)]
# ---- stairs: glowing yellow descending staircase (3 steps down-right) ----
"stairs": [
def _set(g: list[list[str]], x: int, y: int, k: str) -> None: "..............",
if 0 <= x < SIZE and 0 <= y < SIZE: ".KKKKKK.......",
g[y][x] = k ".KyyyyyK......",
".KsssssK......",
".KKKKKKK......",
def _rect(g, x0, y0, x1, y1, k) -> None: "....KKKKKK....",
for y in range(max(0, y0), min(SIZE - 1, y1) + 1): "....KyyyyyK...",
for x in range(max(0, x0), min(SIZE - 1, x1) + 1): "....KsssssK...",
g[y][x] = k "....KKKKKKK...",
".......KKKKKK.",
".......KyyyyyK",
def _frame(g, x0, y0, x1, y1, k) -> None: ".......KsssssK",
for x in range(x0, x1 + 1): ".......KKKKKKK",
_set(g, x, y0, k) "..............",
_set(g, x, y1, k) "..............",
for y in range(y0, y1 + 1): ],
_set(g, x0, y, k)
_set(g, x1, y, k) # ---- player: hooded adventurer, blue cloak, steel highlight ----
"player": [
"....KKKK....",
def _disc(g, cx, cy, rx, ry, k) -> None: "...KhKKhk...",
rx = max(0.1, rx) "..KhhhhhhK..",
ry = max(0.1, ry) "..KhccccKh..",
for y in range(SIZE): "..KhhhhhhK..",
for x in range(SIZE): ".KbbbbbbbbK.",
dx = (x - cx) / rx ".KbhbbbbhbK.",
dy = (y - cy) / ry ".KbbbbbbbbK.",
if dx * dx + dy * dy <= 1.0: ".KbbbbbbbbK.",
g[y][x] = k ".KbbKKKKbbK.",
".KbK....KbK.",
".KK......KK.",
def _hline(g, x0, x1, y, k) -> None: "............",
for x in range(min(x0, x1), max(x0, x1) + 1): "............",
_set(g, x, y, k) ],
# ---- rat: small brown body, ears, pink tail ----
def _vline(g, x, y0, y1, k) -> None: "rat": [
for y in range(min(y0, y1), max(y0, y1) + 1): "..............",
_set(g, x, y, k) "...KK....KK...",
"...KoK..KoK...",
"..KooooooK....",
def _line(g, x0, y0, x1, y1, k) -> None: ".KooooooooK.KK",
dx = abs(x1 - x0) ".KoohhooooKKK.",
dy = -abs(y1 - y0) ".KooooooooK...",
sx = 1 if x0 < x1 else -1 ".KooooooooK...",
sy = 1 if y0 < y1 else -1 "..KooooooK....",
err = dx + dy "...KooooK.....",
while True: "....KhhK......",
_set(g, x0, y0, k) "....K..K...oo.",
if x0 == x1 and y0 == y1: "...........oo.",
break "..............",
e2 = 2 * err ],
if e2 >= dy:
err += dy # ---- goblin: green humanoid, pointed ears, crude blade ----
x0 += sx "goblin": [
if e2 <= dx: "..............",
err += dx "..K.K....K.K..",
y0 += sy "..KgK....KgK..",
".KggggggggggK.",
".KgghhhhhggK..",
def _tri(g, ax, ay, bx, by, cx, cy, k) -> None: ".KggKrrKggK...", # eyes/mouth
ymin = max(0, int(min(ay, by, cy))) ".KggggggggK...",
ymax = min(SIZE - 1, int(max(ay, by, cy))) ".KgggggggggK..",
for y in range(ymin, ymax + 1): ".KgggKKKgggK..",
xs = [] ".KggK...KggK..",
for (x0, y0, x1, y1) in ((ax, ay, bx, by), (bx, by, cx, cy), (cx, cy, ax, ay)): ".KgK.....KgK..",
if y0 == y1: ".KK.......KK..",
if y0 == y: ".....yy.......", # crude blade
xs.extend([x0, x1]) ".....yy.......",
continue ],
t = (y - y0) / (y1 - y0)
xs.append(x0 + t * (x1 - x0)) # ---- skeleton archer: thin bones, ribcage, drawn bow + quiver, glowing eyes ----
if len(xs) >= 2: "skeleton_archer": [
_hline(g, int(round(min(xs))), int(round(max(xs))), y, k) "..............",
".....KKKK.....",
"....KccccK....",
def _flip(g) -> list[list[str]]: "....KqccqK....", # glowing eye sockets
return [row[::-1] for row in g] "....KccccK....",
"....KchhcK....", # cheek bones
".....KKKK.....", # teeth
def _shift(g, dy: int) -> list[list[str]]: "y...KccccK..o.", # quiver fletch | shoulders | bow tip
out = _blank() "yo..KcKKcK.o..", # ribs + bow limb
for y in range(SIZE): "yo..KcKKcKo...", # bow belly (closest to body)
for x in range(SIZE): "yo..KcKKcKo...",
ny = y + dy "yo..KcKKcK.o..",
if 0 <= ny < SIZE: "yo..KcKKcK..o.", # bow tip
out[ny][x] = g[y][x] "y...KcKKcK...o",
return out "....KK..KK....", # pelvis
"....Kc..cK....", # thin bony legs
],
def _outline(g) -> list[list[str]]:
"""1px dark 'K' border around the silhouette (keeps sprites off the floor).""" # ---- orc warrior: broad hulking brute, plate pauldrons, tusks, big blade ----
out = [row[:] for row in g] "orc_warrior": [
for y in range(SIZE): "..............",
for x in range(SIZE): ".....KKKK.....",
if g[y][x] != ".": "....KnnnnK....",
continue "....KHnnHK....", # red eyes / heavy brow
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): "....KnnnnK....",
nx, ny = x + dx, y + dy "...hKnnnnKh...", # jutting tusks
if 0 <= nx < SIZE and 0 <= ny < SIZE and g[ny][nx] != ".": "..KnnnnnnnnK..", # thick neck
out[y][x] = "K" "KKnnnnnnnnnnKK", # massive plate shoulders
break "KnhhnnnnnnhhnK", # pauldron highlights
return out "KnnnnnnnnnnnnK", # broad chest
".KKnnnyynnnKK.", # fists + yellow crossguard
"..KnGGGGGGnK..", # big steel blade
def _rows(g) -> list[str]: "..KnhGGGGhnK..", # blade bright edge
return ["".join(row) for row in g] "...KKGGGKK....", # heavy blade tip
"...KKK..KKK...", # legs
"...KK....KK...", # feet
def _eframes(g) -> list[list[str]]: ],
"""2 idle frames: base + 1px bob, both outlined."""
ob = _outline(g) # ---- wraith: translucent purple wisps, tattered cloak, no legs ----
return [_rows(ob), _rows(_shift(ob, 1))] "wraith": [
"..............",
".....KKKK.....",
def _iframe(g) -> list[list[str]]: "....KppppK....",
return [_rows(_outline(g))] "...KppppppK...",
"...KpHHppK....", # glowing eyes
"...KpppppK....",
# --------------------------------------------------------------------------- # "..KpppppppK...",
# Player — hooded adventurer, 4 facings. Weapon/armor visibly change via the ".KpppppppppK..",
# renderer (held-weapon icon + armor shoulder tint), not extra grids. ".KpKpKpKpKpK..", # tattered hem
# --------------------------------------------------------------------------- # "KpK.pK.pK.pK..",
def _player_down(): "p.p..p...p..p.",
g = _blank() "..............",
_rect(g, 6, 1, 9, 1, "W") # hood crown "..............",
_rect(g, 5, 2, 10, 5, "W") # hood dome "..............",
_rect(g, 6, 4, 9, 5, "s") # face shadow ],
_set(g, 7, 4, "E"); _set(g, 8, 4, "E") # blue eyes
_rect(g, 4, 6, 11, 7, "W") # shoulders # ---- green slime: big glossy domed blob, highlight, googly eyes, drip ----
_set(g, 4, 6, "w"); _set(g, 11, 6, "w") # shoulder highlights "green_slime": [
_rect(g, 5, 8, 10, 11, "W") # torso "..............",
_hline(g, 5, 10, 11, "y") # belt "...KKKKKKKK...",
_vline(g, 4, 8, 11, "W"); _vline(g, 11, 8, 11, "W") # arms "..KggggggggK..",
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h") # legs ".KgghhhhgggK..", # glossy top-left highlight
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K") # boots ".KghhKKhhggK..", # sheen
return g "KgggggggggggK.",
"KgghKggKhgggK.", # two googly eyes
"KgggggggggggK.",
def _player_up(): "KgggggggggggK.",
g = _player_down() ".KgggggggggK..",
_rect(g, 6, 3, 9, 5, "W") # back of hood: no face/eyes ".KgggggggggK..",
_hline(g, 6, 9, 5, "k") "..KKKKKKKKKK..", # flat bottom (squished on ground)
return g ".....g........", # drip
"....gg........",
".....g........",
def _player_right(): "..............",
g = _blank() ],
_rect(g, 5, 1, 9, 1, "W")
_rect(g, 5, 2, 11, 5, "W") # hood, extending right (point) # ---- small slime: smaller cuter variant ----
_set(g, 12, 4, "W") "small_slime": [
_rect(g, 7, 4, 9, 5, "s") # side face "..............",
_set(g, 10, 4, "E") # one eye "..............",
_rect(g, 4, 6, 11, 7, "W") "..............",
_set(g, 4, 6, "w") "....KKKKKK....",
_rect(g, 5, 8, 10, 11, "W") "...KggggggK...",
_hline(g, 5, 10, 11, "y") "..KggHHggggK..",
_vline(g, 4, 8, 11, "W") "..KgghhggggK..",
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h") "..KggggggggK..",
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K") "..KggggggggK..",
return g "...KKKKKKKK...",
".....g........",
"..............",
# --------------------------------------------------------------------------- # "..............",
# Enemies — each a distinct silhouette + dominant hue. "..............",
# --------------------------------------------------------------------------- # ],
def _rat():
g = _blank() # ---- ancient dragon: large red boss, horns, wings, fangs ----
_disc(g, 5, 5, 1.5, 1.5, "W"); _disc(g, 9, 5, 1.5, 1.5, "W") # ears "ancient_dragon": [
_set(g, 5, 5, "o"); _set(g, 9, 5, "o") # inner ear "K............K",
_disc(g, 10, 8, 2.3, 2.0, "s") # head "KK..........KK",
_disc(g, 6, 9, 3.8, 2.7, "s") # body ".KrK......KrK.", # wing tips
_disc(g, 6, 8, 3.0, 1.5, "W") # back highlight "KrrrK....KrrrK",
_set(g, 11, 8, "K") # eye "KrrrrKKKKrrrrK",
_set(g, 12, 9, "o") # nose ".KrrrrrrrrrrK.", # horns sweep
_set(g, 13, 8, "w"); _set(g, 13, 9, "w") # whiskers "..KHHrrrrHHK..", # eyes
_line(g, 3, 10, 0, 13, "o") # tail "..KrrrrrrrrK...",
_set(g, 5, 12, "h"); _set(g, 8, 12, "h") # feet "..KrKnnnrKrK...", # fanged maw
return g ".KrrrrrrrrrrK..",
"KrrKrrrrrrKrrK.",
"KrK..KrrK..KrK.",
def _goblin(): "K.....KK.....K.",
g = _blank() "..............",
_set(g, 4, 5, "g"); _set(g, 4, 6, "g"); _set(g, 11, 5, "g"); _set(g, 11, 6, "g") # pointed ears ],
_disc(g, 8, 6, 3.1, 2.7, "G") # head (dark green) }
_disc(g, 7, 5, 1.8, 1.0, "g") # forehead highlight
_set(g, 7, 6, "e"); _set(g, 9, 6, "e") # glowing eyes # ---- item category base shapes; the 'a' marker is tinted per kind (TINTS) ----
_set(g, 7, 8, "w"); _set(g, 9, 8, "w") # tusks GRIDS["_weapon"] = [
_rect(g, 6, 9, 10, 12, "g") # torso "......Kh......", # pointed tip
_rect(g, 6, 9, 10, 9, "G") # shoulder shade ".....KhaK.....", # blade (a = per-kind tint) w/ bright edge (h)
_hline(g, 6, 10, 12, "y") # loincloth ".....Khaa.....",
_vline(g, 5, 9, 12, "g"); _vline(g, 10, 9, 12, "g") # arms "....Khaaa.....",
_vline(g, 12, 6, 12, "W"); _set(g, 12, 5, "K") # crude club "....KhaaK.....",
_rect(g, 6, 13, 7, 14, "G"); _rect(g, 9, 13, 10, 14, "G") "...Khaaaa.....",
return g "...KhaaaK.....",
"..Khaaaaa.....",
"..KhaaaaK.....",
def _skeleton_archer(): ".Khaaaaaa.....",
g = _blank() ".KhaaaaaK.....",
# big drawn bow on the left (clear arc + taut string) "KKyyyyyyyyyKK.", # wide yellow crossguard
_vline(g, 2, 4, 12, "w") # bow back "...KaaaaK.....", # grip
_set(g, 1, 5, "w"); _set(g, 1, 6, "w") "...KaaaaK.....",
_set(g, 1, 10, "w"); _set(g, 1, 11, "w") # recurve curve "...KaaaaK.....",
_line(g, 2, 4, 9, 8, "K") # bowstring pulled to the hand "....KyyK......", # pommel
_line(g, 2, 12, 9, 8, "K") ]
_hline(g, 3, 7, 8, "w") # draw arm GRIDS["_armor"] = [
_disc(g, 9, 4, 2.0, 2.0, "w") # skull "...KKKKKKKK...", # shield top
_set(g, 8, 4, "E"); _set(g, 10, 4, "E") # glowing sockets "..KaaaaaaaaK..",
_hline(g, 8, 10, 6, "w"); _set(g, 8, 6, "K"); _set(g, 10, 6, "K") ".KaahhaaaaaaK.", # top-left highlight
_rect(g, 8, 7, 10, 11, "w") # ribcage ".KaahbhaaaaaK.", # blue boss
_hline(g, 8, 10, 8, "K"); _hline(g, 8, 10, 10, "K") "KaaabbbaaaaaK.", # blue cross (steel rim accents)
_vline(g, 9, 7, 11, "K") # spine "KaaabbbaaaaaK.",
_vline(g, 12, 5, 11, "b"); _set(g, 12, 4, "y"); _set(g, 12, 5, "y") # quiver "KaaaabbbaaaK..",
_vline(g, 8, 12, 14, "w"); _vline(g, 10, 12, 14, "w") # legs "KaaaaaaaaaK...",
return g ".KaaaaaaK.....",
"..KaaaaK......",
"...KaaK.......",
def _orc_warrior(): "....KK........", # point
g = _blank() "..............",
_disc(g, 8, 5, 3.1, 2.7, "R") # head "..............",
_disc(g, 8, 4, 2.3, 1.2, "r") # crown highlight "..............",
_set(g, 7, 5, "o"); _set(g, 9, 5, "o") # eyes "..............",
_set(g, 7, 7, "w"); _set(g, 9, 7, "w") # tusks ]
_set(g, 7, 8, "w"); _set(g, 9, 8, "w") GRIDS["_potion"] = [
_rect(g, 4, 8, 12, 9, "R") # shoulder plate ".....KKKK.....", # neck
_set(g, 4, 8, "r"); _set(g, 12, 8, "r") "....KooooK....", # cork
_rect(g, 5, 9, 11, 13, "r") # torso "....KKKKKK....", # shoulder
_rect(g, 5, 9, 11, 9, "R") "..KKaaaaaaKK..",
_hline(g, 5, 12, 11, "K") # belt ".KaaaaaaaaaaK.",
_line(g, 13, 13, 13, 4, "w") # great blade ".KaahaaaaaaaK.", # glass highlight
_line(g, 12, 13, 12, 4, "K") # edge "KaaaaaaaaaaaK.", # round bulb (a = per-kind liquid)
_set(g, 13, 13, "y") # pommel "KaaaaaaaaaaaK.",
_rect(g, 6, 13, 7, 14, "R"); _rect(g, 9, 13, 10, 14, "R") "KaaaaaaaaaaaK.",
return g "KaaaaaaaaaaaK.",
".KaaaaaaaaaK..",
".KaaaaaaaaaK..",
def _wraith(): "..KKaaaaaKK...", # base
g = _blank() "..............",
_disc(g, 8, 6, 3.6, 3.5, "P") # hood (dark purple) "..............",
_disc(g, 8, 5, 2.7, 2.0, "p") # hood light "..............",
_disc(g, 8, 7, 1.9, 1.7, "K") # face void ]
_set(g, 7, 6, "E"); _set(g, 9, 6, "E") # glowing eyes GRIDS["_scroll"] = [
_rect(g, 5, 9, 11, 12, "P") # cloak "..............",
# tattered hem (no legs) ".KhC......ChK.", # rolled end caps (top)
_set(g, 5, 13, "p"); _set(g, 7, 13, "P"); _set(g, 9, 13, "p"); _set(g, 11, 13, "P") "KhCk......kChK", # cylindrical rolls: bright rim (h) + dark core (k)
_set(g, 6, 14, "p"); _set(g, 10, 14, "p") "KhCkCCCCCCkChK", # flat paper between the rolls
_set(g, 4, 10, "P"); _set(g, 12, 10, "P") # wisps "KhCkChCCCCkChK", # ruled line
return g "KhCkaaaaaakChK", # ribbon tie (a = per-kind tint)
"KhCkaaaaaakChK",
"KhCkCCChCCkChK", # ruled line
def _slime(): "KhCkCCCCCCkChK",
g = _blank() "KhCkCCCCCCkChK",
for y in range(6, 13): "KhCk......kChK", # rolls
for x in range(3, 13): ".KhC......ChK.", # rolled end caps (bottom)
dx = (x - 8) / 4.7 "..............",
dy = (y - 9) / 3.3 "..............",
if dx * dx + dy * dy <= 1.0: "..............",
g[y][x] = "g" "..............",
_hline(g, 3, 12, 12, "G") # darker base ]
_set(g, 6, 7, "w"); _set(g, 7, 8, "w") # gloss
_disc(g, 6, 10, 1.3, 1.4, "w"); _disc(g, 10, 10, 1.3, 1.4, "w") # googly eyes # Point every item kind at its category base shape (shared list, read-only).
_set(g, 6, 10, "K"); _set(g, 10, 10, "K") _WEAPON_KINDS = ("rusty_dagger", "short_sword", "battle_axe", "war_hammer")
_set(g, 8, 13, "g"); _set(g, 8, 14, "g") # drip _ARMOR_KINDS = ("leather_armor", "chain_mail", "plate_armor")
return g _POTION_KINDS = ("healing_potion", "strength_potion", "invisibility_potion")
_SCROLL_KINDS = ("fireball_scroll", "teleport_scroll", "mapping_scroll")
for _k in _WEAPON_KINDS:
def _small_slime(): GRIDS[_k] = GRIDS["_weapon"]
g = _blank() for _k in _ARMOR_KINDS:
for y in range(7, 14): GRIDS[_k] = GRIDS["_armor"]
for x in range(4, 12): for _k in _POTION_KINDS:
dx = (x - 8) / 3.8 GRIDS[_k] = GRIDS["_potion"]
dy = (y - 10) / 3.4 for _k in _SCROLL_KINDS:
if dx * dx + dy * dy <= 1.0: GRIDS[_k] = GRIDS["_scroll"]
g[y][x] = "g"
_hline(g, 4, 11, 13, "G") # base # Per-kind accent tint applied to the 'a' marker (category hue + per-kind flavor).
_set(g, 6, 8, "w"); _set(g, 7, 9, "w") # gloss TINTS: dict[str, tuple[int, int, int]] = {
_disc(g, 6, 10, 1.1, 1.2, "w"); _disc(g, 10, 10, 1.1, 1.2, "w") # big eyes "rusty_dagger": (170, 130, 80),
_set(g, 6, 10, "K"); _set(g, 10, 10, "K") "short_sword": (210, 215, 225),
_set(g, 8, 13, "g") # drip "battle_axe": (150, 155, 165),
_hline(g, 7, 9, 12, "G") # smile "war_hammer": (120, 115, 130),
return g "leather_armor": (150, 110, 60),
"chain_armor": (120, 130, 145),
"chain_mail": (120, 130, 145),
def _dragon(): "plate_armor": (170, 175, 190),
g = _blank() "healing_potion": (220, 80, 80),
# spread wings (membrane triangles) "strength_potion": (230, 150, 60),
_tri(g, 6, 7, 0, 4, 1, 10, "R") "invisibility_potion": (200, 160, 220),
_tri(g, 6, 7, 0, 4, 1, 10, "R") "fireball_scroll": (240, 150, 60),
_tri(g, 10, 7, 15, 4, 14, 10, "R") "teleport_scroll": (150, 120, 220),
_tri(g, 10, 7, 15, 4, 14, 10, "R") "mapping_scroll": (90, 220, 220),
_set(g, 0, 4, "r"); _set(g, 15, 4, "r") # wingtips }
_set(g, 2, 6, "r"); _set(g, 13, 6, "r") # membrane ribs
# body + head
_disc(g, 8, 9, 3.5, 3.3, "r")
_disc(g, 8, 8, 2.7, 1.8, "R")
_disc(g, 8, 5, 3.1, 2.7, "r")
# horns
_line(g, 6, 3, 4, 0, "y"); _line(g, 10, 3, 12, 0, "y")
# snout + fangs
_rect(g, 7, 5, 9, 6, "R")
_set(g, 7, 7, "w"); _set(g, 9, 7, "w")
_set(g, 7, 4, "o"); _set(g, 9, 4, "o") # eyes
_set(g, 7, 6, "K"); _set(g, 9, 6, "K") # nostrils
# scales + belly
for sx, sy in ((7, 9), (9, 9), (8, 10), (6, 10), (10, 10)):
_set(g, sx, sy, "o")
_rect(g, 7, 10, 9, 12, "o")
# tail + legs
_line(g, 8, 12, 8, 15, "R")
_rect(g, 6, 12, 7, 14, "R"); _rect(g, 9, 12, 10, 14, "R")
return g
# --------------------------------------------------------------------------- #
# Items — pixel-art icons with category accent hues.
# --------------------------------------------------------------------------- #
def _dagger():
g = _blank()
_tri(g, 7, 2, 9, 2, 8, 7, "w") # short wide blade (clearly a dagger)
_set(g, 7, 2, "K"); _set(g, 9, 2, "K")
_vline(g, 8, 3, 6, "K") # fuller
_hline(g, 6, 10, 8, "y") # guard
_vline(g, 8, 9, 12, "h"); _set(g, 8, 12, "y") # handle + pommel
return g
def _sword():
g = _blank()
_line(g, 8, 1, 8, 9, "w"); _line(g, 7, 1, 7, 9, "K")
_hline(g, 5, 11, 9, "y")
_vline(g, 8, 10, 13, "h"); _set(g, 8, 13, "y")
return g
def _axe():
g = _blank()
_vline(g, 7, 2, 14, "h") # handle
_tri(g, 7, 3, 13, 2, 7, 7, "w") # head
_set(g, 13, 2, "K"); _set(g, 12, 3, "K")
_set(g, 7, 14, "y")
return g
def _hammer():
g = _blank()
_vline(g, 8, 5, 14, "h")
_rect(g, 5, 2, 11, 5, "w")
_frame(g, 5, 2, 11, 5, "K")
_set(g, 8, 14, "y")
return g
def _leather():
g = _blank()
_disc(g, 8, 8, 4.1, 4.3, "s")
_disc(g, 8, 7, 3.0, 2.6, "W")
_vline(g, 6, 5, 12, "h"); _vline(g, 10, 5, 12, "h") # straps
_hline(g, 4, 12, 11, "h")
_set(g, 8, 8, "y") # buckle
return g
def _chain():
g = _blank()
_disc(g, 8, 4, 2.6, 2.2, "b") # coif (mail hood)
_disc(g, 8, 5, 1.3, 1.1, "K") # face opening
# hauberk torso: broad shoulders tapering to a waist (rows: y -> x-range)
for y, (a, b) in ((6, (4, 12)), (7, (4, 12)), (8, (5, 11)), (9, (5, 11)),
(10, (6, 10)), (11, (6, 10)), (12, (6, 10)), (13, (6, 10))):
_hline(g, a, b, y, "b")
_hline(g, 4, 11, 6, "w") # collar
for y in range(6, 13): # interlocking ring texture
for x in range(4, 13):
if g[y][x] == "b" and (x + y) % 2 == 0:
_set(g, x, y, "w")
return g
def _plate():
g = _blank()
_disc(g, 4, 6, 1.8, 1.6, "w"); _disc(g, 11, 6, 1.8, 1.6, "w") # pauldrons
# breastplate torso: broad chest tapering to a waist
for y, (a, b) in ((6, (4, 11)), (7, (4, 11)), (8, (5, 10)), (9, (5, 10)),
(10, (5, 10)), (11, (6, 9)), (12, (6, 9)), (13, (6, 9))):
_hline(g, a, b, y, "w")
_disc(g, 6, 8, 1.7, 1.5, "w"); _disc(g, 10, 8, 1.7, 1.5, "w") # pec domes
_set(g, 6, 8, "c"); _set(g, 10, 8, "c") # steel highlights
_vline(g, 8, 7, 13, "K") # center ridge
_hline(g, 6, 9, 12, "K") # belt
for x, y in ((5, 7), (10, 7)):
_set(g, x, y, "b") # rivets
return g
def _potion(color):
def draw():
g = _blank()
_vline(g, 6, 3, 5, "w"); _vline(g, 10, 3, 5, "w") # neck
_hline(g, 6, 10, 3, "w")
_set(g, 8, 2, "h") # cork
_disc(g, 8, 9, 3.3, 3.3, "w") # flask
_disc(g, 8, 9, 2.5, 2.5, color) # liquid
_set(g, 7, 8, "w") # gloss
return g
return draw
def _scroll(emblem):
def draw():
g = _blank()
# rolled scroll: horizontal cylinder with capped ends
_rect(g, 3, 7, 12, 11, "c") # paper body
_hline(g, 3, 12, 7, "b"); _hline(g, 3, 12, 11, "b") # roll shading
_disc(g, 3, 9, 1.2, 2.6, "b"); _disc(g, 12, 9, 1.2, 2.6, "b") # end knobs
_disc(g, 3, 9, 0.7, 1.7, "c"); _disc(g, 12, 9, 0.7, 1.7, "c")
_vline(g, 7, 6, 12, "y"); _vline(g, 8, 6, 12, "y") # tie ribbon
emblem(g) # floating magic emblem up top
return g
return draw
def _emblem_fireball(g):
_tri(g, 5, 5, 11, 5, 8, 0, "o") # flame
_set(g, 8, 1, "y"); _set(g, 7, 2, "y"); _set(g, 9, 2, "y")
_set(g, 8, 3, "r")
def _emblem_teleport(g):
_vline(g, 8, 1, 5, "E"); _hline(g, 6, 10, 3, "E") # 4-point star
_set(g, 6, 1, "c"); _set(g, 10, 1, "c"); _set(g, 6, 5, "c"); _set(g, 10, 5, "c")
_set(g, 8, 3, "w")
def _emblem_mapping(g):
_frame(g, 5, 1, 11, 5, "b") # map frame
_hline(g, 6, 10, 2, "c")
_set(g, 6, 3, "y"); _set(g, 9, 4, "y") # landmarks
_line(g, 6, 3, 10, 4, "c") # road
def _stairs():
g = _blank()
_rect(g, 1, 11, 14, 14, "y") # bottom landing
_rect(g, 1, 9, 12, 11, "y") # mid step
_rect(g, 1, 7, 10, 9, "y") # upper step
_rect(g, 1, 5, 8, 7, "y") # top step
_hline(g, 1, 14, 11, "o"); _hline(g, 1, 12, 9, "o") # lit tread edges
_hline(g, 1, 10, 7, "o"); _hline(g, 1, 8, 5, "o")
_hline(g, 1, 14, 14, "K") # base shadow
_line(g, 5, 2, 9, 4, "w"); _line(g, 9, 4, 5, 4, "w") # down-chevron into the hole
_set(g, 9, 4, "y")
return g
# --------------------------------------------------------------------------- #
# Registry
# --------------------------------------------------------------------------- #
def _build() -> dict[str, list[list[str]]]:
s: dict[str, list[list[str]]] = {}
s["player"] = s["player_down"] = _eframes(_player_down())
s["player_up"] = _eframes(_player_up())
s["player_right"] = _eframes(_player_right())
s["player_left"] = _eframes(_flip(_player_right()))
for name, fn in (
("rat", _rat), ("goblin", _goblin), ("skeleton_archer", _skeleton_archer),
("orc_warrior", _orc_warrior), ("wraith", _wraith), ("green_slime", _slime),
("small_slime", _small_slime), ("ancient_dragon", _dragon),
):
s[name] = _eframes(fn())
for name, fn in (
("weapon_dagger", _dagger), ("weapon_sword", _sword),
("weapon_axe", _axe), ("weapon_hammer", _hammer),
("armor_leather", _leather), ("armor_chain", _chain),
("armor_plate", _plate),
):
s[name] = _iframe(fn())
s["potion_healing"] = _iframe(_potion("m")())
s["potion_strength"] = _iframe(_potion("o")())
s["potion_invisibility"] = _iframe(_potion("p")())
s["scroll_fireball"] = _iframe(_scroll(_emblem_fireball)())
s["scroll_teleport"] = _iframe(_scroll(_emblem_teleport)())
s["scroll_mapping"] = _iframe(_scroll(_emblem_mapping)())
s["stairs"] = _eframes(_stairs())
return s
SPRITES: dict[str, list[list[str]]] = _build()
NAMES: list[str] = sorted(SPRITES.keys())
def frames_count(name: str) -> int:
return len(SPRITES[name]) if name in SPRITES else 1
def grid(name: str, frame: int = 0) -> list[str]:
"""Return the frame's row list for `name` (frame wraps modulo count)."""
frames = SPRITES.get(name)
if not frames:
return ["................"] * SIZE
return frames[frame % len(frames)]
if __name__ == "__main__": # tiny self-check
for n in NAMES:
grd = grid(n, 0)
assert len(grd) == SIZE and all(len(r) == SIZE for r in grd), n
print(f"{len(NAMES)} sprites, all {SIZE}x{SIZE}: {', '.join(NAMES)}")
+352 -221
View File
@@ -1,256 +1,387 @@
"""Gameplay actions: pure functions that mutate a GameSession (plan.md §6, §9). """Intent dispatch: translate a logical key into a session mutation.
`try_move` is the turn driver — a successful move or attack advances the turn, ``apply_input(session, key)`` is the only entry point the game loop calls. It
runs enemy AI, recomputes FOV, ticks effect timers, and checks for death. never raises on valid game state; every combat event, pickup, level-up and
`pickup` / `descend` / `use_item` / `equip` are resolution actions; they log and status change logs a human-readable message (the log is the feedback channel).
mutate but leave turn advancement to the caller so item use stays deterministic
(a potion must not let an enemy sneak in a hit between quaff and the HP check). Turn model: movement, melee, wait, pickup, quaff and read all spend a turn and
trigger an enemy turn afterwards (``_end_turn``). Descent changes floors (no
enemy turn). Menus / mute / How-to-Play are presentation-layer concerns, so
they are graceful no-ops here (main.py owns their on-screen effect).
""" """
from __future__ import annotations from __future__ import annotations
from data import constants as C import json
from ai.behaviors import on_death, take_enemy_turn import os
from engine.combat import attack import random
from engine import game_state from typing import Any
from engine.game_state import recompute_fov
from engine.map_gen import is_walkable from engine.combat import roll_attack
from entities.enemy import Enemy from engine.fov import compute_fov
from entities.item import Item from engine.serializers import session_to_dict
from entities.player import Effect from ai.behaviors import act_enemy, split_on_death
from data.constants import SIGHT_RADIUS, SAVE_FILE
_LOG_MAX = 50
_DIRS: dict[str, tuple[int, int]] = {
"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0),
}
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------- dispatch
# Movement / melee def apply_input(session: Any, key: str) -> None:
# --------------------------------------------------------------------------- # """Apply one logical input to ``session``. Unknown keys are ignored."""
def try_move(session, dx: int, dy: int) -> bool: if not isinstance(key, str):
"""Move the player by (dx, dy) or melee an enemy there. Returns whether the return
player acted (and thus a turn elapsed).""" if key in _DIRS:
player = session.player dx, dy = _DIRS[key]
floor = session.dungeon[session.current_floor] _move(session, dx, dy)
nx, ny = player.x + dx, player.y + dy return
if key == "g":
if not (0 <= nx < floor.width and 0 <= ny < floor.height): _pickup(session)
return False elif key == "f":
if dx or dy: _descend(session)
player.facing = _facing(dx, dy) elif key == "q":
_quaff(session)
target = _enemy_at(floor, nx, ny) elif key == "r":
if target is not None: _read(session)
res = attack(player, target, rng=session.rng, log=session.log) elif key == "e":
if res["killed"]: _equip(session)
on_death(target, session) elif key == "i":
_inventory_info(session)
elif key == "S":
_save(session)
elif key == "wait":
_end_turn(session) _end_turn(session)
return True elif key in ("?", "m", "escape"):
# Overlays / mute live in the presentation layer (main.py); safe no-op.
if floor.tiles[ny][nx] == 1 and not _blocked_at(floor, nx, ny): return
player.x, player.y = nx, ny
_end_turn(session)
return True
return False
def _end_turn(session) -> None: # --------------------------------------------------------------------- queries
"""One turn elapsed: counter up, FOV, enemy turns, effect timers, death.""" def item_under_player(session: Any) -> Any:
session.turn += 1 gm = session.dungeon[session.current_floor]
recompute_fov(session) p = session.player
_enemy_turns(session) return next((e for e in gm.entities if _is_item(e) and e.x == p.x and e.y == p.y), None)
def is_on_stairs(session: Any) -> bool:
gm = session.dungeon[session.current_floor]
return gm.stairs_down is not None and (session.player.x, session.player.y) == gm.stairs_down
# ------------------------------------------------------------------ primitives
def _log(session: Any, msg: str) -> None:
session.log.append(msg)
if len(session.log) > _LOG_MAX:
del session.log[: len(session.log) - _LOG_MAX]
def _is_enemy(e: Any) -> bool:
return bool(getattr(e, "behavior", "")) and getattr(e, "hp", 1) > 0
def _is_item(e: Any) -> bool:
return getattr(e, "category", "") != "" and not getattr(e, "behavior", "")
def _enemy_at(gm: Any, x: int, y: int) -> Any:
return next((e for e in gm.entities if _is_enemy(e) and e.x == x and e.y == y), None)
def _recompute_fov(session: Any) -> set[tuple[int, int]]:
gm = session.dungeon[session.current_floor]
p = session.player
vis = compute_fov(gm, (p.x, p.y), SIGHT_RADIUS)
for y in range(gm.height):
vrow = gm.visible[y]
for x in range(gm.width):
vrow[x] = False
for (x, y) in vis:
gm.visible[y][x] = True
gm.explored[y][x] = True
return vis
def _end_turn(session: Any) -> None:
if session.state != "playing":
return
visible = _recompute_fov(session)
_advance_enemies(session, visible)
if session.state == "playing":
_tick_effects(session) _tick_effects(session)
if session.player.hp <= 0 and session.state == "playing": session.turn += 1
game_state.mark_dead(session)
session.log.append("You have died.")
def _enemy_turns(session) -> None: def _advance_enemies(session: Any, visible: set[tuple[int, int]]) -> None:
floor = session.dungeon[session.current_floor] gm = session.dungeon[session.current_floor]
for e in list(floor.entities): p = session.player
if isinstance(e, Enemy) and e.hp > 0: vis = visible
take_enemy_turn(e, session, rng=session.rng) if p.effect_timers.get("invisibility", 0) > 0:
if session.player.hp <= 0: vis = visible - {(p.x, p.y)}
for enemy in list(gm.entities):
if not _is_enemy(enemy) or session.state != "playing":
continue
act_enemy(enemy, gm, p, vis, random)
if p.hp <= 0:
p.hp = 0
session.state = "dead"
_log(session, "You have been slain. The Underdepths claim another soul.")
break
def _tick_effects(session: Any) -> None:
timers = session.player.effect_timers
for k in list(timers.keys()):
timers[k] -= 1
if timers[k] <= 0:
del timers[k]
_log(session, f"Your {k} effect wears off.")
# ---------------------------------------------------------------------- movement
def _move(session: Any, dx: int, dy: int) -> None:
if session.state != "playing":
return return
p = session.player
gm = session.dungeon[session.current_floor]
def _tick_effects(session) -> None: tx, ty = p.x + dx, p.y + dy
player = session.player enemy = _enemy_at(gm, tx, ty)
if not player.effects: if enemy is not None:
_player_attack(session, enemy)
_end_turn(session)
return return
remaining: list = [] if gm.walkable(tx, ty):
for eff in player.effects: p.x, p.y = tx, ty
eff.duration -= 1 _end_turn(session)
if eff.duration > 0: return
remaining.append(eff) # Bumped a wall: no turn spent (standard roguelike convention).
elif eff.kind == "invisibility":
player.invisible = False
session.log.append("You fade back into view.")
player.effects = remaining
# --------------------------------------------------------------------------- # def _player_attack(session: Any, enemy: Any) -> None:
# Pickup / descend roll = roll_attack(session.player, enemy, random)
# --------------------------------------------------------------------------- # name = getattr(enemy, "name", "enemy")
def pickup(session) -> bool: if not roll.hit:
"""Move the item under the player into inventory. False if nothing there.""" _log(session, f"You miss the {name}.")
player = session.player return
floor = session.dungeon[session.current_floor] enemy.hp -= roll.damage
for e in list(floor.entities): if roll.crit:
if isinstance(e, Item) and e.x == player.x and e.y == player.y: _log(session, f"Critical! You strike the {name} for {roll.damage} damage!")
floor.entities.remove(e)
player.inventory.append(e)
session.log.append(f"You pick up the {e.name}.")
return True
session.log.append("There is nothing here to pick up.")
return False
def descend(session) -> bool:
"""Descend the stairs the player stands on. False if not on stairs / last floor."""
player = session.player
floor = session.dungeon[session.current_floor]
if (player.x, player.y) != floor.stairs_down:
session.log.append("There are no stairs here.")
return False
if session.current_floor >= C.FLOORS - 1:
return False # no descent past the boss floor
session.current_floor += 1
new_floor = session.dungeon[session.current_floor]
spawn = new_floor.rooms[0].center if new_floor.rooms else _first_walkable(new_floor)
if not is_walkable(new_floor, *spawn):
spawn = _first_walkable(new_floor)
player.x, player.y = spawn
recompute_fov(session)
session.log.append(f"You descend to floor {session.current_floor + 1}.")
return True
# --------------------------------------------------------------------------- #
# Use / equip
# --------------------------------------------------------------------------- #
def use_item(session, item) -> None:
"""Apply a potion/scroll, or equip a weapon/armor. Consumes consumables."""
if item.item_type == "potion":
_use_potion(session, item)
_consume(session, item)
elif item.item_type == "scroll":
_use_scroll(session, item)
_consume(session, item)
elif item.item_type in ("weapon", "armor"):
equip(session, item)
else: else:
session.log.append(f"You can't use the {item.name}.") _log(session, f"You hit the {name} for {roll.damage} damage.")
if enemy.hp <= 0:
_defeat_enemy(session, enemy)
def equip(session, item) -> None: def _defeat_enemy(session: Any, enemy: Any) -> None:
"""Place an equippable in its slot; the previous item returns to inventory.""" gm = session.dungeon[session.current_floor]
player = session.player _log(session, f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)")
if item.item_type not in ("weapon", "armor"): levels = session.player.gain_xp(enemy.xp_value)
session.log.append(f"You can't equip the {item.name}.") if levels:
_log(session, f"You reach level {session.player.level}! (HP fully restored)")
if enemy in gm.entities:
gm.entities.remove(enemy)
if getattr(enemy, "can_split", False):
spawned = split_on_death(enemy, gm)
for baby in spawned:
gm.entities.append(baby)
if spawned:
_log(session, f"The {enemy.name} splits into Small Slimes!")
if getattr(enemy, "kind", "") == "ancient_dragon" and session.current_floor == 9:
session.state = "victory"
_log(session, "You slew the Ancient Dragon! Underdepths is conquered.")
# --------------------------------------------------------------------- actions
def _pickup(session: Any) -> None:
if session.state != "playing":
return return
slot = item.item_type item = item_under_player(session)
old = player.equipped.get(slot) if item is None:
player.equipped[slot] = item _log(session, "There is nothing here to pick up.")
if item in player.inventory: return
player.inventory.remove(item) gm = session.dungeon[session.current_floor]
if old is not None: gm.entities.remove(item)
player.inventory.append(old) session.player.inventory.append(item)
session.log.append(f"You unequip the {old.name}.") _log(session, f"You pick up the {item.name}.")
session.log.append(f"You equip the {item.name}.") _end_turn(session)
def _use_potion(session, item) -> None: def _descend(session: Any) -> None:
player = session.player if session.state != "playing":
if item.subtype == "healing": return
amount = item.stats.get("heal", 30) p = session.player
player.hp = min(player.max_hp, player.hp + amount) gm = session.dungeon[session.current_floor]
session.log.append(f"You quaff a Healing Potion and recover {amount} HP.") if gm.stairs_down is None or (p.x, p.y) != gm.stairs_down:
elif item.subtype == "strength": _log(session, "Stand on the yellow > stairs, then press F to descend.")
player.effects.append(Effect( return
kind="strength", session.current_floor += 1
power=item.stats.get("power", 5), ngm = session.dungeon[session.current_floor]
duration=item.stats.get("duration", 20), sp = ngm.spawn or (1, 1)
)) p.x, p.y = sp
session.log.append("Your muscles surge! (+5 power for 20 turns)") _log(session, f"You descend to floor {session.current_floor + 1}.")
elif item.subtype == "invisibility": _recompute_fov(session)
player.effects.append(Effect( session.turn += 1
kind="invisibility",
duration=item.stats.get("duration", 15),
))
player.invisible = True
session.log.append("You fade from sight!")
def _use_scroll(session, item) -> None: def _quaff(session: Any) -> None:
player = session.player if session.state != "playing":
floor = session.dungeon[session.current_floor] return
if item.subtype == "fireball": p = session.player
radius = item.stats.get("radius", 3) potion = next((it for it in p.inventory if getattr(it, "category", "") == "potion"), None)
dmg = item.stats.get("damage", 20) if potion is None:
hit = [e for e in floor.entities _log(session, "You have no potions to quaff.")
if isinstance(e, Enemy) return
and max(abs(e.x - player.x), abs(e.y - player.y)) <= radius] p.inventory.remove(potion)
for e in hit: eff = potion.stats.get("effect")
if eff == "heal":
before = p.hp
p.hp = min(p.max_hp, p.hp + potion.stats.get("amount", 30))
_log(session, f"You quaff a {potion.name}. (+{p.hp - before} HP)")
elif eff == "strength":
p.effect_timers["strength"] = potion.stats.get("duration", 20)
_log(session, f"You quaff a {potion.name}. (+{p.weapon_power - p.power} power)")
elif eff == "invisibility":
p.effect_timers["invisibility"] = potion.stats.get("duration", 15)
_log(session, f"You quaff a {potion.name}. (foes cannot see you)")
else:
_log(session, f"You quaff a {potion.name}.")
_end_turn(session)
def _read(session: Any) -> None:
if session.state != "playing":
return
p = session.player
scroll = next((it for it in p.inventory if getattr(it, "category", "") == "scroll"), None)
if scroll is None:
_log(session, "You have no scrolls to read.")
return
p.inventory.remove(scroll)
eff = scroll.stats.get("effect")
if eff == "fireball":
_fireball(session, scroll.stats)
elif eff == "teleport":
_teleport(session)
elif eff == "mapping":
gm = session.dungeon[session.current_floor]
for y in range(gm.height):
for x in range(gm.width):
gm.explored[y][x] = True
_log(session, "The scroll reveals the entire floor.")
else:
_log(session, f"You read a {scroll.name}.")
_end_turn(session)
def _fireball(session: Any, stats: dict) -> None:
gm = session.dungeon[session.current_floor]
p = session.player
radius = stats.get("radius", 3)
dmg = stats.get("damage", 20)
enemies = [e for e in gm.entities if _is_enemy(e)]
if not enemies:
_log(session, "The fireball fizzles — no target in sight.")
return
target = min(enemies, key=lambda e: max(abs(e.x - p.x), abs(e.y - p.y)))
cx, cy = target.x, target.y
_log(session, f"A fireball erupts! ({dmg} damage, radius {radius})")
for e in [en for en in enemies if max(abs(en.x - cx), abs(en.y - cy)) <= radius]:
e.hp -= dmg e.hp -= dmg
session.log.append(f"The fireball erupts! {len(hit)} foe(s) burn for {dmg} damage.") _log(session, f"The {e.name} is caught in the blast. ({dmg} damage)")
for e in hit:
if e.hp <= 0: if e.hp <= 0:
on_death(e, session) _defeat_enemy(session, e)
elif item.subtype == "teleport":
targets = [
(x, y) for y in range(floor.height) for x in range(floor.width)
if floor.tiles[y][x] == 1
and (x, y) != (player.x, player.y)
and not _blocked_at(floor, x, y)
]
if targets:
player.x, player.y = session.rng.choice(targets)
recompute_fov(session)
session.log.append("The world blurs — you teleport across the floor!")
elif item.subtype == "mapping":
for y in range(floor.height):
for x in range(floor.width):
if floor.tiles[y][x] == 1:
floor.explored[y][x] = True
session.log.append("A complete map of this floor floods your mind!")
def _consume(session, item) -> None: def _teleport(session: Any) -> None:
if item in session.player.inventory: gm = session.dungeon[session.current_floor]
session.player.inventory.remove(item) tiles = [(x, y) for y in range(gm.height) for x in range(gm.width) if gm.walkable(x, y)]
if not tiles:
_log(session, "The teleport scroll finds nowhere to send you.")
return
session.player.x, session.player.y = random.choice(tiles)
_log(session, "You blink across the floor.")
_recompute_fov(session)
# --------------------------------------------------------------------------- # def _equip(session: Any) -> None:
# helpers p = session.player
# --------------------------------------------------------------------------- # improved = False
def _enemy_at(floor, x: int, y: int): best_w = max((it for it in p.inventory if getattr(it, "category", "") == "weapon"),
for e in floor.entities: key=lambda it: it.stats.get("power", 0), default=None)
if isinstance(e, Enemy) and e.x == x and e.y == y: cur_w = p.equipped_weapon.stats.get("power", 0) if p.equipped_weapon else -1
return e if best_w is not None and best_w.stats.get("power", 0) > cur_w:
p.inventory.remove(best_w)
p.equip(best_w)
_log(session, f"You equip the {best_w.name}.")
improved = True
best_a = max((it for it in p.inventory if getattr(it, "category", "") == "armor"),
key=lambda it: it.stats.get("armor", 0), default=None)
cur_a = p.equipped_armor.stats.get("armor", 0) if p.equipped_armor else -1
if best_a is not None and best_a.stats.get("armor", 0) > cur_a:
p.inventory.remove(best_a)
p.equip(best_a)
_log(session, f"You equip the {best_a.name}.")
improved = True
if not improved:
_log(session, "Nothing in your pack is worthier than what you wear.")
def _inventory_info(session: Any) -> None:
inv = session.player.inventory
if not inv:
_log(session, "Your pack is empty.")
return
_log(session, "Pack: " + ", ".join(it.name for it in inv))
def _save_path() -> str:
return os.path.join(os.getcwd(), SAVE_FILE)
def _save(session: Any) -> None:
try:
with open(_save_path(), "w", encoding="utf-8") as f:
json.dump(session_to_dict(session), f)
session.state = "saved"
_log(session, "Game saved.")
except OSError as ex:
_log(session, f"Could not save the game: {ex}")
def load_saved() -> Any:
"""Rebuild a GameSession from ``save.json`` if present, else None."""
from engine.serializers import session_from_dict
path = _save_path()
if not os.path.exists(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
return session_from_dict(json.load(f))
except (OSError, ValueError, KeyError):
return None return None
def _blocked_at(floor, x: int, y: int) -> bool: def delete_save() -> None:
"""True if a blocking entity (enemy) occupies (x, y). Items never block.""" try:
for e in floor.entities: os.remove(_save_path())
if isinstance(e, Enemy) and e.x == x and e.y == y: except OSError:
return True pass
return False
def _first_walkable(game_map) -> tuple[int, int]: if __name__ == "__main__":
for y in range(game_map.height): # Self-check: pickup + descent work on a fresh session.
for x in range(game_map.width): from engine.game_state import new_session
if game_map.tiles[y][x] == 1: s = new_session(seed=1)
return (x, y) gm = s.dungeon[0]
return (1, 1) from data import items as I
px, py = s.player.x, s.player.y
gm.entities.append(I.make_item("healing_potion", px, py))
def _facing(dx: int, dy: int) -> str: n0 = len(s.player.inventory)
if dy < 0: apply_input(s, "g")
return "up" assert len(s.player.inventory) == n0 + 1, "pickup failed"
if dy > 0: s.player.x, s.player.y = gm.stairs_down
return "down" f0 = s.current_floor
if dx < 0: apply_input(s, "f")
return "left" assert s.current_floor == f0 + 1, "descent failed"
if dx > 0: print("actions self-check: OK")
return "right"
return "down"
+74 -84
View File
@@ -1,108 +1,98 @@
"""Resilient generated-audio manager (plan.md Audio). """Procedural sound effects via pygame.mixer.
Every sound is synthesized in memory from a stdlib `array` of PCM samples — no A handful of short tones are synthesized in memory with stdlib ``array`` (no
asset files. The mixer is initialized once, lazily and defensively: if the audio asset files). Audio is feedback only: it never mutates game state and never
driver is missing, `mixer.init` fails, or `Sound` creation throws, audio is blocks input. If the mixer cannot initialize (no device, headless run) the
disabled and the game keeps running silently. No public method ever raises. engine degrades to silent no-ops and never raises.
""" """
from __future__ import annotations from __future__ import annotations
import array import array
import math import math
import random from typing import Any
try:
import pygame import pygame
_HAS_PYGAME = True
except Exception: # pragma: no cover - pygame is a hard dep, but stay safe
pygame = None
_HAS_PYGAME = False
_FREQ = 22050
_SIZE = -16 # 16-bit signed
_CHANNELS = 1
_BUFFER = 256
# name -> synthesis spec: freq (Hz), dur (s), decay (envelope rate), # (base_freq_hz, duration_ms, volume, sweep_to_freq). sweep 0 => steady tone.
# kind (sine | square | noise | sweep), optional freq2 (sweep target). _SFX: dict[str, tuple[int, int, float, int]] = {
_SPECS: dict[str, dict] = { "hit": (330, 70, 0.35, 180),
"hit": dict(freq=330, dur=0.07, decay=9.0, kind="square"), "crit": (660, 110, 0.45, 990),
"miss": dict(freq=180, dur=0.06, decay=10.0, kind="sine"), "miss": (200, 60, 0.20, 120),
"damage": dict(freq=120, dur=0.18, decay=5.0, kind="noise"), "damage": (140, 120, 0.40, 70),
"pickup": dict(freq=660, dur=0.10, decay=8.0, kind="sweep", freq2=990), "pickup": (520, 70, 0.30, 780),
"use": dict(freq=520, dur=0.12, decay=7.0, kind="sweep", freq2=780), "use": (700, 90, 0.30, 520),
"stairs": dict(freq=400, dur=0.16, decay=5.0, kind="sweep", freq2=600), "stairs": (440, 140, 0.35, 880),
"levelup": dict(freq=523, dur=0.30, decay=3.0, kind="sweep", freq2=1046), "levelup": (523, 220, 0.40, 1046),
"death": dict(freq=200, dur=0.45, decay=2.5, kind="sweep", freq2=80), "death": (300, 420, 0.45, 70),
"victory": dict(freq=523, dur=0.50, decay=2.0, kind="sweep", freq2=1568), "victory": (523, 480, 0.45, 1568),
"menu": (600, 50, 0.22, 600),
} }
class AudioManager: def _synth(freq: int, ms: int, volume: float, sweep: int) -> bytes:
"""Generates and plays short SFX; degrades to silence on any audio fault.""" n = max(1, int(_FREQ * ms / 1000))
buf = array.array("h")
for i in range(n):
t = i / _FREQ
f = freq + (sweep - freq) * (i / n) if sweep else freq
env = (1.0 - i / n) ** 1.2 # quick decay envelope
val = int(volume * 32767 * env * math.sin(2 * math.pi * f * t))
buf.append(max(-32768, min(32767, val)))
return buf.tobytes()
def __init__(self) -> None:
class AudioEngine:
"""Tiny SFX player. Silent and raise-free when no audio device is present."""
def __init__(self, enabled: bool = True) -> None:
self.muted: bool = False self.muted: bool = False
self._ok: bool = False self.available: bool = False
self._sounds: dict = {} self._sounds: dict[str, Any] = {}
self._init() if not enabled:
return
# Always attempt init ourselves so a forced failure (e.g. a monkeypatched
# pygame.mixer.init that raises) is observed here, not masked by an
# earlier pygame.init() that may have quietly succeeded.
try:
pygame.mixer.init(frequency=_FREQ, size=_SIZE, channels=_CHANNELS, buffer=_BUFFER)
except Exception:
self.available = False
return
try:
for name, (f, ms, vol, sweep) in _SFX.items():
self._sounds[name] = pygame.mixer.Sound(buffer=_synth(f, ms, vol, sweep))
self.available = True
except Exception:
# Mixer init'd but Sound creation failed: stay silent, stay safe.
self._sounds = {}
self.available = False
def play(self, name: str) -> None: def play(self, name: str) -> None:
try: if not self.available or self.muted:
if self.muted or not self._ok:
return return
snd = self._sounds.get(name) snd = self._sounds.get(name) or self._sounds.get("hit")
if snd is not None: if snd is None:
return
try:
snd.play() snd.play()
except Exception: except Exception:
pass pass # audio is best-effort; never propagate a playback error
def toggle_mute(self) -> None: def toggle_mute(self) -> bool:
self.muted = not self.muted self.muted = not self.muted
return self.muted
# -- internal ------------------------------------------------------------- #
def _init(self) -> None:
if not _HAS_PYGAME:
return
try:
if not pygame.mixer.get_init():
pygame.mixer.init()
except Exception:
self._ok = False
return
self._ok = True
for name, spec in _SPECS.items():
try:
self._sounds[name] = self._make_sound(spec)
except Exception:
pass # that one effect just won't play; others may still work
def _make_sound(self, spec: dict): if __name__ == "__main__":
info = pygame.mixer.get_init() pygame.init()
if info is None: eng = AudioEngine(enabled=True)
raise RuntimeError("mixer not initialized") print("available:", eng.available, "muted:", eng.muted)
rate, size, channels = info eng.play("hit")
code = "h" if abs(size) == 16 else "b" eng.toggle_mute()
maxv = (1 << (abs(size) - 1)) - 1 print("toggled mute ->", eng.muted)
n = max(1, int(rate * spec["dur"])) pygame.quit()
freq = spec["freq"]
freq2 = spec.get("freq2")
decay = spec["decay"]
kind = spec["kind"]
vol = 0.45
rng = random.Random(0x5EED)
buf = array.array(code)
for i in range(n):
t = i / rate
frac = i / n
f = freq + (freq2 - freq) * frac if (kind == "sweep" and freq2) else freq
if kind == "noise":
wave = rng.uniform(-1.0, 1.0)
elif kind == "square":
wave = 1.0 if math.sin(2 * math.pi * f * t) >= 0 else -1.0
else:
wave = math.sin(2 * math.pi * f * t)
env = math.exp(-decay * t)
s = int(maxv * env * wave * vol)
if s > maxv:
s = maxv
elif s < -maxv:
s = -maxv
buf.extend([s] * channels)
return pygame.mixer.Sound(buffer=buf.tobytes())
+20 -53
View File
@@ -1,60 +1,27 @@
"""Turn-based combat resolution (plan.md §4). """Combat resolution: hit chance, armor reduction, critical hits."""
`attack` works for any attacker/defender pair: a Player uses total_power /
total_armor (gear + effects), an Enemy uses its raw stats. The caller owns
death consequences (XP, removal, state changes); attack only resolves the swing
and logs the immediate feedback.
"""
from __future__ import annotations from __future__ import annotations
import random import random
from dataclasses import dataclass
from typing import Any
def attack(attacker, defender, rng=None, log=None) -> dict: @dataclass
r = rng if rng is not None else random.Random() class AttackRoll:
hit: bool
acc = getattr(attacker, "accuracy", 0) crit: bool
eva = getattr(defender, "evasion", 0) damage: int
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05))
attacker_is_player = hasattr(attacker, "total_power")
defender_is_player = hasattr(defender, "total_armor")
base = attacker.total_power() if attacker_is_player else attacker.power
crit_chance = getattr(attacker, "crit_chance", 0.0)
hit = r.random() < hit_chance
crit = False
damage = 0
if hit:
arm = defender.total_armor() if defender_is_player else defender.armor
reduced = max(0, base - arm)
crit = r.random() < crit_chance
damage = reduced * (2 if crit else 1)
defender.hp -= damage
killed = defender.hp <= 0
if log is not None:
_log_swing(log, attacker, defender, hit, crit, damage, attacker_is_player)
return {"hit": hit, "damage": damage, "crit": crit, "killed": killed}
def _log_swing(log: list, attacker, defender, hit: bool, crit: bool, def roll_attack(attacker: Any, defender: Any, rng: random.Random = random) -> AttackRoll:
damage: int, attacker_is_player: bool) -> None: hit_chance = 0.7 + (attacker.accuracy - defender.evasion) * 0.05
if not hit: hit_chance = max(0.1, min(0.95, hit_chance))
if attacker_is_player: base = attacker.power + getattr(attacker, "weapon_power", 0)
log.append(f"You miss the {defender.name}") # Player exposes effective armor via total_armor(); plain objects/enemies use .armor.
else: total_armor = getattr(defender, "total_armor", None)
log.append(f"{attacker.name} misses you") armor = total_armor() if callable(total_armor) else getattr(defender, "armor", 0)
return reduced = max(0, base - armor)
if attacker_is_player: if rng.random() >= hit_chance:
if crit: return AttackRoll(hit=False, crit=False, damage=0)
log.append(f"Critical hit! You hit the {defender.name} for {damage} damage!") crit = rng.random() < attacker.crit_chance
else: return AttackRoll(hit=True, crit=crit, damage=reduced * (2 if crit else 1))
log.append(f"You hit the {defender.name} for {damage} damage!")
else:
if crit:
log.append(f"{attacker.name} critically strikes you for {damage} damage!")
else:
log.append(f"{attacker.name} hits you for {damage} damage!")
+56 -49
View File
@@ -1,87 +1,94 @@
"""Recursive shadowcasting field of view over 8 octants (plan.md §2). """Recursive shadowcasting field of view over 8 octants."""
Written from scratch. Walls block sight, but a wall reached by a light ray is
itself visible (you see the wall face). `compute_fov` mutates `game_map.visible`
to match the set it returns.
"""
from __future__ import annotations from __future__ import annotations
# Per-octant transforms: (xx, xy, yx, yy) map scan offsets (dx, dy) to map space. from typing import Any
from data.constants import FLOOR, SIGHT_RADIUS
# (xx, xy, yx, yy) transforms covering the 8 octants around the origin.
_OCTANTS: tuple[tuple[int, int, int, int], ...] = ( _OCTANTS: tuple[tuple[int, int, int, int], ...] = (
(1, 0, 0, 1), (0, 1, 1, 0), (0, -1, 1, 0), (-1, 0, 0, 1), ( 1, 0, 0, 1),
(-1, 0, 0, -1), (0, -1, -1, 0), (0, 1, -1, 0), (1, 0, 0, -1), ( 0, 1, 1, 0),
( 0, -1, 1, 0),
(-1, 0, 0, 1),
(-1, 0, 0, -1),
( 0, -1, -1, 0),
( 0, 1, -1, 0),
( 1, 0, 0, -1),
) )
def compute_fov(game_map, ox: int, oy: int, radius: int = 8) -> set[tuple[int, int]]: def compute_fov(
"""Return the set of visible tiles from (ox, oy); also set game_map.visible.""" game_map: Any, origin: tuple[int, int], radius: int = SIGHT_RADIUS
width, height = game_map.width, game_map.height ) -> set[tuple[int, int]]:
"""Set of tiles visible from ``origin`` within ``radius``.
Walls block sight but a wall touched by the beam is itself reported
visible (so it renders as a seen wall when adjacent to lit floor).
"""
tiles = game_map.tiles tiles = game_map.tiles
cx, cy = origin
# Fresh visible grid every call so stale tiles never linger. r2 = radius * radius
for y in range(height): visible: set[tuple[int, int]] = {(cx, cy)}
vrow = game_map.visible[y]
for x in range(width):
vrow[x] = False
visible: set[tuple[int, int]] = set()
def blocks(x: int, y: int) -> bool: def blocks(x: int, y: int) -> bool:
if 0 <= x < width and 0 <= y < height: if not game_map.in_bounds(x, y):
return tiles[y][x] == 0 return True
return True # out of bounds behaves as wall return tiles[y][x] != FLOOR
def light(x: int, y: int) -> None:
if 0 <= x < width and 0 <= y < height:
visible.add((x, y))
if not (0 <= ox < width and 0 <= oy < height):
return visible
light(ox, oy) # origin is always seen
r2 = radius * radius
def cast(row: int, start: float, end: float, def cast(row: int, start: float, end: float,
xx: int, xy: int, yx: int, yy: int) -> None: xx: int, xy: int, yx: int, yy: int) -> None:
if start < end: if start < end:
return return
new_start = start
for j in range(row, radius + 1): for j in range(row, radius + 1):
dy = -j
dx = -j - 1 dx = -j - 1
dy = -j
blocked = False blocked = False
new_start = end
while dx <= 0: while dx <= 0:
dx += 1 dx += 1
mx = ox + dx * xx + dy * xy mx = cx + dx * xx + dy * xy
my = oy + dx * yx + dy * yy my = cy + dx * yx + dy * yy
l_slope = (dx - 0.5) / (dy + 0.5) l_slope = (dx - 0.5) / (dy + 0.5)
r_slope = (dx + 0.5) / (dy - 0.5) r_slope = (dx + 0.5) / (dy - 0.5)
if start < r_slope: if start < r_slope:
continue continue
elif end > l_slope: if end > l_slope:
break break
else: if dx * dx + dy * dy <= r2 and game_map.in_bounds(mx, my):
if dx * dx + dy * dy <= r2: visible.add((mx, my))
light(mx, my)
if blocked: if blocked:
if blocks(mx, my): if blocks(mx, my):
new_start = r_slope new_start = r_slope
continue continue
else:
blocked = False blocked = False
start = new_start start = new_start
else: elif blocks(mx, my) and j < radius:
if blocks(mx, my) and j < radius:
blocked = True blocked = True
cast(j + 1, start, l_slope, xx, xy, yx, yy) cast(j + 1, start, l_slope, xx, xy, yx, yy)
new_start = r_slope new_start = r_slope
# Row ended inside a wall run: deeper rows are fully occluded.
if blocked: if blocked:
break break
for (xx, xy, yx, yy) in _OCTANTS: for xx, xy, yx, yy in _OCTANTS:
cast(1, 1.0, 0.0, xx, xy, yx, yy) cast(1, 1.0, 0.0, xx, xy, yx, yy)
for (x, y) in visible:
game_map.visible[y][x] = True
return visible return visible
if __name__ == "__main__":
import random
from engine.map_gen import generate_dungeon
gm = generate_dungeon(seed=1)[0]
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
seen = compute_fov(gm, (sx, sy))
for y in range(gm.height):
print("".join(
"@" if (x, y) == (sx, sy) else
"o" if (x, y) in seen else
("." if gm.walkable(x, y) else "#")
for x in range(gm.width)
))
print(f"visible={len(seen)} (random seed used only by map_gen)", random.random())
+114 -105
View File
@@ -1,130 +1,139 @@
"""GameSession: the single source of truth for all mutable game state. """GameSession: the single source of truth for all mutable state.
It holds the player, all 10 floors, the message log, turn counter, and game ``new_session`` generates all 10 floors AND populates them with enemies/items
state string. `new_game` builds a fresh dive; `recompute_fov` refreshes the (keep generation in map_gen, content spawning here). Floor 9 always carries the
player's sight and merges it into the explored memory. Ancient Dragon so the boss is killable/victory-triggerable on a real playthrough.
""" """
from __future__ import annotations from __future__ import annotations
import json
import os
import random import random
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any
from data import constants as C
from engine import map_gen
from engine.fov import compute_fov
from entities.player import Player from entities.player import Player
from engine import map_gen
from data import enemies as ENEMIES
from data import items as ITEMS
from data.constants import BOSS_ROOM_W, BOSS_ROOM_H, MAP_W, MAP_H
@dataclass(slots=True) @dataclass(slots=True)
class GameSession: class GameSession:
player: Player player: Any = None
dungeon: list dungeon: list = field(default_factory=list)
current_floor: int = 0 current_floor: int = 0
log: list = field(default_factory=list) log: list = field(default_factory=list)
turn: int = 0 turn: int = 0
state: str = "playing" state: str = "playing"
rng: random.Random = field(default_factory=random.Random)
def new_game(seed: int | None = None) -> GameSession: # Enemy roster gated by depth (plan.md Enemy Roster "Floors" column).
_FLOOR_ENEMIES: dict[int, list[str]] = {
0: ["rat", "goblin"],
1: ["rat", "goblin"],
2: ["rat", "goblin", "skeleton_archer"],
3: ["rat", "goblin", "skeleton_archer", "orc_warrior"],
4: ["goblin", "skeleton_archer", "orc_warrior", "green_slime"],
5: ["goblin", "skeleton_archer", "orc_warrior", "wraith", "green_slime"],
6: ["skeleton_archer", "orc_warrior", "wraith", "green_slime"],
7: ["skeleton_archer", "orc_warrior", "wraith", "green_slime"],
8: ["orc_warrior", "wraith", "green_slime", "skeleton_archer"],
}
# (min_enemies, max_enemies, min_items, max_items) per depth band (plan.md table).
_FLOOR_COUNTS: dict[int, tuple[int, int, int, int]] = {
0: (3, 4, 2, 3), 1: (3, 4, 2, 3),
2: (4, 6, 2, 3), 3: (4, 6, 2, 3),
4: (5, 7, 3, 4), 5: (5, 7, 3, 4),
6: (6, 8, 3, 4), 7: (6, 8, 3, 4),
8: (7, 9, 4, 5),
}
# Item pool split by depth (better weapons/armor appear deeper; consumables uniform).
_DEEP_WEAPONS = ["battle_axe", "war_hammer"]
_MID_WEAPONS = ["short_sword", "battle_axe"]
_SHALLOW_WEAPONS = ["rusty_dagger", "short_sword"]
_DEEP_ARMOR = ["chain_mail", "plate_armor"]
_SHALLOW_ARMOR = ["leather_armor", "chain_mail"]
_CONSUMABLES = ["healing_potion", "strength_potion", "invisibility_potion",
"fireball_scroll", "teleport_scroll", "mapping_scroll"]
def _walkable_tiles(gm: Any) -> list[tuple[int, int]]:
return [(x, y) for y in range(gm.height) for x in range(gm.width)
if gm.walkable(x, y)]
def _populate_standard(gm: Any, rng: random.Random) -> None:
pool = _FLOOR_ENEMIES.get(gm.floor_index, ["goblin"])
lo_e, hi_e, lo_i, hi_i = _FLOOR_COUNTS.get(gm.floor_index, (3, 4, 2, 3))
spawn = gm.spawn
tiles = [t for t in _walkable_tiles(gm)
if spawn is None or max(abs(t[0] - spawn[0]), abs(t[1] - spawn[1])) >= 4]
rng.shuffle(tiles)
def take() -> tuple[int, int] | None:
return tiles.pop() if tiles else None
for _ in range(rng.randint(lo_e, hi_e)):
pos = take()
if pos is None:
break
kind = rng.choice(pool)
gm.entities.append(ENEMIES.make_enemy(kind, pos[0], pos[1]))
fi = gm.floor_index
if fi <= 1:
weapons, armors = _SHALLOW_WEAPONS, _SHALLOW_ARMOR
elif fi <= 4:
weapons, armors = _MID_WEAPONS, _SHALLOW_ARMOR
else:
weapons, armors = _DEEP_WEAPONS, _DEEP_ARMOR
for _ in range(rng.randint(lo_i, hi_i)):
pos = take()
if pos is None:
break
roll = rng.random()
if roll < 0.35:
kind = rng.choice(weapons)
elif roll < 0.55:
kind = rng.choice(armors)
else:
kind = rng.choice(_CONSUMABLES)
gm.entities.append(ITEMS.make_item(kind, pos[0], pos[1]))
def _populate_boss(gm: Any) -> None:
# Boss arena: dragon on the far side of the room, two potions near the entrance.
rx = (MAP_W - BOSS_ROOM_W) // 2
ry = (MAP_H - BOSS_ROOM_H) // 2
mid_y = ry + BOSS_ROOM_H // 2
dragon = ENEMIES.make_enemy("ancient_dragon", rx + BOSS_ROOM_W - 2, mid_y)
gm.entities.append(dragon)
gm.entities.append(ITEMS.make_item("healing_potion", rx + 2, mid_y))
gm.entities.append(ITEMS.make_item("healing_potion", rx + 2, mid_y + 1))
def populate_floor(gm: Any, rng: random.Random) -> None:
"""Fill a generated floor's entity list with enemies + items (in place)."""
if gm.floor_index == 9:
_populate_boss(gm)
else:
_populate_standard(gm, rng)
def new_session(seed: int = 0) -> GameSession:
rng = random.Random(seed) rng = random.Random(seed)
# generate_dungeon draws from the global random module; seed it too so the dungeon = map_gen.generate_dungeon(seed=seed)
# entire dive is deterministic from `seed`. for gm in dungeon:
random.seed(seed) populate_floor(gm, rng)
spawn = dungeon[0].spawn or (1, 1)
player = Player(0, 0) player = Player(x=spawn[0], y=spawn[1])
return GameSession(
dungeon = []
for fi in range(C.FLOORS):
floor = map_gen.generate_dungeon(fi)
map_gen.populate(floor, fi, rng=rng)
dungeon.append(floor)
# Player starts at the center of the first room on floor 0.
spawn = dungeon[0].rooms[0].center
if not map_gen.is_walkable(dungeon[0], *spawn):
spawn = _first_walkable(dungeon[0])
player.x, player.y = spawn
session = GameSession(
player=player, player=player,
dungeon=dungeon, dungeon=dungeon,
current_floor=0, current_floor=0,
log=["You enter the Underdepths. Find the stairs and descend."], log=["You descend into the Underdepths."],
turn=0, turn=0,
state="playing", state="playing",
rng=rng,
) )
recompute_fov(session)
return session
def recompute_fov(session: GameSession) -> None:
floor = session.dungeon[session.current_floor]
visible = compute_fov(floor, session.player.x, session.player.y, C.SIGHT_RADIUS)
for (x, y) in visible:
floor.explored[y][x] = True
def _first_walkable(game_map) -> tuple[int, int]:
for y in range(game_map.height):
for x in range(game_map.width):
if game_map.tiles[y][x] == 1:
return (x, y)
return (1, 1)
# --------------------------------------------------------------------------- #
# Persistence + permadeath
# --------------------------------------------------------------------------- #
_GAME_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _save_path(path: str) -> str:
"""Resolve a save path relative to the game directory unless it is absolute."""
return path if os.path.isabs(path) else os.path.join(_GAME_DIR, path)
def save(session: GameSession, path: str = "save.json") -> str:
"""Serialize the session to JSON in the game directory. Returns the file path."""
from engine.serializers import session_to_dict
full = _save_path(path)
with open(full, "w", encoding="utf-8") as f:
json.dump(session_to_dict(session), f)
return full
def load(path: str = "save.json") -> GameSession:
"""Read a saved session JSON and rebuild a live GameSession (FOV recomputed)."""
from engine.serializers import dict_to_session
with open(_save_path(path), "r", encoding="utf-8") as f:
return dict_to_session(json.load(f))
def has_save(path: str = "save.json") -> bool:
"""True when a save file exists (drives the menu's 'Continue' entry)."""
return os.path.isfile(_save_path(path))
def delete_save(path: str = "save.json") -> None:
"""Remove the save file if present. Never raises."""
full = _save_path(path)
try:
if os.path.isfile(full):
os.remove(full)
except OSError:
pass
def mark_dead(session: GameSession) -> None:
"""End the run on player death: flag the state and delete the save (permadeath)."""
session.state = "dead"
delete_save()
def mark_victory(session: GameSession) -> None:
"""End the run on victory: flag the state and delete the save."""
session.state = "victory"
delete_save()
+152 -254
View File
@@ -1,24 +1,28 @@
"""BSP dungeon generation, the GameMap/Rect model, and per-floor population.""" """BSP dungeon generation.
Floors 0..8: a region recursively split into non-overlapping leaf regions,
each gets a carved room, rooms are chained by L-corridors (guarantees a
connected walkable graph), spawn in the first room, stairs in the room
farthest from spawn. Reachability is flood-fill-verified with a fallback
direct corridor.
Floor 9 (boss arena): a single large room, no descent.
"""
from __future__ import annotations from __future__ import annotations
import random import random
from collections import deque
from dataclasses import dataclass from dataclasses import dataclass
from data import constants as C from data.constants import (
from entities.enemy import make_enemy, kinds_for_floor MAP_W, MAP_H, FLOOR_COUNT, WALL, FLOOR,
from entities.item import make_item, item_pool_for_floor ROOM_MIN_W, ROOM_MIN_H, ROOM_MAX_W, ROOM_MAX_H,
BSP_MIN_HALF, BSP_LEAVES_MIN, BSP_LEAVES_MAX,
# BSP / room sizing. Rooms are 4x4..10x8 (plan.md §1); leaves must hold one. BOSS_ROOM_W, BOSS_ROOM_H,
MIN_LEAF: int = 8 )
MIN_ROOM_W: int = 4
MIN_ROOM_H: int = 4
MAX_ROOM_W: int = 10
MAX_ROOM_H: int = 8
BOSS_ROOM_W: int = 20
BOSS_ROOM_H: int = 15
@dataclass(slots=True) @dataclass
class Rect: class Rect:
x: int x: int
y: int y: int
@@ -29,281 +33,175 @@ class Rect:
def center(self) -> tuple[int, int]: def center(self) -> tuple[int, int]:
return (self.x + self.w // 2, self.y + self.h // 2) return (self.x + self.w // 2, self.y + self.h // 2)
def intersects(self, other: "Rect") -> bool:
return (self.x < other.x + other.w
and self.x + self.w > other.x
and self.y < other.y + other.h
and self.y + self.h > other.y)
@dataclass(slots=True) @dataclass(slots=True)
class GameMap: class GameMap:
width: int width: int
height: int height: int
tiles: list[list[int]] # 0 = wall, 1 = floor tiles: list[list[int]]
rooms: list[Rect] rooms: list[Rect]
explored: list[list[bool]] explored: list[list[bool]]
visible: list[list[bool]] visible: list[list[bool]]
entities: list # enemies + items present on this floor entities: list
stairs_down: tuple[int, int] stairs_down: tuple[int, int] | None
spawn: tuple[int, int] | None
floor_index: int floor_index: int
def in_bounds(self, x: int, y: int) -> bool:
return 0 <= x < self.width and 0 <= y < self.height
def is_walkable(game_map: GameMap, x: int, y: int) -> bool: def walkable(self, x: int, y: int) -> bool:
"""True if (x, y) is in bounds and a floor tile.""" return self.in_bounds(x, y) and self.tiles[y][x] == FLOOR
if not (0 <= x < game_map.width and 0 <= y < game_map.height):
return False
return game_map.tiles[y][x] == 1
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------- carving
# Generation def _carve_rect(tiles: list[list[int]], r: Rect) -> None:
# --------------------------------------------------------------------------- # for y in range(r.y, r.y + r.h):
def generate_dungeon(floor_index: int, width: int = C.MAP_WIDTH, for x in range(r.x, r.x + r.w):
height: int = C.MAP_HEIGHT) -> GameMap: tiles[y][x] = FLOOR
"""Generate one floor via BSP (floors 0-8) or a boss arena (floor 9).
Uses the global `random` state so new_game(seed) can seed the whole dive.
"""
tiles: list[list[int]] = [[0] * width for _ in range(height)]
if floor_index == C.FLOORS - 1:
return _boss_arena(floor_index, width, height, tiles)
# Working area sits inside the 1-tile wall border.
root = {"x": 1, "y": 1, "w": width - 2, "h": height - 2}
_build_bsp(root, random.randint(5, 8))
leaves: list[dict] = []
_collect_leaves(root, leaves)
rooms: list[Rect] = []
for leaf in leaves:
leaf["room"] = _carve_room(leaf, tiles, width, height)
rooms.append(leaf["room"])
_connect(root, tiles, width, height)
# Stairs go in the room farthest from the spawn room.
spawn = rooms[0].center
stairs_room = max(rooms, key=lambda r: _dist2(r.center, spawn))
explored = [[False] * width for _ in range(height)]
visible = [[False] * width for _ in range(height)]
return GameMap(width, height, tiles, rooms, explored, visible, [],
stairs_room.center, floor_index)
def _build_bsp(root: dict, target_splits: int) -> None: def _carve_h(tiles: list[list[int]], x1: int, x2: int, y: int) -> None:
"""Split the largest splittable leaf until target_splits splits are done.""" if x2 < x1:
splittable = [root] x1, x2 = x2, x1
done = 0 for x in range(x1, x2 + 1):
prefer_horiz = True tiles[y][x] = FLOOR
while done < target_splits and splittable:
splittable.sort(key=lambda n: n["w"] * n["h"], reverse=True)
node = splittable.pop(0)
halves = _split_node(node, prefer_horiz)
prefer_horiz = not prefer_horiz
if halves is None:
continue # this leaf can't be split; it stays a leaf
left, right = halves
node["left"] = left
node["right"] = right
splittable.append(left)
splittable.append(right)
done += 1
def _split_node(node: dict, prefer_horiz: bool) -> tuple[dict, dict] | None: def _carve_v(tiles: list[list[int]], y1: int, y2: int, x: int) -> None:
"""Split a region on the preferred axis, falling back to the other. if y2 < y1:
y1, y2 = y2, y1
for y in range(y1, y2 + 1):
tiles[y][x] = FLOOR
Returns the two child regions, or None if neither axis can be split.
""" def _carve_corridor(tiles: list[list[int]], a: tuple[int, int],
use_horiz = prefer_horiz b: tuple[int, int], rng: random.Random) -> None:
if use_horiz and node["w"] < 2 * MIN_LEAF: ax, ay = a
use_horiz = False bx, by = b
if not use_horiz and node["h"] < 2 * MIN_LEAF: if rng.random() < 0.5:
use_horiz = True _carve_h(tiles, ax, bx, ay)
length = node["w"] if use_horiz else node["h"] _carve_v(tiles, ay, by, bx)
if length < 2 * MIN_LEAF:
return None
p = random.randint(MIN_LEAF, length - MIN_LEAF)
if use_horiz:
left = {"x": node["x"], "y": node["y"], "w": p, "h": node["h"]}
right = {"x": node["x"] + p, "y": node["y"], "w": node["w"] - p, "h": node["h"]}
else: else:
left = {"x": node["x"], "y": node["y"], "w": node["w"], "h": p} _carve_v(tiles, ay, by, ax)
right = {"x": node["x"], "y": node["y"] + p, "w": node["w"], "h": node["h"] - p} _carve_h(tiles, ax, bx, by)
return left, right
def _collect_leaves(node: dict, out: list[dict]) -> None: # --------------------------------------------------------------------- bsp tree
if "left" in node: def _bsp(root: Rect, rng: random.Random) -> list[Rect]:
_collect_leaves(node["left"], out) target = rng.randint(BSP_LEAVES_MIN, BSP_LEAVES_MAX)
_collect_leaves(node["right"], out) leaves: list[Rect] = []
frontier: list[Rect] = [root]
while frontier:
node = frontier.pop()
if len(leaves) + len(frontier) + 1 >= target:
leaves.append(node)
continue
can_v = node.w >= 2 * BSP_MIN_HALF
can_h = node.h >= 2 * BSP_MIN_HALF
if not (can_v or can_h):
leaves.append(node)
continue
vertical = can_v and (not can_h or rng.random() < node.w / (node.w + node.h))
if vertical:
s = rng.randint(BSP_MIN_HALF, node.w - BSP_MIN_HALF)
frontier.append(Rect(node.x, node.y, s, node.h))
frontier.append(Rect(node.x + s, node.y, node.w - s, node.h))
else: else:
out.append(node) s = rng.randint(BSP_MIN_HALF, node.h - BSP_MIN_HALF)
frontier.append(Rect(node.x, node.y, node.w, s))
frontier.append(Rect(node.x, node.y + s, node.w, node.h - s))
return leaves
def _carve_room(leaf: dict, tiles: list[list[int]], width: int, height: int) -> Rect: def _room_in(leaf: Rect, tiles: list[list[int]], rng: random.Random) -> Rect:
"""Carve a room (4x4..10x8) inside the leaf, shrunk from its edges.""" max_w = leaf.w - 2
shrink = random.randint(1, 2) max_h = leaf.h - 2
max_w = max(MIN_ROOM_W, leaf["w"] - 2 * shrink) w = rng.randint(ROOM_MIN_W, min(ROOM_MAX_W, max_w))
max_h = max(MIN_ROOM_H, leaf["h"] - 2 * shrink) h = rng.randint(ROOM_MIN_H, min(ROOM_MAX_H, max_h))
rw = random.randint(MIN_ROOM_W, min(MAX_ROOM_W, max_w)) x = rng.randint(leaf.x + 1, leaf.x + 1 + max(0, max_w - w))
rh = random.randint(MIN_ROOM_H, min(MAX_ROOM_H, max_h)) y = rng.randint(leaf.y + 1, leaf.y + 1 + max(0, max_h - h))
ox = random.randint(shrink, max(shrink, leaf["w"] - rw - shrink)) room = Rect(x, y, w, h)
oy = random.randint(shrink, max(shrink, leaf["h"] - rh - shrink)) _carve_rect(tiles, room)
rx = leaf["x"] + ox return room
ry = leaf["y"] + oy
for y in range(ry, ry + rh):
for x in range(rx, rx + rw):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
return Rect(rx, ry, rw, rh)
def _connect(node: dict, tiles: list[list[int]], width: int, height: int) -> Rect | None: # ---------------------------------------------------------------- reachability
"""Carve L-corridors between sibling subtree rooms so all rooms connect.""" def _flood(tiles: list[list[int]], start: tuple[int, int],
if "left" not in node: width: int, height: int) -> set[tuple[int, int]]:
return node.get("room") sx, sy = start
lr = _connect(node["left"], tiles, width, height) seen = {(sx, sy)}
rr = _connect(node["right"], tiles, width, height) dq = deque([(sx, sy)])
if lr is not None and rr is not None: while dq:
_carve_corridor(lr.center, rr.center, tiles, width, height) x, y = dq.popleft()
return lr if lr is not None else rr for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if (nx, ny) in seen:
continue
def _carve_corridor(a: tuple[int, int], b: tuple[int, int], if 0 <= nx < width and 0 <= ny < height and tiles[ny][nx] == FLOOR:
tiles: list[list[int]], width: int, height: int) -> None: seen.add((nx, ny))
x1, y1 = a dq.append((nx, ny))
x2, y2 = b return seen
if random.random() < 0.5:
_h_tunnel(x1, x2, y1, tiles, width, height)
_v_tunnel(y1, y2, x2, tiles, width, height)
else:
_v_tunnel(y1, y2, x1, tiles, width, height)
_h_tunnel(x1, x2, y2, tiles, width, height)
def _h_tunnel(x1: int, x2: int, y: int, tiles: list[list[int]],
width: int, height: int) -> None:
for x in range(min(x1, x2), max(x1, x2) + 1):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
def _v_tunnel(y1: int, y2: int, x: int, tiles: list[list[int]],
width: int, height: int) -> None:
for y in range(min(y1, y2), max(y1, y2) + 1):
if 0 <= y < height and 0 <= x < width:
tiles[y][x] = 1
def _boss_arena(floor_index: int, width: int, height: int,
tiles: list[list[int]]) -> GameMap:
"""Floor 9: a single large room; the dragon is placed by populate()."""
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
rx = (width - rw) // 2
ry = (height - rh) // 2
for y in range(ry, ry + rh):
for x in range(rx, rx + rw):
tiles[y][x] = 1
room = Rect(rx, ry, rw, rh)
stairs = (rx + rw // 2, ry + rh - 2) # unused for descent; victory ends the run
explored = [[False] * width for _ in range(height)]
visible = [[False] * width for _ in range(height)]
return GameMap(width, height, tiles, [room], explored, visible, [],
stairs, floor_index)
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int: def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------- builders
# Population def _boss_floor(floor_index: int) -> GameMap:
# --------------------------------------------------------------------------- # width, height = MAP_W, MAP_H
def populate(game_map: GameMap, floor_index: int, rng: random.Random | None = None) -> None: tiles = [[WALL] * width for _ in range(height)]
"""Place enemies AND items per the plan's per-floor distribution. Never raises. explored = [[False] * width for _ in range(height)]
visible = [[False] * width for _ in range(height)]
Floor 9 (boss) gets the dragon plus exactly two healing potions near the rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
entrance; every other floor gets enemies and items drawn from the roster / rx = (width - rw) // 2
catalog, depth-gated. ry = (height - rh) // 2
""" room = Rect(rx, ry, rw, rh)
r = rng if rng is not None else random _carve_rect(tiles, room)
spawn = (rx + 1, ry + rh // 2)
if floor_index == C.FLOORS - 1: return GameMap(width, height, tiles, [room], explored, visible,
room = game_map.rooms[0] [], None, spawn, floor_index)
dx, dy = room.x + room.w // 2, room.y + 2
if not is_walkable(game_map, dx, dy):
ft = _first_floor_tile(game_map)
if ft is None:
return
dx, dy = ft
game_map.entities.append(make_enemy("ancient_dragon", dx, dy))
_place_boss_potions(game_map, room, r)
return
lo, hi = C.ENEMY_COUNT[floor_index]
n = r.randint(lo, hi)
pool = [
(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
]
if not pool:
return
kinds = kinds_for_floor(floor_index)
if not kinds:
return
r.shuffle(pool)
placed = 0
for tile in pool:
if placed >= n:
break
kind = r.choice(kinds)
game_map.entities.append(make_enemy(kind, tile[0], tile[1]))
placed += 1
_place_items(game_map, floor_index, r)
def _place_items(game_map: GameMap, floor_index: int, r) -> None: def _standard_floor(floor_index: int, rng: random.Random) -> GameMap:
"""Scatter ITEM_COUNT items from the depth-weighted pool across floor tiles.""" width, height = MAP_W, MAP_H
lo, hi = C.ITEM_COUNT[floor_index] tiles = [[WALL] * width for _ in range(height)]
n = r.randint(lo, hi) explored = [[False] * width for _ in range(height)]
pool = [ visible = [[False] * width for _ in range(height)]
(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down leaves = _bsp(Rect(1, 1, width - 2, height - 2), rng)
] rooms = [_room_in(leaf, tiles, rng) for leaf in leaves]
if not pool:
return # Chain-connect consecutive rooms -> connected spanning path of floor tiles.
r.shuffle(pool) for i in range(len(rooms) - 1):
names = item_pool_for_floor(floor_index) _carve_corridor(tiles, rooms[i].center, rooms[i + 1].center, rng)
placed = 0
for tile in pool: spawn = rooms[0].center
if placed >= n: far = max(rooms, key=lambda r: _dist2(r.center, spawn))
break stairs = far.center
game_map.entities.append(make_item(r.choice(names), tile[0], tile[1]))
placed += 1 # Reachability safety net (chain already guarantees it; re-carve if a
# future tweak ever breaks connectivity).
reach = _flood(tiles, spawn, width, height)
if stairs not in reach:
_carve_corridor(tiles, spawn, stairs, rng)
return GameMap(width, height, tiles, rooms, explored, visible,
[], stairs, spawn, floor_index)
def _place_boss_potions(game_map: GameMap, room: Rect, r) -> None: def generate_floor(floor_index: int, rng: random.Random) -> GameMap:
"""Put two Healing Potions by the boss-room entrance (far side from the dragon).""" if floor_index == FLOOR_COUNT - 1:
ex, ey = room.center[0], room.y + room.h - 2 return _boss_floor(floor_index)
placed = 0 return _standard_floor(floor_index, rng)
for dx in (-1, 0, 1):
if placed >= 2:
break
x, y = ex + dx, ey
if is_walkable(game_map, x, y):
game_map.entities.append(make_item("Healing Potion", x, y))
placed += 1
if placed < 2: # entrance row blocked: fall back to any floor tiles
pool = [(x, y) for y in range(game_map.height) for x in range(game_map.width)
if game_map.tiles[y][x] == 1]
r.shuffle(pool)
for (x, y) in pool:
if placed >= 2:
break
game_map.entities.append(make_item("Healing Potion", x, y))
placed += 1
def _first_floor_tile(game_map: GameMap) -> tuple[int, int] | None: def generate_dungeon(seed: int) -> list[GameMap]:
for y in range(game_map.height): rng = random.Random(seed)
for x in range(game_map.width): return [generate_floor(i, rng) for i in range(FLOOR_COUNT)]
if game_map.tiles[y][x] == 1:
return (x, y)
return None
+59 -41
View File
@@ -1,31 +1,42 @@
"""Grid A* pathfinding with a Manhattan heuristic (plan.md §3).""" """Grid A* pathfinding with Manhattan heuristic.
Returns shortest 4-connected paths over a game map's walkable tiles.
"""
from __future__ import annotations from __future__ import annotations
import heapq import heapq
from typing import Any
# 4-connected movement on the tile grid.
_DIRS: tuple[tuple[int, int], ...] = ((1, 0), (-1, 0), (0, 1), (0, -1))
def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] | None: def find_path(
"""Shortest floor path from start to goal, or None if unreachable. game_map: Any,
start: tuple[int, int],
goal: tuple[int, int],
blocked: frozenset[tuple[int, int]] = frozenset(),
) -> list[tuple[int, int]] | None:
"""Shortest 4-connected path from ``start`` to ``goal``.
Walkable tiles are in-bounds floor tiles. `blocked` marks extra impassable The path excludes ``start`` and includes ``goal``. Returns ``[]`` when
tiles (other entities) except that the goal is always reachable even if it ``start == goal`` and ``None`` when no route exists. Walls and every tile
sits in `blocked` (an enemy may path up to its target). Returns the path in ``blocked`` are impassable.
including both endpoints; None if start/goal is a wall or out of bounds.
""" """
sx, sy = start if start == goal:
return []
if not game_map.walkable(*start) or not game_map.walkable(*goal) or goal in blocked:
return None
gx, gy = goal gx, gy = goal
if not _is_floor(game_map, sx, sy) or not _is_floor(game_map, gx, gy): def h(x: int, y: int) -> int:
return None return abs(x - gx) + abs(y - gy)
if start == goal:
return [(sx, sy)]
blocked_set = set(blocked)
open_heap: list[tuple[int, int, tuple[int, int]]] = []
g_score: dict[tuple[int, int], int] = {start: 0} g_score: dict[tuple[int, int], int] = {start: 0}
came_from: dict[tuple[int, int], tuple[int, int]] = {} came_from: dict[tuple[int, int], tuple[int, int]] = {}
counter = 0 counter = 0
heapq.heappush(open_heap, (_manhattan(start, goal), counter, start)) open_heap: list[tuple[int, int, tuple[int, int]]] = [(h(*start), counter, start)]
closed: set[tuple[int, int]] = set() closed: set[tuple[int, int]] = set()
while open_heap: while open_heap:
@@ -33,37 +44,44 @@ def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] |
if current in closed: if current in closed:
continue continue
if current == goal: if current == goal:
return _reconstruct(came_from, current) path: list[tuple[int, int]] = []
node = goal
while node != start:
path.append(node)
node = came_from[node]
path.reverse()
return path
closed.add(current) closed.add(current)
cx, cy = current cx, cy = current
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)): base = g_score[current]
nb = (nx, ny) for dx, dy in _DIRS:
if nb in closed or not _is_floor(game_map, nx, ny): nxt = (cx + dx, cy + dy)
if nxt in closed or nxt in blocked or not game_map.walkable(*nxt):
continue continue
if nb in blocked_set and nb != goal: tentative = base + 1
continue if tentative < g_score.get(nxt, float("inf")):
tentative = g_score[current] + 1 g_score[nxt] = tentative
if tentative < g_score.get(nb, 1_000_000): came_from[nxt] = current
g_score[nb] = tentative
came_from[nb] = current
counter += 1 counter += 1
heapq.heappush(open_heap, (tentative + _manhattan(nb, goal), counter, nb)) heapq.heappush(open_heap, (tentative + h(*nxt), counter, nxt))
return None return None
def _is_floor(game_map, x: int, y: int) -> bool: if __name__ == "__main__":
return (0 <= x < game_map.width and 0 <= y < game_map.height from engine.map_gen import generate_dungeon
and game_map.tiles[y][x] == 1)
gm = generate_dungeon(seed=1)[0]
def _manhattan(a: tuple[int, int], b: tuple[int, int]) -> int: sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
return abs(a[0] - b[0]) + abs(a[1] - b[1]) # identity
assert find_path(gm, (sx, sy), (sx, sy)) == []
# reach stairs
def _reconstruct(came_from: dict, current: tuple[int, int]) -> list[tuple[int, int]]: if gm.stairs_down is not None:
path = [current] p = find_path(gm, (sx, sy), gm.stairs_down)
while current in came_from: assert p is not None and p[-1] == gm.stairs_down, (sx, sy, gm.stairs_down, p)
current = came_from[current] assert (sx, sy) not in p
path.append(current) assert all(gm.walkable(*t) for t in p)
path.reverse() print(f"path spawn->stairs: {len(p)} steps, first {p[:3]}")
return path # no path to a wall
wx = next(x for x in range(gm.width) if not gm.walkable(x, 0))
assert find_path(gm, (sx, sy), (wx, 0)) is None
print("pathfinding self-check: OK")
+103 -203
View File
@@ -1,30 +1,111 @@
"""JSON save/load: exact round-trip serialization of a GameSession. """JSON-safe serialization of GameSession for save/load.
The `visible` grids are intentionally NOT serialized — they are recomputed via The volatile `visible` grid is deliberately excluded from the saved form: it is
`recompute_fov` on load. Every other field of Player / Enemy / Item is preserved recomputed from FOV on load, so persisting it would only bloat the save and risk
verbatim, including per-instance enemy state (damaged HP, last-known position, a stale view. Everything else that survives across a save/quit/relaunch is kept.
small-slime `can_split=False`, act counters) so a loaded dive matches the saved
dive exactly. Entities are reconstructed directly from their serialized fields Tuples are preserved as tuples (not flattened to lists) so a to_dict -> from_dict
rather than via `make_enemy`/`make_item`, which would reset mutable state to the -> to_dict cycle is byte-stable under Python dict equality.
roster/catalog defaults.
""" """
from __future__ import annotations from __future__ import annotations
from engine.game_state import GameSession, recompute_fov from dataclasses import fields
from engine.map_gen import GameMap, Rect from typing import Any
from entities.player import Player
from entities.enemy import Enemy from entities.enemy import Enemy
from entities.entity import Entity
from entities.item import Item from entities.item import Item
from entities.player import Effect, Player from engine.map_gen import GameMap, Rect
from engine.game_state import GameSession
# Discriminators for the polymorphic entity list + room rects.
_DCTAGS: dict[type, str] = {Player: "player", Enemy: "enemy", Item: "item", Rect: "rect"}
def _to_json(v: Any) -> Any:
"""Recursively coerce a value to a JSON-safe structure, preserving tuples."""
if v is None or isinstance(v, (bool, int, float, str)):
return v
if isinstance(v, tuple):
return tuple(_to_json(x) for x in v)
if isinstance(v, list):
return [_to_json(x) for x in v]
if isinstance(v, dict):
return {str(k): _to_json(val) for k, val in v.items()}
tag = _DCTAGS.get(type(v))
if tag is not None:
out: dict[str, Any] = {"__type__": tag}
for f in fields(v):
out[f.name] = _to_json(getattr(v, f.name))
return out
raise TypeError(f"not JSON-serializable: {type(v).__name__}")
def _make_dc(cls: type, d: dict) -> Any:
kwargs = {f.name: _from_json(d[f.name]) for f in fields(cls) if f.name in d}
return cls(**kwargs)
def _from_json(v: Any) -> Any:
"""Inverse of _to_json: rebuild dataclass instances from tagged dicts."""
if v is None or isinstance(v, (bool, int, float, str)):
return v
if isinstance(v, tuple):
return tuple(_from_json(x) for x in v)
if isinstance(v, list):
return [_from_json(x) for x in v]
if isinstance(v, dict):
tag = v.get("__type__")
if tag == "player":
return _make_dc(Player, v)
if tag == "enemy":
return _make_dc(Enemy, v)
if tag == "item":
return _make_dc(Item, v)
if tag == "rect":
return Rect(v["x"], v["y"], v["w"], v["h"])
return {k: _from_json(val) for k, val in v.items()}
raise TypeError(f"cannot decode: {type(v).__name__}")
def _floor_to_dict(gm: GameMap) -> dict:
# `visible` is intentionally absent: recomputed from FOV on load.
return {
"width": gm.width,
"height": gm.height,
"tiles": gm.tiles,
"rooms": [_to_json(r) for r in gm.rooms],
"explored": gm.explored,
"entities": [_to_json(e) for e in gm.entities],
"stairs_down": gm.stairs_down,
"spawn": gm.spawn,
"floor_index": gm.floor_index,
}
def _floor_from_dict(d: dict) -> GameMap:
width, height = d["width"], d["height"]
visible = [[False] * width for _ in range(height)]
stairs = d["stairs_down"]
spawn = d["spawn"]
return GameMap(
width=width,
height=height,
tiles=d["tiles"],
rooms=[_from_json(r) for r in d["rooms"]],
explored=d["explored"],
visible=visible,
entities=[_from_json(e) for e in d["entities"]],
stairs_down=tuple(stairs) if stairs is not None else None,
spawn=tuple(spawn) if spawn is not None else None,
floor_index=d["floor_index"],
)
# --------------------------------------------------------------------------- #
# Top level
# --------------------------------------------------------------------------- #
def session_to_dict(session: GameSession) -> dict: def session_to_dict(session: GameSession) -> dict:
return { return {
"player": _player_to_dict(session.player), "player": _to_json(session.player),
"dungeon": [_map_to_dict(m) for m in session.dungeon], "dungeon": [_floor_to_dict(gm) for gm in session.dungeon],
"current_floor": session.current_floor, "current_floor": session.current_floor,
"turn": session.turn, "turn": session.turn,
"log": list(session.log), "log": list(session.log),
@@ -32,193 +113,12 @@ def session_to_dict(session: GameSession) -> dict:
} }
def dict_to_session(d: dict) -> GameSession: def session_from_dict(d: dict) -> GameSession:
session = GameSession( return GameSession(
player=_dict_to_player(d["player"]), player=_from_json(d["player"]),
dungeon=[_dict_to_map(m) for m in d["dungeon"]], dungeon=[_floor_from_dict(fd) for fd in d["dungeon"]],
current_floor=d["current_floor"], current_floor=d["current_floor"],
log=list(d["log"]),
turn=d["turn"], turn=d["turn"],
log=list(d["log"]),
state=d["state"], state=d["state"],
) )
recompute_fov(session)
return session
# --------------------------------------------------------------------------- #
# Player
# --------------------------------------------------------------------------- #
def _player_to_dict(p: Player) -> dict:
return {
"type": "player",
"x": p.x, "y": p.y,
"name": p.name,
"sprite_key": p.sprite_key,
"blocks": p.blocks,
"hp": p.hp, "max_hp": p.max_hp,
"power": p.power, "armor": p.armor,
"accuracy": p.accuracy, "evasion": p.evasion,
"crit_chance": p.crit_chance, "speed": p.speed,
"level": p.level, "xp": p.xp,
"inventory": [_item_to_dict(i) for i in p.inventory],
"equipped": {
slot: (_item_to_dict(it) if it is not None else None)
for slot, it in p.equipped.items()
},
"effects": [_effect_to_dict(e) for e in p.effects],
"facing": p.facing,
"invisible": p.invisible,
"pending_log": list(p.pending_log),
}
def _dict_to_player(d: dict) -> Player:
p = Player(d["x"], d["y"])
p.name = d["name"]
p.sprite_key = d["sprite_key"]
p.blocks = d["blocks"]
p.hp = d["hp"]
p.max_hp = d["max_hp"]
p.power = d["power"]
p.armor = d["armor"]
p.accuracy = d["accuracy"]
p.evasion = d["evasion"]
p.crit_chance = d["crit_chance"]
p.speed = d["speed"]
p.level = d["level"]
p.xp = d["xp"]
p.inventory = [_dict_to_item(i) for i in d["inventory"]]
p.equipped = {
slot: (_dict_to_item(it) if it is not None else None)
for slot, it in d["equipped"].items()
}
p.effects = [_dict_to_effect(e) for e in d["effects"]]
p.facing = d["facing"]
p.invisible = d["invisible"]
p.pending_log = list(d["pending_log"])
return p
# --------------------------------------------------------------------------- #
# Effects
# --------------------------------------------------------------------------- #
def _effect_to_dict(e: Effect) -> dict:
return {"kind": e.kind, "power": e.power, "duration": e.duration}
def _dict_to_effect(d: dict) -> Effect:
return Effect(kind=d["kind"], power=d["power"], duration=d["duration"])
# --------------------------------------------------------------------------- #
# Floor entities (enemies + items) — discriminated by "type"
# --------------------------------------------------------------------------- #
def _entity_to_dict(e) -> dict:
if isinstance(e, Enemy):
return _enemy_to_dict(e)
if isinstance(e, Item):
return _item_to_dict(e)
return {"type": "entity", "x": e.x, "y": e.y,
"name": getattr(e, "name", ""), "sprite_key": getattr(e, "sprite_key", ""),
"blocks": getattr(e, "blocks", True)}
def _dict_to_entity(d):
t = d.get("type")
if t == "enemy":
return _dict_to_enemy(d)
if t == "item":
return _dict_to_item(d)
return Entity(d["x"], d["y"], d.get("name", ""),
d.get("sprite_key", ""), d.get("blocks", True))
def _enemy_to_dict(e: Enemy) -> dict:
return {
"type": "enemy",
"x": e.x, "y": e.y,
"name": e.name,
"sprite_key": e.sprite_key,
"blocks": e.blocks,
"hp": e.hp, "max_hp": e.max_hp,
"power": e.power, "armor": e.armor,
"accuracy": e.accuracy, "evasion": e.evasion,
"crit_chance": e.crit_chance, "speed": e.speed,
"behavior": e.behavior, "xp_value": e.xp_value,
"last_known_pos": (list(e.last_known_pos)
if e.last_known_pos is not None else None),
"act_counter": e.act_counter,
"can_split": e.can_split,
"ranged_power": e.ranged_power,
}
def _dict_to_enemy(d: dict) -> Enemy:
lkp = d["last_known_pos"]
return Enemy(
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
blocks=d["blocks"],
hp=d["hp"], max_hp=d["max_hp"], power=d["power"], armor=d["armor"],
accuracy=d["accuracy"], evasion=d["evasion"],
crit_chance=d["crit_chance"], speed=d["speed"],
behavior=d["behavior"], xp_value=d["xp_value"],
last_known_pos=(tuple(lkp) if lkp is not None else None),
act_counter=d["act_counter"], can_split=d["can_split"],
ranged_power=d["ranged_power"],
)
def _item_to_dict(it: Item) -> dict:
return {
"type": "item",
"x": it.x, "y": it.y,
"name": it.name,
"sprite_key": it.sprite_key,
"blocks": it.blocks,
"item_type": it.item_type,
"subtype": it.subtype,
"stats": dict(it.stats),
}
def _dict_to_item(d: dict) -> Item:
return Item(
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
blocks=d["blocks"], item_type=d["item_type"],
subtype=d["subtype"], stats=dict(d["stats"]),
)
# --------------------------------------------------------------------------- #
# Map
# --------------------------------------------------------------------------- #
def _rect_to_dict(r: Rect) -> dict:
return {"x": r.x, "y": r.y, "w": r.w, "h": r.h}
def _map_to_dict(m: GameMap) -> dict:
return {
"width": m.width,
"height": m.height,
"tiles": [list(row) for row in m.tiles],
"rooms": [_rect_to_dict(r) for r in m.rooms],
"explored": [list(row) for row in m.explored],
"entities": [_entity_to_dict(e) for e in m.entities],
"stairs_down": list(m.stairs_down),
"floor_index": m.floor_index,
}
def _dict_to_map(d: dict) -> GameMap:
width = d["width"]
height = d["height"]
return GameMap(
width=width, height=height,
tiles=[list(row) for row in d["tiles"]],
rooms=[Rect(r["x"], r["y"], r["w"], r["h"]) for r in d["rooms"]],
explored=[list(row) for row in d["explored"]],
visible=[[False] * width for _ in range(height)],
entities=[_dict_to_entity(e) for e in d["entities"]],
stairs_down=tuple(d["stairs_down"]),
floor_index=d["floor_index"],
)
+22 -69
View File
@@ -1,85 +1,38 @@
"""Enemy entities and the full stat roster from plan.md §Enemy Roster.""" """Enemy entity: stat block + AI behavior descriptor.
Full field set per the tests/smoke.py contract. Stats are populated by
data/enemies.make_enemy (phase 3); the defaults exist so a bare Enemy() is
always constructible.
"""
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any
from entities.entity import Entity
ENEMY_KINDS: list[str] = [
"rat", "goblin", "skeleton_archer", "orc_warrior",
"wraith", "green_slime", "ancient_dragon",
]
# kind -> full roster. `floors` is the (min, max) depth gate from plan.md.
# `ranged` is ranged_power (skeleton bolt / dragon breath); 0 = no ranged.
_ROSTER: dict[str, dict] = {
"rat": dict(
name="Rat", hp=8, power=3, armor=0, accuracy=4, evasion=2, crit=0.05,
speed=1, behavior="wander", xp=5, ranged=0, floors=(0, 3),
),
"goblin": dict(
name="Goblin", hp=15, power=5, armor=1, accuracy=5, evasion=1, crit=0.05,
speed=1, behavior="chase", xp=12, ranged=0, floors=(0, 5),
),
"skeleton_archer": dict(
name="Skeleton Archer", hp=12, power=4, armor=1, accuracy=6, evasion=1, crit=0.10,
speed=1, behavior="ranged", xp=15, ranged=6, floors=(2, 7),
),
"orc_warrior": dict(
name="Orc Warrior", hp=30, power=8, armor=3, accuracy=5, evasion=0, crit=0.10,
speed=1, behavior="flee", xp=25, ranged=0, floors=(3, 8),
),
"wraith": dict(
name="Wraith", hp=20, power=10, armor=0, accuracy=6, evasion=3, crit=0.10,
speed=2, behavior="phase", xp=30, ranged=0, floors=(5, 8),
),
"green_slime": dict(
name="Green Slime", hp=18, power=5, armor=1, accuracy=4, evasion=0, crit=0.05,
speed=1, behavior="split", xp=18, ranged=0, floors=(4, 8),
),
"ancient_dragon": dict(
name="Ancient Dragon", hp=120, power=15, armor=8, accuracy=7, evasion=0, crit=0.15,
speed=1, behavior="chase", xp=200, ranged=15, floors=(9, 9),
),
}
@dataclass(slots=True) @dataclass(slots=True)
class Enemy(Entity): class Enemy:
x: int = 0
y: int = 0
kind: str = ""
name: str = "" name: str = ""
sprite_key: str = "enemy"
hp: int = 1 hp: int = 1
max_hp: int = 1 max_hp: int = 1
power: int = 0 power: int = 1
armor: int = 0 armor: int = 0
accuracy: int = 0 accuracy: int = 4
evasion: int = 0 evasion: int = 0
crit_chance: float = 0.0 crit_chance: float = 0.0
ranged_power: int = 0
speed: int = 1 speed: int = 1
behavior: str = "wander" behavior: str = "wander"
xp_value: int = 0 xp_value: int = 0
last_known_pos: tuple[int, int] | None = None last_known_pos: Any = None
act_counter: int = 0 can_split: bool = False
can_split: bool = True sprite_key: str = ""
ranged_power: int = 0
@property
def make_enemy(kind: str, x: int, y: int) -> Enemy: def xp(self) -> int:
"""Construct an Enemy of the given kind at (x, y) with full roster stats.""" # Contract field is xp_value; gates/tests read .xp. One descriptor,
s = _ROSTER[kind] # no extra storage (slots-safe: name is not a slot).
return Enemy( return self.xp_value
x=x, y=y, name=s["name"], sprite_key=kind,
hp=s["hp"], max_hp=s["hp"], power=s["power"], armor=s["armor"],
accuracy=s["accuracy"], evasion=s["evasion"], crit_chance=s["crit"],
speed=s["speed"], behavior=s["behavior"], xp_value=s["xp"],
ranged_power=s["ranged"],
)
def kinds_for_floor(floor_index: int) -> list[str]:
"""Non-boss enemy kinds allowed to spawn on the given floor (depth-gated)."""
return [
k for k, s in _ROSTER.items()
if k != "ancient_dragon"
and s["floors"][0] <= floor_index <= s["floors"][1]
]
+1 -6
View File
@@ -1,4 +1,4 @@
"""Base entity: a thing with a position on the map.""" """Base entity: position, identity, sprite key."""
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
@@ -6,11 +6,6 @@ from dataclasses import dataclass
@dataclass(slots=True) @dataclass(slots=True)
class Entity: class Entity:
"""Anything that lives on a dungeon tile: player, enemies, items, stairs.
`sprite_key` names the procedural pixel-art sprite to rasterize for it.
`blocks` is True when other entities cannot share its tile.
"""
x: int x: int
y: int y: int
name: str name: str
+13 -60
View File
@@ -1,69 +1,22 @@
"""Items: weapons, armor, potions, scrolls (plan.md §6). """Item entity: identity + effect/equipment payload.
The full fixed catalog lives here. `make_item` builds any catalog entry; Matches the tests/smoke.py contract: x, y, kind, name, category, stats(dict).
`item_pool_for_floor` gives a depth-weighted name list for dungeon population. ``blocks`` defaults False because items share the floor's entity list with
enemies, and the AI blocker check treats a missing ``blocks`` as True — an item
without this field would wrongly block movement.
""" """
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from entities.entity import Entity
@dataclass(slots=True) @dataclass(slots=True)
class Item(Entity): class Item:
"""A carryable thing. `blocks` is False — items never occupy a tile alone.""" x: int = 0
item_type: str = "misc" # weapon | armor | potion | scroll y: int = 0
subtype: str = "" # healing | strength | invisibility | fireball | teleport | mapping kind: str = ""
name: str = ""
category: str = ""
stats: dict = field(default_factory=dict) stats: dict = field(default_factory=dict)
sprite_key: str = ""
blocks: bool = False
# name -> (item_type, subtype, stats, sprite_key). Stats are read by Player /
# actions: weapons carry power (+ optional crit delta), armor carries armor
# (+ optional evasion delta), potions/scrolls carry their effect magnitudes.
_CATALOG: dict[str, tuple[str, str, dict, str]] = {
"Rusty Dagger": ("weapon", "", {"power": 2}, "weapon_dagger"),
"Short Sword": ("weapon", "", {"power": 4}, "weapon_sword"),
"Battle Axe": ("weapon", "", {"power": 7}, "weapon_axe"),
"War Hammer": ("weapon", "", {"power": 10, "crit_chance": -0.05}, "weapon_hammer"),
"Leather Armor": ("armor", "", {"armor": 2}, "armor_leather"),
"Chain Mail": ("armor", "", {"armor": 4}, "armor_chain"),
"Plate Armor": ("armor", "", {"armor": 7, "evasion": -10}, "armor_plate"),
"Healing Potion": ("potion", "healing", {"heal": 30}, "potion_healing"),
"Strength Potion": ("potion", "strength", {"power": 5, "duration": 20}, "potion_strength"),
"Invisibility Potion": ("potion", "invisibility", {"duration": 15}, "potion_invisibility"),
"Scroll of Fireball": ("scroll", "fireball", {"damage": 20, "radius": 3}, "scroll_fireball"),
"Scroll of Teleport": ("scroll", "teleport", {}, "scroll_teleport"),
"Scroll of Mapping": ("scroll", "mapping", {}, "scroll_mapping"),
}
def make_item(name: str, x: int, y: int) -> Item:
"""Construct a catalog Item named `name` at (x, y)."""
itype, subtype, stats, sprite = _CATALOG[name]
return Item(
x=x, y=y, name=name, sprite_key=sprite, blocks=False,
item_type=itype, subtype=subtype, stats=dict(stats),
)
def item_pool_for_floor(floor_index: int) -> list[str]:
"""Depth-weighted item names droppable on this floor (plan.md §6 distribution).
Potions and scrolls are uniform across depth; better weapons/armor appear
deeper. Floor 9 (boss) is handled separately by the populator.
"""
pool = [
"Healing Potion", "Strength Potion", "Invisibility Potion",
"Scroll of Fireball", "Scroll of Teleport", "Scroll of Mapping",
]
if floor_index >= 5:
pool += ["War Hammer", "Plate Armor", "Battle Axe", "Chain Mail",
"Short Sword", "Leather Armor", "Rusty Dagger"]
elif floor_index >= 3:
pool += ["Battle Axe", "Chain Mail", "Short Sword", "Leather Armor", "Rusty Dagger"]
elif floor_index >= 1:
pool += ["Short Sword", "Leather Armor", "Rusty Dagger"]
else:
pool += ["Rusty Dagger", "Leather Armor"]
return pool
+59 -65
View File
@@ -1,87 +1,81 @@
"""The player adventurer: stats, inventory, equipment, leveling.""" """Player: stats, inventory, equipment, and leveling."""
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any
from data import constants as C from data.constants import LEVEL_TABLE, LEVEL_CAP, PLAYER_BASE, STRENGTH_POTION_POWER
from entities.entity import Entity
@dataclass(slots=True) @dataclass(slots=True)
class Effect: class Player:
"""A timed status effect on the player (plan.md §6 potions). x: int = 0
y: int = 0
`kind` is "strength" (+power) or "invisibility". `duration` is turns left; name: str = "Adventurer"
actions.tick decrements it and expires the effect at 0.
"""
kind: str
power: int = 0
duration: int = 0
@dataclass(slots=True)
class Player(Entity):
name: str = "You"
sprite_key: str = "player" sprite_key: str = "player"
# stats blocks: bool = True
hp: int = 50 hp: int = PLAYER_BASE["hp"]
max_hp: int = 50 max_hp: int = PLAYER_BASE["max_hp"]
power: int = 4 power: int = PLAYER_BASE["power"]
armor: int = 0 armor: int = PLAYER_BASE["armor"]
accuracy: int = 5 accuracy: int = PLAYER_BASE["accuracy"]
evasion: int = 2 evasion: int = PLAYER_BASE["evasion"]
crit_chance: float = 0.10 crit_chance: float = PLAYER_BASE["crit_chance"]
speed: int = 1 speed: int = PLAYER_BASE["speed"]
# progression
level: int = 1 level: int = 1
xp: int = 0 xp: int = 0
# gear / effects
inventory: list = field(default_factory=list) inventory: list = field(default_factory=list)
equipped: dict = field(default_factory=dict) equipped_weapon: Any = None
effects: list = field(default_factory=list) equipped_armor: Any = None
facing: str = "down" effect_timers: dict = field(default_factory=dict)
invisible: bool = False
# transient: level-up messages the game loop flushes into the session log @property
pending_log: list = field(default_factory=list) def weapon_power(self) -> int:
# combat.roll_attack reads attacker.power + getattr(weapon_power, 0), so the
# equipped weapon and the strength-potion bonus must surface here for melee.
wp = 0
if self.equipped_weapon is not None:
wp += self.equipped_weapon.stats.get("power", 0)
if self.effect_timers.get("strength", 0) > 0:
wp += STRENGTH_POTION_POWER
return wp
def total_power(self) -> int: def total_power(self) -> int:
"""Base power + equipped weapon bonus + active strength effect.""" return self.power + self.weapon_power
p = self.power
weapon = self.equipped.get("weapon")
if weapon is not None and hasattr(weapon, "stats"):
p += weapon.stats.get("power", 0)
for eff in self.effects:
if getattr(eff, "kind", None) == "strength":
p += getattr(eff, "power", 0)
return int(p)
def total_armor(self) -> int: def total_armor(self) -> int:
"""Base armor + equipped armor bonus."""
a = self.armor a = self.armor
armor = self.equipped.get("armor") if self.equipped_armor is not None:
if armor is not None and hasattr(armor, "stats"): a += self.equipped_armor.stats.get("armor", 0)
a += armor.stats.get("armor", 0) return a
return int(a)
def gain_xp(self, amount: int) -> bool: def equip(self, item: Any) -> None:
"""Award XP, applying chained level-ups from the plan table. if item is None:
return
category = getattr(item, "category", "")
if category == "weapon":
if self.equipped_weapon is not None:
self.inventory.append(self.equipped_weapon)
self.equipped_weapon = item
elif category == "armor":
if self.equipped_armor is not None:
self.inventory.append(self.equipped_armor)
self.equipped_armor = item
else:
self.inventory.append(item)
Fully heals and raises max_hp/power on each level-up. Level-up lines def gain_xp(self, amount: int) -> int:
are buffered into `pending_log` for the game loop to flush. Returns
True if any level-up occurred.
"""
self.xp += amount self.xp += amount
levelled = False gained = 0
while self.level < C.MAX_LEVEL and self.xp >= C.XP_THRESHOLDS[self.level + 1]: while self.level < LEVEL_CAP and self.level - 1 < len(LEVEL_TABLE):
new_level = self.level + 1 need = LEVEL_TABLE[self.level - 1][0]
hp_gain = C.LEVEL_HP_GAIN[new_level] if self.xp < need:
pow_gain = C.LEVEL_POWER_GAIN[new_level] break
self.level = new_level _need, hp_gain, pow_gain = LEVEL_TABLE[self.level - 1]
self.level += 1
self.max_hp += hp_gain self.max_hp += hp_gain
self.power += pow_gain self.power += pow_gain
gained += 1
if gained:
self.hp = self.max_hp self.hp = self.max_hp
levelled = True return gained
self.pending_log.append(
f"You reach level {self.level}! (HP +{hp_gain}, Power +{pow_gain})"
)
return levelled
+248 -359
View File
@@ -1,391 +1,280 @@
"""Underdepths entry point: full game loop + state machine (plan.md §9). """Entry point, game loop, and state machine for Underdepths.
HEADLESS RULE: never force the dummy SDL drivers. Detect headless from the Headless detection honors ``SDL_VIDEODRIVER=='dummy'`` (never forced in code);
ENVIRONMENT the test harness sets (SDL_VIDEODRIVER==dummy). When headless, run ``UNDERDEPTHS_MAX_FRAMES`` bounds a run so the harness can launch this headless
a scripted self-check of `max_frames` frames then return. With no environment and exit cleanly. ``new_game(seed)`` builds a fresh ``GameSession``.
variables, `python main.py` opens a real window with real audio.
State machine: menu -> (howto) -> playing -> {dead, victory, saved} -> menu.
All gameplay intents flow through ``engine.actions.apply_input``; sound effects
are best-effort and never block.
""" """
from __future__ import annotations from __future__ import annotations
import os import os
import re import sys
from typing import Any
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1") import pygame
import pygame # noqa: E402 from data.constants import MAP_W, MAP_H, TILE, COLORS
from engine import actions as act
from engine.audio import AudioEngine
from engine.game_state import new_session
from render.camera import Camera
from render.renderer import Renderer
from engine import actions, game_state # noqa: E402 SCREEN_W = 960
from engine.audio import AudioManager # noqa: E402 SCREEN_H = 600
from render import renderer as R # noqa: E402 FONT_STACK = "monospace,consolas,couriernew,dejavusans"
from render import sprites as RS # noqa: E402 MAXFRAMES_ENV = "UNDERDEPTHS_MAX_FRAMES"
SAVE = "save.json" _MENU = ["New Game", "Continue", "How to Play", "Quit"]
FPS = 60 _HOWTO = [
MOVE_DELAY = 0.11 "UNDERDEPTHS - How to Play",
"",
"Move / attack ....... Arrows or H J K L (walk into an enemy to hit it)",
"Pick up item ........ G (stand on the item first)",
"Descend stairs ...... F (stand on the yellow > stairs first)",
"Inventory list ...... I Equip best gear ... E",
"Quaff potion ........ Q Read scroll ........ R",
"Save & quit ......... S How to Play ........ ?",
"Mute sound .......... M Wait one turn ...... .",
"Cancel / close ...... Esc",
"",
"Descend 10 floors. Slay the Ancient Dragon on floor 10 to win.",
"Walk onto an item's tile, then press G to pick it up.",
"Walk onto the yellow > stairs tile, then press F to descend.",
"",
"Press any key to return.",
]
def _num(s: str): def new_game(seed: int = 0) -> Any:
m = re.search(r"for (\d+) damage", s) return new_session(seed)
return int(m.group(1)) if m else None
def _facing_delta(facing: str): # --------------------------------------------------------------------- helpers
return {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}.get(facing, (0, 1)) def _font(size: int, bold: bool = False) -> pygame.font.Font:
class Game:
def __init__(self, screen, audio, headless: bool) -> None:
self.screen = screen
self.audio = audio
self.headless = headless
self.r = R.Renderer((R.WIN_W, R.WIN_H), audio)
self.session = None
self.view = "menu" # menu | play | dead | victory
self.overlay = None # None | inv | equip | quaff | read | help
self.menu_index = 0
self.t = 0.0
self.move_cd = 0.0
self._prev_log = 0
self._prev_hp = 0
# ------------------------------------------------------------------ #
def _menu_options(self):
opts = ["New Game"]
if game_state.has_save(SAVE):
opts.append("Continue")
opts += ["How to Play", "Quit"]
return opts
def _start_new_game(self) -> None:
game_state.delete_save(SAVE)
self.session = game_state.new_game(seed=None)
self._prev_log = len(self.session.log)
self._prev_hp = self.session.player.hp
self.view = "play"
self.overlay = "help" # How to Play before the first turn
def _continue(self) -> bool:
if not game_state.has_save(SAVE):
return False
try: try:
self.session = game_state.load(SAVE) return pygame.font.SysFont(FONT_STACK, size, bold=bold)
except Exception: except Exception:
return False return pygame.font.Font(None, size)
self._prev_log = len(self.session.log)
self._prev_hp = self.session.player.hp
self.view = "play"
self.overlay = None
return True
# ------------------------------------------------------------------ #
def run(self) -> None: def _draw_text(surf: pygame.Surface, msg: str, pos: tuple[int, int],
color: tuple[int, int, int], font: pygame.font.Font) -> None:
try:
surf.blit(font.render(msg, True, color), pos)
except Exception:
pass
def _play_for_log(audio: AudioEngine, new_lines: list[str]) -> None:
for line in new_lines:
low = line.lower()
if "critical" in low:
audio.play("crit")
elif "defeated" in low or "slew" in low:
audio.play("levelup")
elif "reach level" in low:
audio.play("levelup")
elif "you hit" in low:
audio.play("hit")
elif "miss" in low:
audio.play("miss")
elif "pick up" in low:
audio.play("pickup")
elif "descend" in low:
audio.play("stairs")
elif "equip" in low or "quaff" in low or "read" in low:
audio.play("use")
_KEYMAP = {
pygame.K_UP: "up", pygame.K_DOWN: "down", pygame.K_LEFT: "left", pygame.K_RIGHT: "right",
pygame.K_h: "left", pygame.K_j: "down", pygame.K_k: "up", pygame.K_l: "right",
pygame.K_g: "g", pygame.K_f: "f", pygame.K_i: "i", pygame.K_e: "e",
pygame.K_q: "q", pygame.K_r: "r", pygame.K_PERIOD: "wait",
}
# --------------------------------------------------------------------- screens
def _draw_menu(screen: pygame.Surface, idx: int, has_save: bool,
title_f: pygame.font.Font, opt_f: pygame.font.Font) -> None:
screen.fill(COLORS["bg"])
_draw_text(screen, "UNDERDEPTHS", (SCREEN_W // 2 - 140, 90), COLORS["stairs"], title_f)
_draw_text(screen, "a turn-based roguelike descent", (SCREEN_W // 2 - 150, 140),
COLORS["text_dim"], opt_f)
y = 230
for i, label in enumerate(_MENU):
if label == "Continue" and not has_save:
color = COLORS["text_dim"]
elif i == idx:
color = COLORS["stairs"]
_draw_text(screen, ">", (SCREEN_W // 2 - 130, y), COLORS["stairs"], opt_f)
color = COLORS["stairs"]
else:
color = COLORS["text"]
_draw_text(screen, label, (SCREEN_W // 2 - 100, y), color, opt_f)
y += 40
_draw_text(screen, "Up/Down to choose, Enter to select", (SCREEN_W // 2 - 160, SCREEN_H - 50),
COLORS["text_dim"], opt_f)
def _draw_howto(screen: pygame.Surface, font: pygame.font.Font,
big: pygame.font.Font) -> None:
screen.fill(COLORS["bg"])
for i, line in enumerate(_HOWTO):
col = COLORS["stairs"] if line.startswith("UNDERDEPTHS") else COLORS["text"]
f = big if i == 0 else font
_draw_text(screen, line, (60, 40 + i * 28), col, f)
def _draw_endcard(screen: pygame.Surface, session: Any, kind: str,
big: pygame.font.Font, font: pygame.font.Font) -> None:
overlay = pygame.Surface((SCREEN_W, SCREEN_H), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 170))
screen.blit(overlay, (0, 0))
if kind == "dead":
title, col = "YOU DIED", COLORS["hp_empty"]
sub = f"You fell on floor {session.current_floor + 1} at level {session.player.level}."
else:
title, col = "VICTORY", COLORS["stairs"]
sub = "You slew the Ancient Dragon and conquered Underdepths."
_draw_text(screen, title, (SCREEN_W // 2 - 120, SCREEN_H // 2 - 60), col, big)
_draw_text(screen, sub, (SCREEN_W // 2 - 220, SCREEN_H // 2), COLORS["text"], font)
_draw_text(screen, "Press any key to return to the menu",
(SCREEN_W // 2 - 160, SCREEN_H // 2 + 50), COLORS["text_dim"], font)
# --------------------------------------------------------------------- main
def main(argv: list[str] | None = None) -> int:
headless = os.environ.get("SDL_VIDEODRIVER") == "dummy"
try:
max_frames = int(os.environ.get(MAXFRAMES_ENV, "0"))
except ValueError:
max_frames = 0
pygame.init()
audio = AudioEngine(enabled=True)
try:
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), 0 if headless else pygame.SCALED)
except Exception:
screen = pygame.Surface((SCREEN_W, SCREEN_H))
pygame.display.set_caption("Underdepths")
renderer = Renderer()
camera = Camera()
title_f, opt_f, big_f, font_f = _font(40, True), _font(20, True), _font(28, True), _font(18)
ui = "menu"
menu_idx = 0
session: Any = None
last_log_len = 0
clock = pygame.time.Clock() clock = pygame.time.Clock()
running = True running = True
while running: frame = 0
dt = clock.tick(FPS) / 1000.0
self.t += dt
self.move_cd = max(0.0, self.move_cd - dt)
while running:
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
running = False running = False
elif event.type == pygame.KEYDOWN: elif event.type == pygame.KEYDOWN:
if self._keydown(event.key): k = event.key
running = False if ui == "menu":
break if k in (pygame.K_DOWN, pygame.K_s):
menu_idx = (menu_idx + 1) % len(_MENU)
if self.view == "play" and self.overlay is None: audio.play("menu")
self._poll_move(dt) elif k in (pygame.K_UP, pygame.K_w):
menu_idx = (menu_idx - 1) % len(_MENU)
self.r.update(dt) audio.play("menu")
self._render() elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
pygame.display.flip() choice = _MENU[menu_idx]
def run_headless(self, max_frames: int) -> None:
"""Scripted self-check: new game, then render `max_frames` frames."""
self.session = game_state.new_game(seed=1234)
self._prev_log = len(self.session.log)
self._prev_hp = self.session.player.hp
self.view = "play"
self.overlay = None
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
for i in range(max(1, max_frames)):
dt = 1.0 / 30.0
self.t += dt
if self.session.state == "playing" and i > 0:
dx, dy = dirs[i % len(dirs)]
try:
actions.try_move(self.session, dx, dy)
except Exception:
pass
self.r.update(dt)
try:
self.r.render_world(self.screen, self.session, self.t)
except Exception:
pass
try:
pygame.display.flip()
except Exception:
pass
# ------------------------------------------------------------------ #
# Input
# ------------------------------------------------------------------ #
def _keydown(self, key) -> bool:
# Global: mute works everywhere.
if key == pygame.K_m:
self.audio.toggle_mute()
return False
if self.overlay == "help":
self.overlay = None
return False
if self.overlay in ("inv", "quaff", "read"):
if key == pygame.K_ESCAPE:
self.overlay = None
return False
self._overlay_select(self.overlay, key)
return False
if self.overlay == "equip":
if key == pygame.K_ESCAPE:
self.overlay = None
return False
if self.view == "menu":
return self._menu_key(key)
if self.view in ("dead", "victory"):
self.view = "menu"
self.session = None
self.overlay = None
return False
if self.view == "play":
return self._play_key(key)
return False
def _menu_key(self, key) -> bool:
opts = self._menu_options()
if key in (pygame.K_UP, pygame.K_k):
self.menu_index = (self.menu_index - 1) % len(opts)
elif key in (pygame.K_DOWN, pygame.K_j):
self.menu_index = (self.menu_index + 1) % len(opts)
elif key in (pygame.K_RETURN, pygame.K_KP_ENTER):
choice = opts[self.menu_index]
if choice == "New Game": if choice == "New Game":
self._start_new_game() session = new_game(seed=0)
camera.reset((session.player.x, session.player.y))
last_log_len = len(session.log)
ui = "howto"
elif choice == "Continue": elif choice == "Continue":
self._continue() loaded = act.load_saved()
if loaded is not None:
session = loaded
session.state = "playing"
camera.reset((session.player.x, session.player.y))
last_log_len = len(session.log)
ui = "playing"
elif choice == "How to Play": elif choice == "How to Play":
self.overlay = "help" ui = "howto"
elif choice == "Quit": elif choice == "Quit":
return True running = False
elif key == pygame.K_ESCAPE: elif k == pygame.K_ESCAPE:
return True running = False
return False elif ui == "howto":
if k == pygame.K_ESCAPE:
def _play_key(self, key) -> bool: ui = "playing" if session is not None else "menu"
s = self.session
if key == pygame.K_ESCAPE:
self.overlay = None
return False
if key == pygame.K_QUESTION:
self.overlay = "help"
return False
if key == pygame.K_i:
self.overlay = "inv"; return False
if key == pygame.K_e:
self.overlay = "equip"; return False
if key == pygame.K_q:
self.overlay = "quaff"; return False
if key == pygame.K_r:
self.overlay = "read"; return False
if key == pygame.K_g:
self._act(lambda: actions.pickup(s)); return False
if key == pygame.K_f:
self._act(lambda: actions.descend(s)); return False
if key == pygame.K_s:
game_state.save(s, SAVE)
self.session = None
self.view = "menu"
self.overlay = None
self.menu_index = 0
return False
# movement (immediate first step; held movement continues via _poll_move)
d = self._key_dir(key)
if d is not None:
self._move(*d)
self.move_cd = MOVE_DELAY
return False
def _key_dir(self, key):
m = {pygame.K_UP: (0, -1), pygame.K_DOWN: (0, 1),
pygame.K_LEFT: (-1, 0), pygame.K_RIGHT: (1, 0),
pygame.K_k: (0, -1), pygame.K_j: (0, 1),
pygame.K_h: (-1, 0), pygame.K_l: (1, 0)}
return m.get(key)
def _poll_move(self, dt) -> None:
if self.move_cd > 0:
return
keys = pygame.key.get_pressed()
d = None
if keys[pygame.K_UP] or keys[pygame.K_k]:
d = (0, -1)
elif keys[pygame.K_DOWN] or keys[pygame.K_j]:
d = (0, 1)
elif keys[pygame.K_LEFT] or keys[pygame.K_h]:
d = (-1, 0)
elif keys[pygame.K_RIGHT] or keys[pygame.K_l]:
d = (1, 0)
if d is not None:
self._move(*d)
self.move_cd = MOVE_DELAY
def _overlay_select(self, mode, key) -> None:
if not (pygame.K_a <= key <= pygame.K_z):
return
idx = key - pygame.K_a
s = self.session
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 s.player.inventory if wanted(it)]
if 0 <= idx < len(items):
self._act(lambda: actions.use_item(s, items[idx]))
self.overlay = None
# ------------------------------------------------------------------ #
# Action wrappers
# ------------------------------------------------------------------ #
def _move(self, dx, dy) -> None:
if self.session.state != "playing":
return
self._act(lambda: actions.try_move(self.session, dx, dy))
def _act(self, fn) -> None:
s = self.session
before = len(s.log)
fn()
# flush any buffered level-up lines
for m in s.player.pending_log:
s.log.append(m)
s.player.pending_log.clear()
self._emit_juice(s, len(s.log) - before)
self._prev_log = len(s.log)
self._prev_hp = s.player.hp
if s.state == "dead":
self.view = "dead"
self.audio.play("death")
elif s.state == "victory":
self.view = "victory"
self.audio.play("victory")
# ------------------------------------------------------------------ #
# Juice — derived from new log lines (the log is the feedback channel)
# ------------------------------------------------------------------ #
def _emit_juice(self, s, n_new) -> None:
if n_new <= 0:
return
p = s.player
pfx, pfy = _facing_delta(getattr(p, "facing", "down"))
front = (p.x + pfx, p.y + pfy)
px, py = self.r.world_px(p.x, p.y)
fx, fy = self.r.world_px(*front)
for line in s.log[-n_new:]:
low = line.lower()
dmg = _num(line)
crit = "critical" in low
if "you hit" in low and "defeated" not in low:
self.r.particles.burst(fx, fy, (240, 230, 180), n=8 if not crit else 16,
speed=90, life=0.4)
if dmg is not None:
self.r.floats.add(fx, fy - 6, f"-{dmg}", (255, 240, 200), big=crit)
if crit:
self.r.floats.add(fx, fy - 22, "CRIT!", (255, 210, 90), big=True)
self.r.particles.burst(fx, fy, (255, 210, 90), n=14, speed=120, life=0.5)
self.audio.play("hit")
elif ("hits you" in low or "critically strikes" in low or "shoots you" in low) and "defeated" not in low:
mag = 7.0 if crit else 4.0
self.r.shake.trigger(mag)
self.r.particles.burst(px, py, (210, 60, 60), n=12, speed=80, life=0.45)
if dmg is not None:
self.r.floats.add(px, py - 6, f"-{dmg}", (240, 90, 90), big=crit)
self.audio.play("damage")
elif "miss" in low:
tx, ty = (fx, fy) if "you miss" in low else (px, py)
self.r.floats.add(tx, ty - 4, "MISS", (170, 170, 170))
self.audio.play("miss")
elif "defeated" in low:
self.r.particles.burst(fx, fy, (200, 200, 210), n=18, speed=70, life=0.5)
self.audio.play("hit")
elif "reach level" in low:
self.r.particles.burst(px, py, (130, 225, 100), n=20, speed=90, life=0.7)
self.r.floats.add(px, py - 20, "LEVEL UP!", (130, 225, 100), big=True)
self.audio.play("levelup")
elif "pick up" in low:
self.r.particles.burst(px, py, (240, 220, 90), n=14, speed=60, life=0.5)
self.audio.play("pickup")
elif "descend" in low:
self.r.particles.burst(px, py, (240, 220, 80), n=16, speed=70, life=0.6)
self.audio.play("stairs")
elif any(k in low for k in ("teleport", "quaff", "surge", "fade", "scroll", "erupts", "floods", "equip")):
self.r.particles.burst(px, py, (120, 200, 255), n=12, speed=60, life=0.5)
self.audio.play("use")
elif "died" in low:
self.audio.play("death")
# ------------------------------------------------------------------ #
# Render dispatch
# ------------------------------------------------------------------ #
def _render(self) -> None:
if self.view == "menu":
self.r.render_menu(self.screen, self.menu_index, game_state.has_save(SAVE), self.t)
if self.overlay == "help":
self.r.render_help(self.screen, self.t)
return
if self.session is None:
self.r.render_menu(self.screen, self.menu_index, game_state.has_save(SAVE), self.t)
return
self.r.render_world(self.screen, self.session, self.t)
if self.overlay == "help":
self.r.render_help(self.screen, self.t)
elif self.overlay in ("inv", "equip", "quaff", "read"):
self.r.render_inventory(self.screen, self.session, self.overlay, self.t)
if self.view == "dead":
self.r.render_end(self.screen, self.session, "dead", self.t)
elif self.view == "victory":
self.r.render_end(self.screen, self.session, "victory", self.t)
def main(max_frames: int | None = None) -> None:
headless = os.environ.get("SDL_VIDEODRIVER", "").lower() == "dummy"
pygame.init()
flags = 0 if headless else pygame.SCALED
try:
screen = pygame.display.set_mode((R.WIN_W, R.WIN_H), flags)
except Exception:
screen = pygame.Surface((R.WIN_W, R.WIN_H))
try:
pygame.display.set_caption("Underdepths")
except Exception:
pass
RS.warm()
audio = AudioManager()
game = Game(screen, audio, headless)
try:
if headless:
game.run_headless(max_frames if max_frames is not None else 60)
else: else:
game.run() ui = "playing" if session is not None else "menu"
finally: elif ui == "playing" and session is not None:
try: if k == pygame.K_m:
audio.toggle_mute()
elif k == pygame.K_SLASH:
ui = "howto"
elif k == pygame.K_ESCAPE:
ui = "menu"
session = None
elif k == pygame.K_s:
before = len(session.log)
act.apply_input(session, "S")
_play_for_log(audio, session.log[before:])
elif k in _KEYMAP:
before = len(session.log)
act.apply_input(session, _KEYMAP[k])
_play_for_log(audio, session.log[before:])
elif ui in ("dead", "victory"):
ui = "menu"
session = None
# sync UI from session state
if session is not None and ui == "playing":
if session.state == "dead":
ui = "dead"
audio.play("death")
act.delete_save()
elif session.state == "victory":
ui = "victory"
audio.play("victory")
act.delete_save()
elif session.state == "saved":
ui = "menu"
session = None
# render
if ui == "menu":
_draw_menu(screen, menu_idx, act.load_saved() is not None, title_f, opt_f)
elif ui == "howto":
_draw_howto(screen, font_f, big_f)
else:
if session is not None:
camera.update((session.player.x, session.player.y))
offset = camera.offset_for((SCREEN_W, SCREEN_H), (session.player.x, session.player.y))
renderer.render(screen, session, camera_xy=offset)
if ui == "dead":
_draw_endcard(screen, session, "dead", big_f, font_f)
elif ui == "victory":
_draw_endcard(screen, session, "victory", big_f, font_f)
else:
ui = "menu"
_draw_menu(screen, menu_idx, False, title_f, opt_f)
pygame.display.flip()
if max_frames and frame >= max_frames:
running = False
frame += 1
clock.tick(60)
pygame.quit() pygame.quit()
except Exception: return 0
pass
if __name__ == "__main__": if __name__ == "__main__":
main() sys.exit(main(sys.argv[1:]))
+342 -429
View File
@@ -1,470 +1,383 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# ============================================================================= # Underdepths self-driving build pipeline.
# Underdepths — self-driving build pipeline.
# #
# Drives the entire game build via `pi -p` (the DEFAULT model only — never # Drives the whole game build with `pi -p` (DEFAULT model only — never
# passes --model/--provider), one dispatch per build phase, each gated by # --model/--provider). Resumable via .build_state (single int = last completed
# `python3 tests/smoke.py --phase N`. Resumable across crashes via .build_state. # phase). Re-run after a crash picks up where it left off.
# A goal backstop after phase 4 verifies EVERY acceptance criterion and loops
# fixes until all pass.
# #
# Phases run SEQUENTIALLY (a hung worker would block bash `&`+`wait` forever; # Hardening (learned the hard way on this exact challenge):
# learned the hard way on this very project). Every dispatch is wrapped in # * SEQUENTIAL dispatches only — parallel `pi -p` agents corrupt shared files.
# `timeout --kill-after=30` because the pi (node) process ignores SIGTERM. # * Watchdog SIGKILL of the whole process group: `pi` is node, ignores
# # SIGTERM, so plain `timeout` lets hung workers linger. setsid -w puts the
# State machine (.build_state = index of last completed phase): # worker in its own session; we kill -$pgid to reap the whole tree.
# 0 -> nothing 1 -> P1 2 -> P2 3 -> P3 4 -> P4(4a+4b+gate) 5 -> goal # * Gate-pass advances even if the dispatch itself was killed/timed out.
# ============================================================================= # * Ralph loop feeds the ACTUAL gate error back into the next dispatch.
set -uo pipefail set -uo pipefail
cd "$(dirname "$0")"
STATE=.build_state DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PIDF=.pipeline.pid cd "$DIR"
LOG_DIR=logs
STATE_FILE="$DIR/.build_state"
LOG_DIR="$DIR/.logs"
LOG="$LOG_DIR/build.log"
DISPATCH_LOG="$LOG_DIR/dispatch.log"
PIDFILE="$LOG_DIR/dispatch.pid"
mkdir -p "$LOG_DIR" mkdir -p "$LOG_DIR"
MAX_RETRIES=${MAX_RETRIES:-3} TTL="${UNDERDEPTHS_TTL:-3000}" # per-dispatch ceiling, seconds (50 min)
TTL=${TTL:-3000} # ~50 min ceiling per dispatch MAX_RETRIES=3
PY=${PY:-python3}
GATE="$PY tests/smoke.py"
COMPILE_GATE="$PY -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK"
# --- concurrency guard: never two pipelines in one directory --------------- PY="${PYTHON:-python3}"
if [[ -f "$PIDF" ]]; then
old="$(cat "$PIDF" 2>/dev/null || true)"
if [[ -n "$old" && "$old" != "$$" ]] && kill -0 "$old" 2>/dev/null; then
echo "FATAL: orchestrate.sh (PID $old) already running in this dir." >&2
echo " The pipeline edits shared files concurrently; re-run a single" >&2
echo " instance after it finishes (it is resumable via .build_state)." >&2
exit 1
fi
fi
echo "$$" > "$PIDF"
trap 'rm -f "$PIDF"' EXIT
get_state() { [[ -f "$STATE" ]] && cat "$STATE" 2>/dev/null || echo 0; } log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" | tee -a "$LOG"; }
set_state() { echo "$1" > "$STATE"; }
halt() { echo "!!! PIPELINE HALTED at the phase above — see logs/ !!!" >&2; exit 1; }
# dispatch NAME PROMPT GATE_CMD # ---------------------------------------------------------------------------
# Ralph loop: up to MAX_RETRIES, feeding the actual gate error back on retry. # run_dispatch <prompt> : run `pi -p "<prompt>"` under a watchdog. Always
dispatch() { # returns (never hangs). Output appended to $DISPATCH_LOG.
local name="$1" prompt="$2" gate="$3" # ---------------------------------------------------------------------------
local attempt=0 gate_out gate_rc full_prompt run_dispatch() {
while (( attempt < MAX_RETRIES )); do local prompt="$1"
attempt=$((attempt + 1)) : > "$DISPATCH_LOG"
echo "===================================================================" : > "$PIDFILE"
echo ">>> $name (attempt $attempt/$MAX_RETRIES) $(date +%H:%M:%S)" log " dispatch: pi -p (<${#prompt} chars>) TTL=${TTL}s"
echo "==================================================================="
if (( attempt == 1 )); then # setsid -w: child becomes session leader (pid==pgid); parent waits => $! is a
full_prompt="$prompt" # synchronous handle. Inner bash records its pid+pgid for the watchdog.
else setsid -w bash -c '
full_prompt="$(printf '%s\n\n--- PREVIOUS ATTEMPT FAILED THE GATE (fix THIS specifically) ---\n%s\n\nDo not rewrite parts that already work. Make the gate pass.\n\n--- ORIGINAL TASK ---\n%s' \ echo "$$ $(ps -o pgid= -p $$ | tr -d " ")" > "$1"
"$prompt" "$(printf '%s' "${gate_out}" | tail -n 70)" "$prompt")" exec pi -p "$2"
fi ' bash "$PIDFILE" "$prompt" >>"$DISPATCH_LOG" 2>&1 &
local logf="$LOG_DIR/${name}.attempt${attempt}.log"
# Run pi in its OWN session/process-group via setsid; a watchdog hard-SIGKILLs
# the entire group at TTL. GNU `timeout --kill-after` proved unreliable on this
# host (a hung pi worker lingered ~20 min past its deadline); the explicit
# whole-group kill is the dependable hammer. (setsid ships via util-linux.)
setsid bash -c 'pi -p -a --name "$0" @plan.md "$1" > "$2" 2>&1' \
"$name" "$full_prompt" "$logf" &
local job=$! local job=$!
( sleep "$TTL"; kill -KILL -"$job" 2>/dev/null; ) &
local wd=$! # Watchdog: after TTL, SIGKILL the whole session + the handle.
( sleep "$TTL"
if [ -f "$PIDFILE" ]; then
read -r wpid wpgid < "$PIDFILE"
kill -KILL -- "-${wpgid}" 2>/dev/null
kill -KILL "$wpid" 2>/dev/null
fi
kill -KILL "$job" 2>/dev/null
) &
local wdog=$!
wait "$job" 2>/dev/null wait "$job" 2>/dev/null
local rc=$? local rc=$?
kill "$wd" 2>/dev/null; wait "$wd" 2>/dev/null kill "$wdog" 2>/dev/null
if (( rc != 0 )); then wait "$wdog" 2>/dev/null
echo " ! dispatch ended (rc=$rc; timeout or error); tail of log:" >&2 log " dispatch returned rc=$rc"
tail -n 8 "$logf" >&2 return "$rc"
fi }
echo " gate: $gate"
gate_out="$(eval "$gate" 2>&1)" # ---------------------------------------------------------------------------
gate_rc=$? # run_gate <args...> : run the smoke gate. Sets GATE_OUT to combined output.
printf '%s\n' "${gate_out}" | tail -n 35 # Returns 0 on PASS, 1 on FAIL.
if (( gate_rc == 0 )); then # ---------------------------------------------------------------------------
echo "<<< $name PASS" GATE_OUT=""
run_gate() {
local out
out="$($PY tests/smoke.py "$@" 2>&1)"
local rc=$?
GATE_OUT="$out"
if [ "$rc" -eq 0 ]; then
log " GATE $*: PASS"
return 0 return 0
fi fi
echo " ! gate failed (attempt $attempt, rc=$gate_rc)" log " GATE $*: FAIL"
done
echo "<<< $name FAILED after $MAX_RETRIES attempts — full log: $LOG_DIR/${name}.attempt${MAX_RETRIES}.log" >&2
return 1 return 1
} }
# ============================================================================= # ---------------------------------------------------------------------------
# Shared preamble prepended to every worker prompt. # dispatch_fix <kind> <gate_error> : targeted fix dispatch with the real error.
# ============================================================================= # ---------------------------------------------------------------------------
read -r -d '' SHARED <<'SHARED_EOF' || true dispatch_fix() {
You are building "Underdepths", a turn-based roguelike in Python 3 + pygame-ce. local kind="$1" err="$2"
@plan.md is the COMPLETE design spec — READ IT before writing anything. local prompt
AGENTS.md (auto-loaded) holds the project conventions; follow them. prompt="$(cat <<EOF
You are fixing Underdepths phase gate failures. The repository already has code
in place; do NOT rewrite working systems — make the MINIMAL change that fixes
the failures below without breaking any OTHER passing phase gate.
CONTRACT (authoritative): tests/smoke.py is your verification gate AND its Read tests/smoke.py: its module docstring is the API CONTRACT every module must
module docstring defines the EXACT public API you must implement — dataclass match, and the phaseN() functions are the acceptance tests. Read AGENTS.md and
fields, function names + signatures, return shapes. Implement to that API. plan.md for full design context.
Run `python3 tests/smoke.py --phase N` repeatedly until it prints
`phase N: PASS`. You MAY correct smoke.py ONLY if an expectation directly
contradicts plan.md; NEVER weaken a behavioural assertion to pass trivially.
HEADLESS RULE (getting this wrong fails the whole build): smoke.py sets FAILED GATE: python tests/smoke.py $kind
SDL_VIDEODRIVER=dummy. In main.py NEVER force headless with Full gate output (stdout+stderr):
os.environ.setdefault("SDL_VIDEODRIVER","dummy") or setdefault on the audio
driver — that makes `python3 main.py` silently run headless and exit on every
real machine. Instead detect headless from the ENVIRONMENT the test sets:
headless = os.environ.get("SDL_VIDEODRIVER","").lower() == "dummy"
When headless is True, run a scripted self-check loop:
main(max_frames=K) runs at most K frames then returns. When headless is False,
open a REAL window with REAL audio and play normally. `python3 main.py` with no
environment variables MUST launch the playable game window.
IMPLEMENTATION RULES: $err
- @dataclass(slots=True) for all entities and state objects. Type hints on every
function signature. Constants in data/constants.py. No magic numbers in logic.
- NO stubs, NO TODO comments, NO placeholders. Every function has a real,
working implementation. If a file lists a function, it must work.
- All art is procedural pixel-art drawn with pygame.draw from in-code palettes —
NO external image / sprite-sheet / font / audio asset files. pygame.font.SysFont
only. Plain flat colored rectangles for entities/tiles are NOT acceptable.
- Every combat event, item pickup, level-up, and status change must append a
human-readable message to session.log (the message log is primary feedback).
- Use the standard library (json, random, math, dataclasses, heapq, array).
Represent grids as list[list[int]] (tiles) and list[list[bool]] (explored /
visible) — no numpy dependency. GameSession is the single source of truth.
- Rendering reads GameSession and draws; it never mutates game state.
SHARED_EOF
# ============================================================================= After fixing, run: python tests/smoke.py $kind
# Phase 1 — Foundation Repeat until it prints PASS. Then stop. Do not touch unrelated files.
# ============================================================================= EOF
read -r -d '' P1 <<'P1_EOF' || true )"
BUILD PHASE 1 — Foundation. Make `python3 tests/smoke.py --phase 1` print PASS. run_dispatch "$prompt"
}
Create these files (add __init__.py to data/, entities/, engine/, ai/, render/): # ---------------------------------------------------------------------------
# Phase build dispatches (attempt 1 of each phase runs these).
# Each points the agent at the contract in tests/smoke.py so there is ONE source
# of truth — no duplicated signatures that can drift.
# ---------------------------------------------------------------------------
P_COMMON="Read AGENTS.md, plan.md, and tests/smoke.py completely. The module
docstring of tests/smoke.py is the API CONTRACT — every signature, dataclass
field, and return shape there MUST be implemented exactly. The phaseN() function
matching your task is your acceptance test; run it and fix until PASS. Use only
Python 3.11 stdlib + pygame-ce. All art is procedural pixel-art via pygame.draw
(no external asset files). @dataclass(slots=True) for entities, type hints on
every function, constants in data/constants.py. Do NOT break any other phase's
passing gate."
data/constants.py phase1_build() {
TILE=20, MAP_WIDTH=80, MAP_HEIGHT=50, SIGHT_RADIUS=8, FLOORS=10 run_dispatch "$(cat <<EOF
COLORS / PALETTE dicts (wall dark gray ~ (60,60,70) visible / (30,30,35) $P_COMMON
explored; floor (40,35,30)/(20,18,15); per-enemy accent hues; item accents
yellow/blue/red/cyan; stairs yellow). The full XP/level-up table from plan
(levels 1->2 ... 9->10: cumulative XP 30,70,140,250,400,600,850,1150,1500;
HP/power gains per plan). Per-floor enemy/item count distribution from plan.
entities/entity.py PHASE 1 — Foundation. Create these modules implementing the contract in
@dataclass(slots=True) Entity(x:int, y:int, name:str, sprite_key:str, tests/smoke.py:
blocks:bool=True). data/constants.py TILE=20, MAP_W=80, MAP_H=50, SIGHT_RADIUS=8,
FLOOR_COUNT=10, plus PALETTE/COLORS per plan.md
entities/entity.py Entity dataclass
entities/player.py Player (base stats from plan.md: hp50 power4 etc.)
entities/enemy.py Enemy dataclass (full field set per contract)
engine/map_gen.py Rect, GameMap (with .walkable/.in_bounds),
generate_dungeon(seed)->list[GameMap] (all 10 floors),
generate_floor(floor_index, rng)->GameMap
engine/game_state.py GameSession dataclass + new_session(seed)
main.py minimal but real: def main(argv=None)->int,
detects SDL_VIDEODRIVER=='dummy' for headless,
honors env UNDERDEPTHS_MAX_FRAMES, exposes new_game()
BSP dungeon generation per plan.md: recursively split, carve rooms (4x4..10x8),
L-corridors between siblings, 1-tile wall border, all 10 floors generated up
front. Floors 0-8: place stairs_down on a FLOOR tile REACHABLE from spawn
(verify with a flood fill — re-carve corridors until reachable). Floor 9 is the
boss arena: single large room (20x15), NO stairs_down (None). spawn in the first
room.
entities/player.py Verify before finishing: python tests/smoke.py --phase 1 (must print PASS)
@dataclass(slots=True) Player(Entity) with the base stats from plan Also eyeball the ASCII render it prints — '>' must appear on a reachable floor tile.
(hp=50,max_hp=50,power=4,armor=0,accuracy=5,evasion=2,crit_chance=0.10, EOF
speed=1, level=1, xp=0, inventory:list, equipped:dict, effects:list, )"
facing="down", name="You", sprite_key="player", blocks=True). }
Methods: total_power()->int (base + equipped weapon power + strength effect),
total_armor()->int (base + equipped armor), gain_xp(amount)->bool that applies
the level-up table (level up may chain multiple levels), fully heals and
increases max_hp/power per the table, logs "You reach level N!", returns True
if any level-up occurred. Implement the FULL level table now.
entities/enemy.py phase2_build() {
@dataclass(slots=True) Enemy(Entity) with hp,max_hp,power,armor,accuracy, # Four independent systems, built SEQUENTIALLY (never parallel — shared files).
evasion,crit_chance,speed,behavior,xp_value, plus last_known_pos (tuple|None), run_dispatch "$(cat <<EOF
act_counter:int=0, can_split:bool=True, ranged_power:int=0. $P_COMMON
ENEMY_KINDS list of all seven. make_enemy(kind,x,y)->Enemy returning the FULL
stat roster from plan's Enemy Roster table (rat/goblin/skeleton_archer/
orc_warrior/wraith/green_slime/ancient_dragon). Dragon ranged_power>=15.
engine/map_gen.py PHASE 2a — Field of View. Create engine/fov.py: recursive shadowcasting over 8
@dataclass(slots=True) Rect(x,y,w,h) with a .center property returning (x+w//2, octants, radius SIGHT_RADIUS=8. Function compute_fov(game_map, origin, radius=8)
y+h//2). @dataclass(slots=True) GameMap(width,height,tiles,rooms,explored, -> set[tuple[int,int]] of visible tiles. Walls block sight but are themselves
visible,entities,stairs_down,floor_index) exactly per the contract docstring. visible when adjacent to a visible floor tile. Do NOT modify map_gen.py.
generate_dungeon(floor_index,width=80,height=50)->GameMap using BSP: all walls, Verify: python tests/smoke.py --phase 2 (it tests fov now; other phase-2 parts
5-8 recursive splits alternating axis, carve a room (4x4..10x8, shrunk 1-2 from may still fail — that's fine, just don't break phase 1). Finish fov only.
region edge) per leaf, connect siblings with L-shaped corridors, place stairs_down EOF
in the room farthest from spawn. Floor 9 is the BOSS ARENA: a single large room )"
(~20x15) — exactly ONE room with w>=15 and h>=10. Floors 0-8 have >=3 rooms, run_dispatch "$(cat <<EOF
a solid 1-tile wall border on all four edges, no overlapping rooms, and every $P_COMMON
room reachable from every other via floor-tile flood fill. is_walkable(map,x,y)
->bool (in bounds and tile==1). populate(map,floor_index,rng=None) places
ENEMIES per plan's per-floor distribution (floor 9: just the dragon + leave room
for 2 potions; items are added in phase 3 so do not place items yet). Ensure
populate never raises on any floor 0-9.
main.py PHASE 2b — A* pathfinding. Create engine/pathfinding.py: grid A* with Manhattan
A MINIMAL entry for now: define main(max_frames=None) that, when heuristic. find_path(game_map, start, goal, blocked=frozenset()) ->
SDL_VIDEODRIVER==dummy, runs a tiny headless self-check (generate a dungeon, list[tuple]|None. Path EXCLUDES start, INCLUDES goal, [] when start==goal, None
print nothing fatal) and returns; otherwise prints "Underdepths — phase 1 when unreachable. Treat walls + the `blocked` set as impassable. Do NOT modify
scaffold". It will be FULLY rebuilt in phase 4. Obey the HEADLESS RULE. map_gen.py or fov.py. Verify: python tests/smoke.py --phase 2 (pathfinding
P1_EOF assertions should pass).
P1="$(printf '%s\n\n%s' "$SHARED" "$P1")" EOF
)"
run_dispatch "$(cat <<EOF
$P_COMMON
# ============================================================================= PHASE 2c — Combat. Create engine/combat.py: @dataclass AttackRoll(hit,crit,
# Phase 2 — Core systems (FOV, A*, combat, minimal game state, chase AI) damage) and roll_attack(attacker, defender, rng=random)->AttackRoll. Read
# ============================================================================= .accuracy .evasion .power .armor .crit_chance (+optional .weapon_power) off the
read -r -d '' P2 <<'P2_EOF' || true arguments (duck-typed). Formulas from plan.md:
BUILD PHASE 2 — Core systems. Make `python3 tests/smoke.py --phase 2` print PASS. hit_chance = clamp(0.7 + (atk.accuracy - def.evasion)*0.05, 0.1, 0.95)
Do NOT regress phase 1 (re-run --phase 1 if unsure). base = atk.power + weapon_power ; reduced = max(0, base - def.armor)
crit = rng.random() < atk.crit_chance ; damage = reduced*(2 if crit else 1)
Miss => hit=False, damage=0. Do NOT modify map_gen/fov/pathfinding.
Verify: python tests/smoke.py --phase 2 (combat assertions should pass).
EOF
)"
run_dispatch "$(cat <<EOF
$P_COMMON
engine/fov.py PHASE 2d — Enemy AI. Create ai/behaviors.py: act_enemy(enemy, game_map, player,
compute_fov(game_map, ox, oy, radius=8) -> set of (x,y) visible tiles, using visible:set, rng)->None. Dispatch on enemy.behavior: wander / chase (A* toward
RECURSIVE SHADOWCASTING over 8 octants (write it from scratch, no library). player when in `visible`, else last_known_pos; adjacent=>melee via combat) /
Walls block sight but a wall adjacent to a visible floor tile is itself flee (hp<30% => move away) / ranged (shoot/kite per plan) / phase (move toward
visible. Mutate game_map.visible accordingly and RETURN the visible set. player ignoring walls, acts every 2 turns) / split (on death spawn 2 smaller).
Read/write enemy.x/.y/.last_known_pos. Do NOT modify the engine/* systems.
Verify: python tests/smoke.py --phase 2 (ALL of phase 2 must now PASS).
EOF
)"
}
engine/pathfinding.py phase3_build() {
astar(game_map, start, goal, blocked=frozenset()) -> list[(x,y)] | None, grid run_dispatch "$(cat <<EOF
A* with Manhattan heuristic. Walkable = in-bounds floor tile not in `blocked` $P_COMMON
and not a wall. Return the path excluding the start node's duplicate; None if
unreachable or if start/goal is a wall/out of bounds.
engine/combat.py PHASE 3 — Content. Create/flesh out:
attack(attacker, defender, rng=None, log=None) -> dict with keys data/enemies.py ENEMY_DEFS dict + make_enemy(kind,x,y)->Enemy. Kinds:
hit:bool, damage:int, crit:bool, killed:bool. Use plan's formulas: rat,goblin,skeleton_archer,orc_warrior,wraith,green_slime,
hit_chance = clamp(0.7 + (attacker.accuracy - defender.evasion)*0.05, 0.1, 0.95); ancient_dragon,small_slime. Stats EXACTLY per plan.md Enemy
on hit, base = attacker.power(+weapon bonus via total_power for the player), Roster (hp/power/armor/speed/behavior/xp). green_slime
reduced = max(0, base - defender.armor), crit doubles damage, apply to can_split=True. ancient_dragon armor 8 hp 120 power 15.
defender.hp, killed = defender.hp <= 0. If log is a list, append the plan's data/items.py ITEM_DEFS dict + make_item(kind,x,y)->Item. Catalog per
human messages ("You hit the Goblin for 8 damage!", "Critical hit! ...", plan.md: rusty_dagger..war_hammer, leather/chain/plate
"Goblin misses you"). The attacker may be Player (use total_power/total_armor) armor, healing/strength/invisibility potions, fireball/
or Enemy (use raw stats). rng defaults to random.Random(). teleport/mapping scrolls. war_hammer power MUST be +10.
entities/item.py Item dataclass: x,y,kind,name,category,stats(dict).
entities/player.py Player: add inventory(list), equipped_weapon/equipped_armor,
effect_timers(dict), total_power(), total_armor(), equip(item)
(swap old back to inventory), gain_xp(amount)->int using the
plan.md XP table (cumulative 30/70/140/250/400/600/850/1150/
1500), level cap 10, FULL HEAL + stat gain on level-up.
entities/enemy.py ensure Enemy has all contract fields (last_known_pos,
can_split, speed, etc.).
Do NOT break phases 1-2. Verify: python tests/smoke.py --phase 3 (must PASS).
EOF
)"
}
engine/game_state.py phase4_build() {
@dataclass(slots=True) GameSession holding player, dungeon (list of 10 # Large phase — split into sequential sub-builds BEFORE the single phase gate.
GameMap), current_floor:int, log:list[str], turn:int, state:str run_dispatch "$(cat <<EOF
("playing"/"dead"/"victory"/"menu"), plus an rng. new_game(seed=None)-> $P_COMMON
GameSession: build the player, generate all 10 floors (generate_dungeon),
populate enemies, place the player in the first room center of floor 0,
init log/turn, set state="playing". recompute_fov(session): clear visible,
compute_fov from the player, merge into explored. (Items/inventory wiring is
phase 3; keep new_game minimal but functional.)
ai/behaviors.py PHASE 4a — State + persistence. engine/game_state.py: full GameSession
take_enemy_turn(enemy, session, rng=None) dispatching on enemy.behavior. (player,dungeon,current_floor,log,turn,state) + new_session(seed)->GameSession
Implement at least: wander (random walkable step or wait), chase (A* toward that generates all 10 floors, places the player at floor-0 spawn, state='menu'/
player when player visible via FOV, else toward last_known_pos; adjacent -> 'playing'. engine/serializers.py: session_to_dict(session)->dict and
melee via combat.attack into session.log), and a stub for the others (you will session_from_dict(d)->GameSession (JSON-safe). Persist player (stats, level, xp,
finish flee/ranged/phase/split in phase 3). Respect speed (speed==2 acts every inventory, equipped, effect_timers, position), all 10 floors (tiles, explored,
other turn via act_counter). Enemies must not stack (treat other entities as entities, stairs_down, spawn), current_floor, turn, log. Do NOT serialize the
blocked). Update last_known_pos when the player is visible. volatile `visible` grid (recomputed from FOV on load). Verify with a quick
P2_EOF python -c round-trip; do not break earlier phases.
P2="$(printf '%s\n\n%s' "$SHARED" "$P2")" EOF
)"
run_dispatch "$(cat <<EOF
$P_COMMON
# ============================================================================= PHASE 4b — Actions + audio + main loop. engine/actions.py: apply_input(session,
# Phase 3 — Content: items, inventory, equipment, scrolls, full AI, XP wiring key:str)->None translating logical keys into intents and mutating session:
# ============================================================================= 'up/down/left/right' (move 1 tile; moving into an enemy = melee via combat;
read -r -d '' P3 <<'P3_EOF' || true after the player acts, advance enemies via ai.behaviors + log messages), 'g'
BUILD PHASE 3 — Content layer. Make `python3 tests/smoke.py --phase 3` pass. (pick up item under player into inventory), 'f' (descend ONLY if player stands
Do NOT regress phases 1-2. on stairs_down; current_floor+=1; recompute FOV), 'i','e','q','r' (inventory/
equipment/potion/scroll menus or direct use), 'S' (save via serializers to
save.json then state='saved'), '?' (How to Play), 'm' (mute toggle),
'escape'/'wait'. Dragon death on floor 9 => session.state='victory'. Player
hp<=0 => state='dead'. engine/audio.py: AudioEngine(enabled=True) wrapping
pygame.mixer — generate short in-memory tones (stdlib array); .play(name),
.toggle_mute(), .muted bool, .available bool; NEVER raise (silent fallback if
mixer init fails). main.py: full game loop, main menu (New Game / Continue if
save.json exists / How to Play / Quit), How to Play screen (every control +
the pickup/descent steps), death + victory screens, 'g'/'f' are driven by
actions.apply_input. MUST detect headless via SDL_VIDEODRIVER=='dummy' (never
force it in code) and honor env UNDERDEPTHS_MAX_FRAMES to exit after N frames.
Expose new_game(seed)->GameSession. Do NOT break earlier phases.
EOF
)"
run_dispatch "$(cat <<EOF
$P_COMMON
entities/item.py PHASE 4c — Rendering (procedural pixel-art). data/sprites.py: 2D palette-key
@dataclass(slots=True) Item(Entity) with item_type ("weapon"/"armor"/ grids per entity/tile/item (12x12..16x16). render/sprites.py: get_sprite(name)
"potion"/"scroll"), subtype (e.g. "healing","strength","invisibility", -> cached pygame.Surface, rasterized once via pygame.draw from the grids —
"fireball","teleport","mapping"), stats:dict, name, sprite_key. MUST include a 'stairs' sprite that is DISTINCT, non-empty, and glowing YELLOW
make_item(name,x,y)->Item implementing the FULL catalog from plan: Rusty (R>120,G>100,B<110), plus distinct sprites for player + all 7 enemies + items.
Dagger(+2), Short Sword(+4), Battle Axe(+7), War Hammer(+10 power, crit -5%), render/renderer.py: Renderer.render(surface, session, camera_xy=(0,0)) draws
Leather Armor(armor 2), Chain Mail(armor 4), Plate Armor(armor 7, evasion -10%), map tiles + entities + items, and MUST blit the 'stairs' sprite on EVERY
Healing Potion(heal 30), Strength Potion(+5 power/20 turns), Invisibility stairs_down tile (invisible stairs make the game unwinnable — a build failure).
Potion(invisible/15 turns), Scroll of Fireball(20 dmg radius 3), Scroll of render/effects.py: radial torch-light from player (SIGHT_RADIUS falloff),
Teleport, Scroll of Mapping. Player.total_power/total_armor must read the explored-but-not-visible tiles dimmed, wall occlusion, screen vignette, particle
equipped weapon/armor stats. bursts (hit/crit/death/pickup/level-up/stairs), screen-shake on damage.
render/camera.py: smooth easing follow. NO external image files. Do NOT break
earlier phases. Verify: python tests/smoke.py --phase 4 (must PASS — includes
the stairs-rendered assertion and the dragon-kill -> victory assertion).
EOF
)"
}
engine/actions.py (full gameplay actions; pure functions on GameSession) # ---------------------------------------------------------------------------
try_move(session, dx, dy)->bool: if target tile has an enemy -> melee # run_phase <n> : attempt-1 build dispatches, then gate->fix Ralph loop.
(combat.attack player->enemy, log, award XP + handle death/split, check win); # Returns 0 on gate PASS, 1 after MAX_RETRIES exhausted.
else move player if walkable & unblocked; then advance enemy turns + recompute # ---------------------------------------------------------------------------
FOV + tick effect timers. Return whether the player acted. run_phase() {
pickup(session)->bool: if an Item is under the player, move it to inventory local n=$1
(or auto-consume potions? NO — into inventory), log "You pick up X", return True. log "===== PHASE $n: build (attempt 1) ====="
descend(session)->bool: if player on stairs_down, current_floor+=1, place case "$n" in
player at that floor's spawn/first room center, recompute FOV, log descent. 1) phase1_build ;;
Return False if not on stairs or already on floor 9 (no stairs there pre-win). 2) phase2_build ;;
use_item(session, item): potions -> apply effect (heal capped at max_hp; 3) phase3_build ;;
strength/invisibility push a timed Effect into player.effects), scrolls -> 4) phase4_build ;;
fireball (20 dmg to all enemies within 3 of player), teleport (random walkable *) log "unknown phase $n"; return 1 ;;
tile), mapping (set entire current floor explored True); consume (remove from esac
inventory). Equippables -> equip(session,item).
equip(session,item): place in the right slot, move old item back to inventory,
apply stat mods via total_power/total_armor (War Hammer crit -5%, Plate evasion
-10%). Log "You equip X".
ai/behaviors.py (COMPLETE the behavior set) local attempt
Finish flee (HP<30% -> move away, else chase), ranged/kiting (skeleton archer: for attempt in $(seq 1 "$MAX_RETRIES"); do
fire ranged_attack at range>3 using ranged_power with a distance penalty; if run_gate --phase "$n"; then
step away when adjacent <=2; wander when no sight), phase (wraith: move toward return 0
player IGNORING walls, acts every 2 turns via act_counter), and the dragon's
boss behavior (chase + every 3rd turn breath weapon: 15 damage to all tiles in
a line toward the player). on_death(enemy, session): if green_slime and
can_split, spawn TWO smaller slimes (half hp, half power, can_split=False,
name "Small Slime") into the floor entities and log it; always award XP via
player.gain_xp and remove the corpse. Slime small variants must not split.
engine/game_state.py (extend)
new_game must now also place ITEMS per plan's distribution (extend populate or
spawn items alongside enemies; floor 9 gets exactly 2 healing potions near the
entrance + the dragon). Add a player.invisible flag (True while an invisibility
effect is active — enemies then cannot see the player). Effect timers tick down
each turn (try_move end) and expire. Death -> state="dead"; killing the dragon
on floor 9 -> state="victory".
data/items.py and data/enemies.py (optional)
You may keep catalogs inline in the entity modules OR factor them here; either
is fine. Do not duplicate the make_enemy/make_item contract.
P3_EOF
P3="$(printf '%s\n\n%s' "$SHARED" "$P3")"
# =============================================================================
# Phase 4a — Persistence + audio + state transitions
# =============================================================================
read -r -d '' P4A <<'P4A_EOF' || true
BUILD PHASE 4a — Persistence + resilient audio. Do NOT regress phases 1-3.
This is the first half of phase 4; the render/UI/main half follows in 4b.
engine/serializers.py
session_to_dict(session)->dict and dict_to_session(d)->GameSession giving an
EXACT round trip. Serialize: player (all stats, level, xp, inventory, equipped,
position, effects with remaining turns, facing), all 10 floors (tiles, rooms,
explored, entities, stairs_down, floor_index), current_floor, turn, log, state.
Do NOT serialize the `visible` grids — they are recomputed via recompute_fov on
load. dict_to_session must reconstruct Player/Enemy/Item objects (store a type
discriminator per entity) and call recompute_fov. Tiles as list[list[int]],
explored as list[list[bool]] serialize directly with json.
engine/audio.py
AudioManager class. Generate short tones in memory with stdlib array.array +
pygame.mixer.Sound(buffer=...) (NO audio asset files). Provide play(name) for
events: hit, miss, damage, pickup, use, stairs, levelup, death, victory.
toggle_mute()->mutes/unmutes; .muted bool. CRITICAL: every public method must
be wrapped so that ANY mixer init / Sound creation failure disables audio
silently and never raises — the game stays fully playable with no audio device.
Initialize the mixer once, lazily and defensively.
engine/game_state.py (extend)
save(session, path="save.json") writes session_to_dict via json to the game
directory; load(path) reads it. On player death: state="dead" AND delete
save.json (permadeath). On victory: state="victory" and delete save.json.
Keep new_game/recompute_fov working. Add a helper has_save(path) used by the
menu (phase 4b).
You only write logic here; rendering and the full main loop come in phase 4b.
Run `python3 tests/smoke.py --phase 1`, `--phase 2`, `--phase 3` to confirm no
regression; phase 4 gate runs after 4b.
P4A_EOF
P4A="$(printf '%s\n\n%s' "$SHARED" "$P4A")"
# =============================================================================
# Phase 4b — Procedural pixel-art, rendering, juice, full main loop + UI
# =============================================================================
read -r -d '' P4B <<'P4B_EOF' || true
BUILD PHASE 4b — Visuals, UI, and the full game loop. Make
`python3 tests/smoke.py --phase 4` print PASS. Do NOT regress phases 1-3.
Phase 4a already added serializers.py, audio.py, and save/load.
data/sprites.py
2D grids of single-char palette keys (e.g. "." transparent, "K" outline,
shades) for EVERY entity, tile, item, and stairs — roughly 12x12..16x16 cells.
Each of the 7 enemies + the player + each item category + stairs must be
DISTINCT and recognizable (not recolors): hooded adventurer whose equipped
weapon/armor change the sprite; rat (tail/ears/whiskers); goblin (ears/
loincloth); skeleton archer (bow/quiver/glowing eyes); orc warrior (tusks/
big blade); wraith (tattered cloak, no legs); green slime (glossy, googly
eyes, drip); ancient dragon (horns/wings/scales/fangs). 2-3 idle frames each.
render/sprites.py
Rasterize a palette-key grid to a pygame.Surface ONCE and cache by
(name,frame,SCALE). The renderer blits the cached surface scaled to TILE.
render/effects.py
Radial torch-light centered on the player out to SIGHT_RADIUS (brightness
falloff), explored-not-visible tiles remembered but tinted dark blue-gray and
dimmer, walls occlude light (derived from the FOV/visible grid), soft screen
vignette. Particle bursts (hit sparks, crit star burst, blood/slime/ash poof
on death, level-up stars, pickup sparkle, stairs shimmer) — pool and cap
counts. Screen-shake on player damage (decaying offset). Floating combat text
(-8, MISS!, CRIT!). Soft ellipse shadows under entities.
render/camera.py
Viewport offset that eases toward the player each frame. Show ~48x28 tiles.
render/renderer.py (PURE: reads GameSession, never mutates)
Compose: map tiles (beveled walls w/ lighter top edge + darker bottom + seeded
per-tile variation; dithered floor with flecks), entities + items + stairs,
lighting overlay, particles, shadows, screen-shake, camera offset. UI: bordered
panels (1px pixel frame, inner bevel); top bar (Floor N/10, HP bar with heart
icon, Level, XP bar); right panel (last ~8 log messages, color-coded: combat
white, damage red, level-up green, items yellow); bottom bar (equipment slots
as pixel-art icons, active effect timers, sound on/off icon); context prompt
line styled as UI — on an item show "Press G to pick up <name>", on stairs
show "Press F to descend". pygame.font.SysFont only.
main.py (FULL rebuild)
State machine: menu -> playing -> dead / victory / saved. Obey the HEADLESS
RULE precisely (detect SDL_VIDEODRIVER==dummy; main(max_frames=K) runs a
scripted headless self-check of K frames then returns; real launches open a
window with audio). Main menu: New Game (generate dungeon, then show How to
Play before the first turn), Continue (only if save.json exists), How to Play
(always; explains EVERY control), Quit. How to Play must be reachable from the
menu and shown before every New Game, and reopened with `?` during play.
Controls from plan: arrows/hjkl move-attack, g pickup, i inventory, e
equipment, q quaff, r read scroll, f descend (on stairs), S save+quit,
? help, m mute, Esc close menus. Show contextual "Press G to pick up" on an
item and "Press F to descend" on stairs. Death screen: "You died on floor N.
You reached level M." Victory: "You slew the Ancient Dragon! ...". Press any
key -> menu. Initialize audio at the app boundary; keep playable if it fails.
P4B_EOF
P4B="$(printf '%s\n\n%s' "$SHARED" "$P4B")"
# =============================================================================
# Phase 4 gate + goal backstop prompts
# =============================================================================
read -r -d '' P4FIX <<'P4FIX_EOF' || true
VERIFY AND FIX PHASE 4. Run `python3 tests/smoke.py --phase 4`. If it already
prints `phase 4: PASS`, change nothing. If it fails, read the failure, open the
relevant file(s) among engine/serializers.py, engine/audio.py, engine/actions.py,
engine/game_state.py, render/*, data/sprites.py, main.py, and fix the SPECIFIC
failure without regressing phases 1-3 (re-run --phase 1/2/3 to be sure). Do not
weaken smoke assertions.
P4FIX_EOF
read -r -d '' PGOAL <<'PGOAL_EOF' || true
GOAL BACKSTOP. The four phase gates should already pass. Now verify EVERY
acceptance criterion in @plan.md end to end:
1. Run `python3 tests/smoke.py --goal`. It must print "[goal] ALL ACCEPTANCE
CRITERIA PASS". If any criterion fails, read the failure and fix the SPECIFIC
gap in the code (you may touch any file) without weakening smoke assertions.
2. Confirm `python3 main.py` is structured to launch a real window with audio
when SDL_VIDEODRIVER is NOT dummy (do NOT actually open a window here — just
confirm the headless branch is env-gated, not forced).
3. Re-run `python3 tests/smoke.py --goal` until it passes.
The game must be complete and playable: 10 floors, 7 enemies, A*, FOV, BSP,
combat with crits, XP/leveling, items/inventory/equipment, save/load, win + lose
states, How to Play, contextual g/f prompts, resilient audio, and distinct
procedural pixel-art with lighting + particles.
PGOAL_EOF
PGOAL="$(printf '%s\n\n%s' "$SHARED" "$PGOAL")"
# =============================================================================
# Main driver
# =============================================================================
echo "Underdepths build pipeline — state=$(get_state) ttl=${TTL}s retries=${MAX_RETRIES}"
s="$(get_state)"
if (( s < 1 )); then dispatch phase1-foundation "$P1" "$GATE --phase 1" && set_state 1 || halt; fi
s="$(get_state)"
if (( s < 2 )); then dispatch phase2-core "$P2" "$GATE --phase 2" && set_state 2 || halt; fi
s="$(get_state)"
if (( s < 3 )); then dispatch phase3-content "$P3" "$GATE --phase 3" && set_state 3 || halt; fi
s="$(get_state)"
if (( s < 4 )); then
dispatch phase4a-persist "$P4A" "$COMPILE_GATE" || halt
dispatch phase4b-visuals "$P4B" "$COMPILE_GATE" || halt
dispatch phase4-gate "$P4FIX" "$GATE --phase 4" && set_state 4 || halt
fi fi
s="$(get_state)" if [ "$attempt" -lt "$MAX_RETRIES" ]; then
if (( s < 5 )); then dispatch goal-backstop "$PGOAL" "$GATE --goal" && set_state 5 || halt; fi log "===== PHASE $n: fix attempt $((attempt + 1)) ====="
dispatch_fix "--phase $n" "$GATE_OUT" || true
fi
done
log "PHASE $n FAILED after $MAX_RETRIES gate attempts"
log "last gate output:\n$GATE_OUT"
return 1
}
echo # ---------------------------------------------------------------------------
echo "===================================================================" # Goal backstop: after all 4 phases, verify EVERY acceptance criterion headlessly.
echo "BUILD COMPLETE — all phase gates + goal backstop PASS." # ---------------------------------------------------------------------------
echo "Play it: python3 main.py" goal_loop() {
echo "Verify: python3 tests/smoke.py --goal" log "===== GOAL BACKSTOP ====="
echo "===================================================================" if run_gate --goal; then
return 0
fi
local attempt
for attempt in $(seq 1 "$MAX_RETRIES"); do
log "===== GOAL fix attempt $attempt ====="
dispatch_fix "--goal" "$GATE_OUT" || true
if run_gate --goal; then
return 0
fi
done
log "GOAL FAILED after $MAX_RETRIES attempts"
log "last goal output:\n$GATE_OUT"
return 1
}
# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------
main() {
local state
state="$(cat "$STATE_FILE" 2>/dev/null || echo 0)"
log "Underdepths pipeline starting. Last completed phase: $state"
for n in 1 2 3 4; do
if [ "$n" -le "$state" ]; then
log "phase $n: already complete, skipping"
continue
fi
if ! run_phase "$n"; then
log "HALT: phase $n did not pass. See $DISPATCH_LOG and $LOG."
exit 1
fi
echo "$n" > "$STATE_FILE"
log "phase $n COMPLETE (.build_state -> $n)"
done
if ! goal_loop; then
log "HALT: goal backstop did not pass. See $DISPATCH_LOG and $LOG."
exit 1
fi
log "============================================================"
log "BUILD COMPLETE: all 4 phases + goal backstop PASS."
log "Play it: python main.py"
log "============================================================"
}
main "$@"
+12 -2
View File
@@ -75,7 +75,7 @@ class GameMap:
2. Recursively split the map into two regions (alternate horizontal/vertical), 5–8 splits total. 2. Recursively split the map into two regions (alternate horizontal/vertical), 5–8 splits total.
3. For each leaf region, carve a room (fill a random sub-rectangle as floor, shrink 1-2 tiles from region edges). 3. For each leaf region, carve a room (fill a random sub-rectangle as floor, shrink 1-2 tiles from region edges).
4. Connect sibling regions with L-shaped corridors. 4. Connect sibling regions with L-shaped corridors.
5. Place stairs down in the last room generated (rooms farthest from spawn). 5. Place stairs down in the last room generated (rooms farthest from spawn). Stairs MUST land on a floor tile that is reachable from the player's spawn room through the carved corridors (verified by flood fill). Floors 0–8 always have stairs; floor 9 (boss arena) has NO descent — it is won by slaying the dragon.
6. Spawn enemies and items per floor (see distribution below). 6. Spawn enemies and items per floor (see distribution below).
**Room size:** 4×4 to 10×8 tiles. **Room size:** 4×4 to 10×8 tiles.
@@ -96,6 +96,15 @@ Enemies on each floor are drawn from the roster, gated by depth (see Enemy Roste
Generate all 10 floors at game start. This makes save/load simpler (serialize all floors). Generate all 10 floors at game start. This makes save/load simpler (serialize all floors).
### Winnability (hard requirement)
Every floor MUST be completable by a real player — no dead ends:
- **Floors 0–8:** `stairs_down` exists, sits on a floor tile, and is REACHABLE from the spawn room (flood-fill). The renderer MUST draw a distinct, visible `>` staircase sprite on that tile (glowing yellow) so the player can find it and press `f` to descend. Stairs that exist only in data but are never rendered make the floor unwinnable — this is a build failure.
- **Floor 9 (boss arena):** the Ancient Dragon is present, reachable across the arena, and DEFEATABLE by a player who has leveled and geared up through floors 0–8. Because the dragon has armor 8, the player must be able to obtain (by floor 9) a weapon strong enough that `total_power > 8` (e.g. Battle Axe/War Hammer plus level bonuses) so each swing deals nonzero damage. Slaying it triggers victory; there is no descent from floor 9.
The phase gates must assert the floors-0–8 reachability/rendering above; the goal backstop must confirm the dragon is killable.
### 2. Field of View (fov.py) ### 2. Field of View (fov.py)
**Algorithm: Recursive Shadowcasting** (8 octants). **Algorithm: Recursive Shadowcasting** (8 octants).
@@ -333,7 +342,7 @@ feel.
- **Ancient Dragon:** large multi-hue red boss — horns, spread wings, scales, fangs. - **Ancient Dragon:** large multi-hue red boss — horns, spread wings, scales, fangs.
- **Items:** pixel-art icons (weapon, armor, potion flask, scroll) with the - **Items:** pixel-art icons (weapon, armor, potion flask, scroll) with the
category accent (yellow / blue / red / cyan) as the dominant hue. category accent (yellow / blue / red / cyan) as the dominant hue.
- **Stairs:** a pixel-art descending staircase / `>` arrow, glowing yellow. - **Stairs:** a pixel-art descending staircase / `>` arrow, glowing yellow. The renderer MUST blit this sprite on every `stairs_down` tile so the descent is visually discoverable — invisible stairs make the game unwinnable and are a build failure.
- Animate: 2–3 idle frames cycled by turn/time (gentle breathe/bob via a sine - Animate: 2–3 idle frames cycled by turn/time (gentle breathe/bob via a sine
offset); attack = a short lunge; taking damage = a white hit-flash; death = a offset); attack = a short lunge; taking damage = a white hit-flash; death = a
poof. Small Slimes use a smaller, cuter variant of the slime sprite. poof. Small Slimes use a smaller, cuter variant of the slime sprite.
@@ -401,6 +410,7 @@ The game is DONE when ALL of these are true:
- [ ] Standing on an item/stairs shows the exact key needed; `g` pickup and `f` descent work - [ ] Standing on an item/stairs shows the exact key needed; `g` pickup and `f` descent work
- [ ] Simple sound effects play when audio is available; missing audio devices fall back silently - [ ] Simple sound effects play when audio is available; missing audio devices fall back silently
- [ ] Entities, tiles, and items are drawn as distinct procedural pixel-art sprites (not flat colored squares); no external image files are loaded - [ ] Entities, tiles, and items are drawn as distinct procedural pixel-art sprites (not flat colored squares); no external image files are loaded
- [ ] Every level is winnable: on floors 0–8 stairs exist, are reachable from spawn, and are VISIBLY RENDERED (the `>` staircase); floor 9 is won by slaying a dragon the player can actually damage with floor-9-appropriate gear
### Systems Depth (judging criteria) ### Systems Depth (judging criteria)
- [ ] **A* pathfinding** — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you. - [ ] **A* pathfinding** — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you.
+9
View File
@@ -71,6 +71,15 @@ You are done when ALL of these are true:
- You can play: move, explore, fight, stand on loot and press `g`, stand on - You can play: move, explore, fight, stand on loot and press `g`, stand on
stairs and press `f`, level up, save, quit, relaunch, and continue stairs and press `f`, level up, save, quit, relaunch, and continue
— all without crashes. — all without crashes.
- Every level is winnable: floors 0–8 have stairs that EXIST, are REACHABLE
from spawn, and are VISIBLY RENDERED (the `>` staircase) so the player can
descend with `f`; floor 9 is won by slaying the dragon, who must be
defeatable with gear obtainable by floor 9 (total_power must exceed the
dragon's armor). The smoke gate must assert stairs exist + are reachable on
every floor 0–8 and that the renderer draws the stairs tile. A floor with
missing, unreachable, or invisible stairs — or an unkillable boss — is a
build failure. (A prior build shipped stairs only in map data, never drawn —
do not repeat that.)
Do not stop early. Do not ask for clarification. The specification is complete. Do not stop early. Do not ask for clarification. The specification is complete.
Build the game. Build the game.
+1
View File
@@ -0,0 +1 @@
"""Rendering package: pure read-and-draw of GameSession."""
+36 -17
View File
@@ -1,27 +1,46 @@
"""Viewport camera that eases toward the player each frame (plan.md Juice).""" """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 __future__ import annotations
import math from data.constants import MAP_W, MAP_H, TILE
class Camera: class Camera:
"""Pixel-space camera top-left. Eases toward its target; can snap.""" def __init__(self, smoothing: float = 0.18) -> None:
def __init__(self) -> None:
self.x: float = 0.0 self.x: float = 0.0
self.y: float = 0.0 self.y: float = 0.0
self._tx: float = 0.0 self.smoothing = max(0.0, min(1.0, smoothing))
self._ty: float = 0.0
def set_target(self, px: float, py: float) -> None: def reset(self, player_xy: tuple[int, int]) -> None:
self._tx = px self.x = float(player_xy[0] * TILE)
self._ty = py self.y = float(player_xy[1] * TILE)
def snap(self, px: float, py: float) -> None: def update(self, player_xy: tuple[int, int]) -> tuple[int, int]:
self.x = self._tx = px tx = player_xy[0] * TILE
self.y = self._ty = py 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 update(self, dt: float, ease: float = 7.0) -> None: def offset_for(self, surface_wh: tuple[int, int], player_xy: tuple[int, int]) -> tuple[int, int]:
k = 1.0 - math.exp(-ease * dt) """Center the player on screen, clamped to the map bounds (pixel offset)."""
self.x += (self._tx - self.x) * k sw, sh = surface_wh
self.y += (self._ty - self.y) * k 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
+102 -159
View File
@@ -1,181 +1,124 @@
"""Procedural visual effects: particles, floating combat text, screen shake, """Render-only effects: screen-shake, particles, and a vignette.
lighting helpers (torch falloff, vignette). All drawn from state; none mutate it.
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 from __future__ import annotations
import math import math
import random import random
from typing import Any
try:
import pygame import pygame
except Exception: # pragma: no cover
pygame = None # type: ignore _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)
# --------------------------------------------------------------------------- #
# Particles — pooled and capped.
# --------------------------------------------------------------------------- #
class Particles: class Particles:
def __init__(self, cap: int = 260) -> None: """Pooled, capped particle bursts (hit sparks, blood, level-up stars, etc.)."""
self._pool: list[dict] = []
self._cap = cap
def clear(self) -> None: def __init__(self) -> None:
self._pool.clear() self._parts: list[dict[str, Any]] = []
def burst(self, x: float, y: float, color, n: int = 10, speed: float = 70.0, def burst(self, x: float, y: float, color: tuple[int, int, int],
life: float = 0.45, gravity: float = 0.0, size: int = 2) -> None: count: int = 10, speed: float = 60.0, life: float = 0.4) -> None:
for _ in range(n): for _ in range(count):
if len(self._pool) >= self._cap: if len(self._parts) >= _MAX_PARTICLES:
self._pool.pop(0) break
ang = random.random() * math.tau ang = random.uniform(0, math.tau)
spd = random.uniform(speed * 0.25, speed) spd = speed * random.uniform(0.4, 1.0)
self._pool.append(dict( self._parts.append({
x=x, y=y, vx=math.cos(ang) * spd, vy=math.sin(ang) * spd, "x": x, "y": y,
life=life, max=life, color=color, g=gravity, size=size)) "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: def update(self, dt: float) -> None:
out = [] alive: list[dict[str, Any]] = []
drag = max(0.0, 1.0 - 2.2 * dt) for p in self._parts:
for p in self._pool: p["age"] += dt
p["life"] -= dt if p["age"] >= p["life"]:
if p["life"] <= 0:
continue continue
p["x"] += p["vx"] * dt p["x"] += p["vx"] * dt
p["y"] += p["vy"] * dt p["y"] += p["vy"] * dt
p["vy"] += p["g"] * dt p["vy"] += 90.0 * dt # gentle gravity
p["vx"] *= drag alive.append(p)
p["vy"] *= drag self._parts = alive
out.append(p)
self._pool = out
def draw(self, surf, cam) -> None: def draw(self, surface: pygame.Surface, cam_xy: tuple[int, int]) -> None:
if pygame is None: ox, oy = cam_xy
return for p in self._parts:
for p in self._pool: t = 1.0 - p["age"] / p["life"]
frac = max(0.0, p["life"] / p["max"]) r = max(1, int(p["size"] * t))
a = max(0, min(255, int(255 * frac))) c = p["color"]
r = max(1, int(p["size"] * (0.6 + 0.4 * frac))) col = (int(c[0] * t), int(c[1] * t), int(c[2] * t))
sx = int(p["x"] - cam[0]) pygame.draw.circle(surface, col, (int(p["x"] - ox), int(p["y"] - oy)), r)
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))
# --------------------------------------------------------------------------- # def vignette(size: tuple[int, int]) -> pygame.Surface:
# Floating combat text. """Soft edge-darkening overlay (cached by size via module dict)."""
# --------------------------------------------------------------------------- # key = size
class FloatText: surf = _VIGNETTE_CACHE.get(key)
def __init__(self) -> None: if surf is not None:
self._items: list[dict] = [] return surf
w, h = size
def clear(self) -> None: surf = pygame.Surface((w, h), pygame.SRCALPHA)
self._items.clear() cx, cy = w / 2, h / 2
max_d = math.hypot(cx, cy)
def add(self, x: float, y: float, text: str, color, big: bool = False) -> None: # Subtle edge-only vignette: concentric non-overlapping annuli (width=step)
self._items.append(dict( # so alpha never accumulates. Only the outer ~38% of the screen darkens; the
x=x, y=y, text=text, color=color, life=0.95, max=0.95, # center stays clear. Max alpha is gentle so edges are never crushed to black.
vy=-30.0, big=big)) step = 8
inner_t = 0.62 # no darkening inside 62% of the corner distance
def update(self, dt: float) -> None: max_alpha = 78
out = [] r = int(max_d)
for it in self._items: while r > 0:
it["life"] -= dt t = r / max_d
if it["life"] <= 0: if t > inner_t:
continue u = (t - inner_t) / (1.0 - inner_t)
it["y"] += it["vy"] * dt alpha = int(max_alpha * u * u)
it["vy"] *= max(0.0, 1.0 - 1.6 * dt) if alpha > 0:
out.append(it) pygame.draw.circle(surf, (0, 0, 0, alpha), (int(cx), int(cy)), r, step)
self._items = out r -= step
_VIGNETTE_CACHE[key] = surf
def draw(self, surf, font, font_big, cam) -> None: return surf
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])))
# --------------------------------------------------------------------------- # _VIGNETTE_CACHE: dict[tuple[int, int], pygame.Surface] = {}
# 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))
+455 -469
View File
@@ -1,520 +1,506 @@
"""Pure renderer: composes the world + UI from a GameSession (never mutates it). """Pure renderer: composes map tiles, entities, lighting, juice, and UI.
Layout (module constants, derived from C.TILE): Reads ``GameSession`` and draws — never mutates game state. Visibility for
+---------------------------------------------+---- lighting is DERIVED here via FOV (read-only) so a freshly-built session renders
| TOP BAR floor | HP bar | level | XP bar | } SIDE panel correctly even before the action layer has ticked. Stairs are ALWAYS blitted on
+---------------------------------------------+ ) (log) ``stairs_down`` when in view/remembered (invisible stairs make the game
| | ) unwinnable).
| MAP VIEWPORT (camera follows player)| )
| | )
+---------------------------------------------+----
| BOTTOM BAR equipment | effects | sound | prompt|
+---------------------------------------------+
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any
import math import math
try:
import pygame import pygame
except Exception: # pragma: no cover
pygame = None # type: ignore
from data import constants as C from data.constants import (
from data import sprites as S TILE, SIGHT_RADIUS, COLORS, MAP_W, MAP_H,
from render import sprites as RS
from render.camera import Camera
from render.effects import (
FloatText, Particles, Shake, make_torch, make_vignette, torch_factor,
) )
from engine.fov import compute_fov
from render.sprites import get_tile_sprite
from render.effects import Particles, Shake, vignette, torch_factor
TILE: int = C.TILE _BG = COLORS["bg"]
VIEW_TW: int = 48 _FONT_STACK = "monospace,consolas,couriernew,dejavusans"
VIEW_TH: int = 28 # Sprites rendered larger than one tile (centered on their tile).
MAP_W_PX: int = VIEW_TW * TILE _BIG_SPRITES = frozenset({"ancient_dragon"})
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): def _dim(color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
return (max(0, min(255, int(color[0] * f))), return (int(color[0] * factor), int(color[1] * factor), int(color[2] * factor))
max(0, min(255, int(color[1] * f))),
max(0, min(255, int(color[2] * f))))
def _hash(tx: int, ty: int) -> float: def _hash2(x: int, y: int) -> int:
n = (tx * 73856093) ^ (ty * 19349663) return (x * 73856093 ^ y * 19349663) & 0xFF
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: class Renderer:
def __init__(self, size, audio) -> None: def __init__(self) -> None:
self.W, self.H = size
self.audio = audio
self.cam = Camera()
self.particles = Particles() self.particles = Particles()
self.floats = FloatText()
self.shake = Shake() self.shake = Shake()
self._dt = 0.0 self._anim = 0.0
self._cam_world = (0.0, 0.0) self._last_hp: int | None = None
self._fx_cam = (0.0, 0.0) self._last_log_len = 0
fname = "dejavusans,arial,helvetica,sans" self._font_big: pygame.font.Font | None = None
self.font = pygame.font.SysFont(fname, 13) self._font_small: pygame.font.Font | None = None
self.font_s = pygame.font.SysFont(fname, 11) self._font: pygame.font.Font | None = None
self.font_b = pygame.font.SysFont(fname, 15, bold=True) self._fonts_ok = True
self.font_l = pygame.font.SysFont(fname, 30, bold=True) self._torch: pygame.Surface | None = None
self.font_xl = pygame.font.SysFont(fname, 46, bold=True) self._glow_surf: pygame.Surface | None = None
self.vignette = make_vignette(MAP_W_PX, MAP_H_PX) self._shadow_cache: dict[int, pygame.Surface] = {}
self.torch = make_torch(C.SIGHT_RADIUS * TILE)
# ------------------------------------------------------------------ # # --------------------------------------------------------------- fonts
def update(self, dt: float) -> None: def _fonts(self) -> None:
self._dt = max(0.001, dt) if not self._fonts_ok or self._font is not None:
self.particles.update(dt) return
self.floats.update(dt) 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 world_px(self, tx: int, ty: int): def _text(self, surf: pygame.Surface, msg: str, pos: tuple[int, int],
"""Screen-pixel center of a world tile (for spawning effects).""" color: tuple[int, int, int], big: bool = False,
cx, cy = self._cam_world small: bool = False) -> None:
wx = tx * TILE + TILE / 2 if self._font is None:
wy = ty * TILE + TILE / 2 return
return (wx - cx + MAP_X, wy - cy + MAP_Y) 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
# World def render(self, surface: pygame.Surface, session: Any,
# ------------------------------------------------------------------ # camera_xy: tuple[int, int] = (0, 0)) -> None:
def render_world(self, screen, session, t: float) -> None: self._fonts()
floor = session.dungeon[session.current_floor] self._anim += 0.016
p = session.player self.particles.update(0.016)
map_pw = C.MAP_WIDTH * TILE
map_ph = C.MAP_HEIGHT * TILE
tgt_x = p.x * TILE + TILE / 2 - MAP_W_PX / 2 gm = session.dungeon[session.current_floor]
tgt_y = p.y * TILE + TILE / 2 - MAP_H_PX / 2 player = session.player
tgt_x = max(0.0, min(tgt_x, max(0.0, map_pw - MAP_W_PX))) vis = compute_fov(gm, (player.x, player.y), SIGHT_RADIUS)
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) cam_x, cam_y = camera_xy
vis = floor.visible sh_x, sh_y = self.shake.offset()
expl = floor.explored ox, oy = cam_x - sh_x, cam_y - sh_y
tx0 = max(0, int(cx // TILE) - 1) sw, sh = surface.get_size()
tx1 = min(C.MAP_WIDTH - 1, int((cx + MAP_W_PX) // TILE) + 1)
ty0 = max(0, int(cy // TILE) - 1) surface.fill(_BG)
ty1 = min(C.MAP_HEIGHT - 1, int((cy + MAP_H_PX) // TILE) + 1)
px, py = p.x, p.y x0 = max(0, ox // TILE)
for ty in range(ty0, ty1 + 1): y0 = max(0, oy // TILE)
row_v = vis[ty] x1 = min(gm.width, (ox + sw) // TILE + 1)
row_e = expl[ty] y1 = min(gm.height, (oy + sh) // TILE + 1)
row_t = floor.tiles[ty]
sy = round(ty * TILE - cy + soy) + MAP_Y # Visible terrain/entities are drawn to a light layer at FULL brightness,
for tx in range(tx0, tx1 + 1): # then a smooth radial torch gradient is multiplied in. That gives a soft
if not row_e[tx] and not row_v[tx]: # 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 continue
sx = round(tx * TILE - cx + sox) + MAP_X is_wall = not gm.walkable(tx, ty)
if row_v[tx]: if visible:
light = torch_factor(math.hypot(tx - px, ty - py), C.SIGHT_RADIUS) if is_wall:
if row_t[tx] == 0: self._wall(light, px, py, tx, ty, 1.0)
self._wall(screen, sx, sy, tx, ty, light)
else: else:
self._floor(screen, sx, sy, tx, ty, light) self._floor(light, px, py, tx, ty, 1.0)
else: else:
col = WALL_E if row_t[tx] == 0 else FLOOR_E if is_wall:
pygame.draw.rect(screen, col, (sx, sy, TILE, TILE)) self._wall_explored(surface, px, py, tx, ty)
if row_t[tx] == 0: else:
pygame.draw.rect(screen, _shade(col, 0.7), (sx, sy + TILE - 3, TILE, 3)) 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))
if self.torch is not None: # ---- entities (items under, enemies over, player on top) ----
ts = self.torch.get_width() for e in gm.entities:
gx = round(px * TILE + TILE / 2 - (cx - sox)) + MAP_X - ts // 2 if self._is_item(e):
gy = round(py * TILE + TILE / 2 - (cy - soy)) + MAP_Y - ts // 2 if (e.x, e.y) in vis:
screen.blit(self.torch, (gx, gy), special_flags=pygame.BLEND_RGB_ADD) 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))
self._draw_entities(screen, floor, p, cx - sox, cy - soy, t) # 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)
if self.vignette is not None: self.particles.draw(surface, (ox, oy))
screen.blit(self.vignette, (MAP_X, MAP_Y)) self._sense_events(session, vis, ox, oy)
surface.blit(vignette((sw, sh)), (0, 0))
self._ui(surface, session, sw, sh)
self.particles.draw(screen, self._fx_cam) # --------------------------------------------------------------- tiles
self.floats.draw(screen, self.font_s, self.font_b, self._fx_cam) 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))
self._ui_top(screen, session) def _wall(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
self._ui_log(screen, session) f: float = 1.0) -> None:
self._ui_bottom(screen, session) 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 _wall(self, surf, sx, sy, tx, ty, light) -> None: def _floor_explored(self, surf: pygame.Surface, px: int, py: int,
h = _hash(tx, ty) tx: int, ty: int) -> None:
h2 = _hash(tx + 101, ty - 57) base = COLORS["floor_explored"]
bevel = max(2, TILE // 7) pygame.draw.rect(surf, base, (px, py, TILE, TILE))
# per-tile base shade so no two walls read identically h = _hash2(tx, ty)
pygame.draw.rect(surf, _shade(WALL_V, light * (0.82 + 0.36 * h)), (sx, sy, TILE, TILE)) pygame.draw.rect(surf, _dim(base, 0.7),
pygame.draw.rect(surf, _shade(WALL_V, light * 1.45), (sx, sy, TILE, bevel)) # lit top bevel (px + (h % (TILE - 4)) + 2, py + ((h >> 3) % (TILE - 4)) + 2, 2, 2))
pygame.draw.rect(surf, _shade(WALL_V, light * 0.5), pygame.draw.rect(surf, _dim(base, 1.3),
(sx, sy + TILE - bevel, TILE, bevel)) # shadow base (px + ((h >> 2) % (TILE - 4)) + 2, py + ((h >> 5) % (TILE - 4)) + 2, 2, 2))
# 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: def _wall_explored(self, surf: pygame.Surface, px: int, py: int,
h = _hash(tx, ty) tx: int, ty: int) -> None:
pygame.draw.rect(surf, _shade(FLOOR_V, light * (0.86 + 0.28 * h)), (sx, sy, TILE, TILE)) pygame.draw.rect(surf, COLORS["wall_explored"], (px, py, TILE, TILE))
# subtle checkerboard dither (stable per tile parity) pygame.draw.rect(surf, _dim(COLORS["wall_explored"], 1.35), (px, py, TILE, 3)) # faint top edge
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: def _torch_mask(self) -> pygame.Surface:
from entities.enemy import Enemy """Cached smooth radial brightness mask (white core -> gray rim).
from entities.item import Item
vis = floor.visible Built tiny then smooth-scaled so the falloff is bilinear-smooth with no
# ground features first (remembered on explored tiles) tile-sized bands. Multiplied (BLEND_RGB_MULT) onto the light layer.
ground = [e for e in floor.entities """
if isinstance(e, Item) or (not isinstance(e, Enemy) and getattr(e, "sprite_key", "") == "stairs")] if self._torch is not None:
for e in ground: return self._torch
if not (vis[e.y][e.x] or floor.explored[e.y][e.x]): diam = (SIGHT_RADIUS * TILE + TILE) * 2 # covers the whole FOV disc + rim
continue s = 64
self._blit_entity(surf, e, cx, cy, t, shadow=True) small = pygame.Surface((s, s), pygame.SRCALPHA)
# actors: visible enemies + the player, sorted by y for overlap c = (s - 1) / 2
actors = [e for e in floor.entities for yy in range(s):
if isinstance(e, Enemy) and e.hp > 0 and vis[e.y][e.x]] for xx in range(s):
actors.append(player) t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
actors.sort(key=lambda e: e.y) b = 0.45 + 0.55 * (1.0 - t) ** 1.5 # 1.0 core -> ~0.45 rim
for e in actors: g = int(b * 255)
self._blit_entity(surf, e, cx, cy, t, shadow=True, is_actor=True) small.set_at((xx, yy), (g, g, g, 255))
self._torch = pygame.transform.smoothscale(small, (diam, diam))
return self._torch
def _blit_entity(self, surf, e, cx, cy, t, shadow=False, is_actor=False) -> None: def _glow(self) -> pygame.Surface:
from entities.enemy import Enemy """Cached warm radial glow added (BLEND_RGB_ADD) at the torch core so the
sx = round(e.x * TILE - cx) + MAP_X bright center reads clearly against the dimmer rim."""
sy = round(e.y * TILE - cy) + MAP_Y if self._glow_surf is not None:
if shadow: return self._glow_surf
sh = pygame.Surface((TILE - 4, 5), pygame.SRCALPHA) diam = SIGHT_RADIUS * TILE * 2
pygame.draw.ellipse(sh, (0, 0, 0, 90), sh.get_rect()) s = 48
surf.blit(sh, (sx + 2, sy + TILE - 5)) 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
name = e.sprite_key def _shadow_surf(self, size: int) -> pygame.Surface:
if name == "player": """Cached soft elliptical ground shadow (~90% tile wide) drawn under an
name = "player_" + getattr(e, "facing", "down") entity/stairs so sprites read as grounded. Built from concentric ellipses
if name not in S.SPRITES: with rising alpha toward the center for a feathered edge."""
name = "player_down" s = self._shadow_cache.get(size)
frame = int(t * 2.5 + (e.x * 7 + e.y * 13)) % max(1, RS.frame_count(name)) if s is not None:
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 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
def _ui_top(self, surf, session) -> None: # --------------------------------------------------------------- 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 p = session.player
self._panel(surf, (0, 0, WIN_W, TOP_H), COL["ui_bg"]) cx = p.x * TILE - ox + TILE // 2
self._text(surf, f"Floor {session.current_floor + 1}/{C.FLOORS}", (8, 9), self.font_b, COL["prompt"]) cy = p.y * TILE - oy + TILE // 2
# HP bar # player took damage since last frame
hx = 150 hp = getattr(p, "hp", None)
self._bar(surf, (hx, 10, 240, 14), p.hp / max(1, p.max_hp), if self._last_hp is not None and hp is not None and hp < self._last_hp:
COL["hp_full"], COL["hp_back"], icon=self._heart()) self.shake.trigger(6.0)
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + 246, 9), self.font_s) self.particles.burst(cx, cy, COLORS["hp_empty"], count=10, speed=80)
# Level + XP if hp <= 0:
self._text(surf, f"Lv {p.level}", (hx + 320, 9), self.font_b, COL["prompt"]) self.particles.burst(cx, cy, (220, 220, 220), count=22, speed=120, life=0.7)
xp_next = C.XP_THRESHOLDS.get(min(p.level + 1, C.MAX_LEVEL), p.xp) self._last_hp = hp
xp_cur = C.XP_THRESHOLDS.get(p.level, 0) # new log lines -> spawn flavor at the player
frac = (p.xp - xp_cur) / max(1, xp_next - xp_cur) if xp_next > xp_cur else 1.0 new_lines = session.log[self._last_log_len:]
self._bar(surf, (WIN_W - SIDE_W - 150, 10, 130, 14), frac, COL["xp_full"], COL["xp_back"]) self._last_log_len = len(session.log)
self._text(surf, "XP", (WIN_W - SIDE_W - 172, 9), self.font_s, COL["xp_full"]) 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)
def _ui_log(self, surf, session) -> None: # --------------------------------------------------------------- UI
x = MAP_W_PX def _ui(self, surf: pygame.Surface, session: Any, sw: int, sh: int) -> None:
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 p = session.player
y = WIN_H - BOT_H # ---- top bar ----
self._panel(surf, (0, y, WIN_W, BOT_H), COL["ui_bg"]) self._panel(surf, (0, 0, sw, 28))
# equipment slots floor_n = session.current_floor + 1
self._text(surf, "WPN", (8, y + 6), self.font_s, COL["weapon"]) self._text(surf, f"Floor {floor_n}/10", (6, 6), COLORS["text"])
wpn = p.equipped.get("weapon")
self._slot(surf, 8, y + 20, wpn) # HP: pixel-art heart icon + red track / green fill
self._text(surf, "ARM", (42, y + 6), self.font_s, COL["armor"]) hx, hy, hw = 156, 8, 140
self._slot(surf, 42, y + 20, p.equipped.get("armor")) self._heart(surf, 134, 6)
# active effect timers pygame.draw.rect(surf, COLORS["hp_empty"], (hx, hy, hw, 12))
ex = 90 frac = max(0.0, p.hp / max(1, p.max_hp))
self._text(surf, "Effects", (ex, y + 6), self.font_s, COL["prompt"]) pygame.draw.rect(surf, COLORS["hp_full"], (hx, hy, int(hw * frac), 12))
if p.effects: pygame.draw.rect(surf, COLORS["panel_border"], (hx, hy, hw, 12), 1)
tx = ex self._text(surf, f"{p.hp}/{p.max_hp}", (hx + hw + 5, 6), COLORS["text"])
for eff in p.effects:
label = ("STR" if eff.kind == "strength" else "INV") # Level/XP: star icon + Lv + XP bar (right side)
col = COL["weapon"] if eff.kind == "strength" else COL["wraith"] star_x = sw - 252
self._text(surf, f"{label} {eff.duration}", (tx, y + 22), self.font_s, col) self._star(surf, star_x, 6)
tx += 52 self._text(surf, f"Lv {p.level}", (star_x + 16, 6), COLORS["text"])
else: xx, xw = sw - 170, 112
self._text(surf, "-", (ex, y + 22), self.font_s, (90, 90, 100)) pygame.draw.rect(surf, (30, 30, 40), (xx, 10, xw, 8))
# sound icon lvl = min(max(1, p.level), 9)
self._text(surf, "[m] sound " + ("OFF" if self.audio.muted else "ON"), need = [30, 70, 140, 250, 400, 600, 850, 1150, 1500][lvl - 1]
(WIN_W - SIDE_W - 110, y + 22), self.font_s, prev = [0, 30, 70, 140, 250, 400, 600, 850, 1150][lvl - 1]
(120, 120, 130) if self.audio.muted else COL["log_levelup"]) xpfrac = max(0.0, min(1.0, (p.xp - prev) / max(1, need - prev)))
# context prompt pygame.draw.rect(surf, COLORS["xp_bar"], (xx, 10, int(xw * xpfrac), 8))
prompt = self._context(session) 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: if prompt:
self._text(surf, prompt, (8, y + BOT_H - 16), self.font_b, COL["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"])
def _slot(self, surf, x, y, item) -> None: # --------------------------------------------------------------- UI helpers
rect = (x, y, 28, 22) @staticmethod
pygame.draw.rect(surf, COL["ui_panel"], rect) def _log_color(line: str) -> tuple[int, int, int]:
pygame.draw.rect(surf, COL["ui_border"], rect, 1) 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: if item is not None:
ico = RS.get(item.sprite_key, 0, 20) kind = getattr(item, "kind", "") or getattr(item, "sprite_key", "")
if ico is not None: surf.blit(get_tile_sprite(kind, 20), (x + 2, y + 2))
surf.blit(ico, (x + 4, y + 1)) 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(self, session) -> str: def _context_prompt(self, session: Any) -> str:
from entities.item import Item
p = session.player p = session.player
floor = session.dungeon[session.current_floor] gm = session.dungeon[session.current_floor]
for e in floor.entities: item = next((e for e in gm.entities
if isinstance(e, Item) and e.x == p.x and e.y == p.y: if self._is_item(e) and e.x == p.x and e.y == p.y), None)
return f"Press G to pick up {e.name}" if item is not None:
if (p.x, p.y) == floor.stairs_down and session.current_floor < C.FLOORS - 1: return f"Press G to pick up {item.name}"
if gm.stairs_down == (p.x, p.y):
return "Press F to descend" return "Press F to descend"
return "" return ""
# ------------------------------------------------------------------ # def _panel(self, surf: pygame.Surface, rect: tuple[int, int, int, int]) -> None:
# Screens pygame.draw.rect(surf, COLORS["panel"], rect)
# ------------------------------------------------------------------ # pygame.draw.rect(surf, COLORS["panel_border"], rect, 1)
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)"
+133 -37
View File
@@ -1,55 +1,151 @@
"""Rasterize palette-key sprite grids to cached pygame Surfaces (plan.md Rendering). """Rasterize palette-key grids to cached pygame Surfaces.
`get(name, frame, tile)` builds a Surface once (keyed by name+frame+tile) and ``get_sprite(name)`` returns the native-size cached Surface; the renderer scales
caches it. The renderer blits the cached surface directly. Pixel-art is kept it to ``TILE`` via ``get_tile_sprite``. All art is procedural (pygame.draw /
crisp with nearest-neighbour `transform.scale` (never smoothscale). set_at from in-code palettes); no external image files are loaded.
""" """
from __future__ import annotations from __future__ import annotations
try: from typing import Any
import pygame import pygame
except Exception: # pragma: no cover
pygame = None # type: ignore
from data import sprites as S from data import sprites as SPRITE_DATA
from data.constants import PALETTE, TILE as _TILE from data.constants import PALETTE, TILE
_cache: dict = {} _NATIVE: dict[str, pygame.Surface] = {}
_SCALED: dict[str, pygame.Surface] = {}
def get(name: str, frame: int = 0, tile: int = _TILE): def _color(ch: str, tint: tuple[int, int, int] | None) -> tuple[int, int, int] | None:
"""Return the cached Surface for `name` scaled to `tile`x`tile`.""" if ch == "a":
if pygame is None: return tint if tint is not None else (200, 200, 200)
return None return PALETTE.get(ch)
key = (name, frame, tile)
cached = _cache.get(key)
if cached is not None: def _rasterize(grid: list[str], tint: tuple[int, int, int] | None) -> pygame.Surface:
return cached
grid = S.grid(name, frame)
h = len(grid) h = len(grid)
w = max(len(r) for r in grid) if grid else 1 w = max((len(row) for row in grid), default=1)
w = max(1, w) w = max(1, w)
cell = 3 # fixed >=2 internal px/cell; crisp nearest-scale to any tile size surf = pygame.Surface((w, h), pygame.SRCALPHA)
surf = pygame.Surface((w * cell, h * cell), pygame.SRCALPHA)
for y, row in enumerate(grid): for y, row in enumerate(grid):
for x, ch in enumerate(row): for x, ch in enumerate(row):
col = PALETTE.get(ch) c = _color(ch, tint)
if col is not None: if c is not None:
pygame.draw.rect(surf, col, (x * cell, y * cell, cell, cell)) surf.set_at((x, y), (c[0], c[1], c[2], 255))
if (w * cell, h * cell) != (tile, tile):
surf = pygame.transform.scale(surf, (tile, tile))
_cache[key] = surf
return surf return surf
def frame_count(name: str) -> int: def _convert(surf: pygame.Surface) -> pygame.Surface:
return S.frames_count(name) try:
return surf.convert_alpha()
except Exception:
return surf # no display yet (e.g. constructed before set_mode): use raw
def warm(tile: int = _TILE) -> None: def _make_dragon() -> pygame.Surface:
"""Pre-rasterize every sprite frame so the first frame is hitch-free.""" """Procedural 2x2 boss dragon: ONE connected silhouette (wings+body+head+tail
if pygame is None: drawn in the same red with no internal outlines, so it reads as a single
return creature, not separate blobs), then details layered on top."""
for name in S.NAMES: size = TILE * 2
for f in range(S.frames_count(name)): s = pygame.Surface((size, size), pygame.SRCALPHA)
get(name, f, tile) 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()
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+783 -527
View File
File diff suppressed because it is too large. Load diff