Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2eb2a44fa9 | ||
|
|
4a549d002f |
No files matched your search
@@ -0,0 +1 @@
|
||||
4
|
||||
@@ -1,14 +0,0 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
|
||||
# Runtime / build artifacts
|
||||
save.json
|
||||
.build_state
|
||||
.pipeline.pid
|
||||
logs/
|
||||
.pi/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
@@ -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] ============================================================
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
49976 49976
|
||||
@@ -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] ============================================================
|
||||
@@ -0,0 +1 @@
|
||||
37587 37587
|
||||
@@ -0,0 +1 @@
|
||||
68252 68252
|
||||
@@ -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'
|
||||
@@ -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.
|
||||
@@ -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'
|
||||
@@ -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.
|
||||
@@ -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 [])
|
||||
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 30 KiB |
@@ -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)))
|
||||
@@ -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.")
|
||||
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 46 KiB |
@@ -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`,
|
||||
`entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop.
|
||||
- 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):**
|
||||
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
|
||||
- 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
|
||||
- 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
|
||||
|
||||
@@ -173,6 +174,13 @@ When you believe you are done:
|
||||
`Press F to descend`. Automated tests must exercise both actions.
|
||||
- **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.
|
||||
- **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
|
||||
a phase and the acceptance criteria aren't all met, keep building.
|
||||
- **Flat colored-square art.** Entities/tiles drawn as plain rectangles read as
|
||||
|
||||
@@ -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
|
||||
covers the enemy's tile (and the player is not invisible). Slow enemies
|
||||
(speed > 1) act every Nth turn via act_counter. Enemies never stack: other
|
||||
blocking entities are treated as impassable.
|
||||
Each turn the game loop calls ``act_enemy`` once per living enemy, after the
|
||||
player acts. The function mutates ``enemy.x``/``enemy.y``/``enemy.last_known_pos``
|
||||
in place and, when adjacent, resolves a melee attack through ``engine.combat``.
|
||||
It never raises on valid game state.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from engine import combat, game_state, pathfinding
|
||||
from engine.map_gen import is_walkable
|
||||
from engine.combat import roll_attack
|
||||
from engine.pathfinding import find_path
|
||||
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:
|
||||
r = rng if rng is not None else (getattr(session, "rng", None) or random)
|
||||
floor = session.dungeon[session.current_floor]
|
||||
player = session.player
|
||||
# Behavior tuning. Plan-defined, kept here as named constants (not magic numbers).
|
||||
_WANDER_MOVE_CHANCE: float = 0.5 # wander: 50/50 move vs wait
|
||||
_FLEE_HP_FRACTION: float = 0.30 # flee when hp below 30% of max
|
||||
_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:
|
||||
enemy.act_counter += 1
|
||||
if enemy.act_counter % enemy.speed != 0:
|
||||
return
|
||||
# ponytail: per-enemy turn parity for the "phase" behavior (acts every 2 turns).
|
||||
# Enemy is a slots dataclass we may not extend here, so bookkeep in a dict keyed
|
||||
# by id(). Ceiling: grows with the enemy count of one run; id() reuse after GC is
|
||||
# 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
|
||||
if bh == "wander":
|
||||
_wander(enemy, floor, session, r)
|
||||
elif bh == "chase":
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
elif bh == "flee":
|
||||
_flee(enemy, floor, session, r, player_visible)
|
||||
elif bh == "ranged":
|
||||
_ranged(enemy, floor, session, r, player_visible)
|
||||
elif bh == "phase":
|
||||
_phase(enemy, floor, session, r, player_visible)
|
||||
elif bh == "split":
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
def act_enemy(
|
||||
enemy: Any,
|
||||
game_map: Any,
|
||||
player: Any,
|
||||
visible: set[tuple[int, int]],
|
||||
rng: random.Random = random,
|
||||
) -> None:
|
||||
"""Resolve one enemy turn, dispatching on ``enemy.behavior``."""
|
||||
behavior = getattr(enemy, "behavior", "wander")
|
||||
if behavior == "wander":
|
||||
_wander(enemy, game_map, rng)
|
||||
elif behavior == "phase":
|
||||
_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:
|
||||
_wander(enemy, floor, session, r)
|
||||
|
||||
|
||||
# --- 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)
|
||||
_chase(enemy, game_map, player, visible, rng)
|
||||
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:
|
||||
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)
|
||||
# --------------------------------------------------------------------- behaviors
|
||||
|
||||
|
||||
def _ranged(enemy, floor, session, r, player_visible) -> None:
|
||||
player = session.player
|
||||
if not player_visible:
|
||||
_wander(enemy, floor, session, r)
|
||||
def _wander(enemy: Any, game_map: Any, rng: random.Random) -> None:
|
||||
if rng.random() < _WANDER_MOVE_CHANCE:
|
||||
return
|
||||
dist = _manhattan((enemy.x, enemy.y), (player.x, player.y))
|
||||
if dist > 3:
|
||||
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)
|
||||
moves = [d for d in _DIRS if game_map.walkable(enemy.x + d[0], enemy.y + d[1])]
|
||||
if not moves:
|
||||
return
|
||||
if not player_visible:
|
||||
_wander(enemy, floor, session, r)
|
||||
dx, dy = rng.choice(moves)
|
||||
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
|
||||
# Drift toward the player through walls, but never onto another entity.
|
||||
best = None
|
||||
best_d = _manhattan((enemy.x, enemy.y), (player.x, player.y))
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
continue
|
||||
if _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
d = _manhattan((nx, ny), (player.x, player.y))
|
||||
if d < best_d:
|
||||
best_d = d
|
||||
best = (nx, ny)
|
||||
if best is not None:
|
||||
enemy.x, enemy.y = best
|
||||
blockers = _enemy_blockers(game_map, enemy, player)
|
||||
_step_toward(enemy, game_map, (px, py), blockers)
|
||||
return
|
||||
# Player out of sight: move toward the last known position, else wander.
|
||||
lkp = enemy.last_known_pos
|
||||
if lkp is None or (enemy.x, enemy.y) == lkp:
|
||||
enemy.last_known_pos = None
|
||||
_wander(enemy, game_map, rng)
|
||||
return
|
||||
blockers = _enemy_blockers(game_map, enemy, player)
|
||||
_step_toward(enemy, game_map, lkp, blockers)
|
||||
|
||||
|
||||
def _move_away(enemy, floor, session, r, threat) -> None:
|
||||
best = None
|
||||
best_d = _manhattan((enemy.x, enemy.y), threat)
|
||||
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 not is_walkable(floor, nx, ny) or _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
d = _manhattan((nx, ny), threat)
|
||||
if d > best_d:
|
||||
best_d = d
|
||||
best = (nx, ny)
|
||||
if best is not None:
|
||||
enemy.x, enemy.y = best
|
||||
else:
|
||||
_wander(enemy, floor, session, r)
|
||||
def _flee(
|
||||
enemy: Any,
|
||||
game_map: Any,
|
||||
player: Any,
|
||||
visible: set[tuple[int, int]],
|
||||
rng: random.Random,
|
||||
) -> None:
|
||||
px, py = player.x, player.y
|
||||
if (px, py) not in visible:
|
||||
_wander(enemy, game_map, rng)
|
||||
return
|
||||
_step_away(enemy, game_map, px, py)
|
||||
|
||||
|
||||
def _ranged_attack(enemy, player, r, log) -> None:
|
||||
acc = getattr(enemy, "accuracy", 0)
|
||||
eva = getattr(player, "evasion", 0)
|
||||
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05))
|
||||
rp = enemy.ranged_power
|
||||
if r.random() < hit_chance:
|
||||
player.hp -= rp
|
||||
if log is not None:
|
||||
log.append(f"{enemy.name} shoots you for {rp} damage!")
|
||||
elif log is not None:
|
||||
log.append(f"{enemy.name}'s shot misses you")
|
||||
def _ranged(
|
||||
enemy: Any,
|
||||
game_map: Any,
|
||||
player: Any,
|
||||
visible: set[tuple[int, int]],
|
||||
rng: random.Random,
|
||||
) -> None:
|
||||
px, py = player.x, player.y
|
||||
if (px, py) not in visible:
|
||||
_wander(enemy, game_map, rng)
|
||||
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)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Death resolution
|
||||
# --------------------------------------------------------------------------- #
|
||||
def on_death(enemy, session) -> None:
|
||||
"""Resolve an enemy's death: split, award XP, remove corpse, check victory.
|
||||
def _phase(
|
||||
enemy: Any,
|
||||
game_map: Any,
|
||||
player: Any,
|
||||
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
|
||||
corpse is removed. Slaying the dragon wins the run.
|
||||
|
||||
# ------------------------------------------------------------------- death hook
|
||||
|
||||
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
|
||||
floor = session.dungeon[session.current_floor]
|
||||
|
||||
session.log.append(f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)")
|
||||
|
||||
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
|
||||
if not getattr(enemy, "can_split", False) or getattr(enemy, "hp", 1) > 0:
|
||||
return []
|
||||
spawned: list[Enemy] = []
|
||||
for dx, dy in ((1, 0), (-1, 0)):
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if not is_walkable(floor, nx, ny):
|
||||
continue
|
||||
if _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
floor.entities.append(Enemy(
|
||||
x=nx, y=ny, name="Small Slime", sprite_key="small_slime",
|
||||
hp=half_hp, max_hp=half_hp, power=half_pow, armor=enemy.armor,
|
||||
accuracy=enemy.accuracy, evasion=enemy.evasion,
|
||||
crit_chance=enemy.crit_chance, speed=1,
|
||||
behavior="split", xp_value=max(1, enemy.xp_value // 2),
|
||||
if game_map.in_bounds(nx, ny) and game_map.walkable(nx, ny):
|
||||
spawned.append(_small_copy(enemy, nx, ny))
|
||||
return spawned
|
||||
|
||||
|
||||
def _small_copy(parent: Any, x: int, y: int) -> Enemy:
|
||||
half_hp = max(1, int(parent.max_hp) // 2)
|
||||
return Enemy(
|
||||
x=x, y=y,
|
||||
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,
|
||||
))
|
||||
spawned += 1
|
||||
if spawned:
|
||||
session.log.append(f"The {enemy.name} splits into {spawned} smaller slimes!")
|
||||
sprite_key="small_slime",
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 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")
|
||||
@@ -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
|
||||
===================================================================
|
||||
@@ -1,133 +1,126 @@
|
||||
"""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
|
||||
|
||||
# --- Grid / viewport -------------------------------------------------------- #
|
||||
TILE: int = 24
|
||||
MAP_WIDTH: int = 80
|
||||
MAP_HEIGHT: int = 50
|
||||
# --- viewport / grid -------------------------------------------------------
|
||||
TILE: int = 20
|
||||
MAP_W: int = 80
|
||||
MAP_H: int = 50
|
||||
SIGHT_RADIUS: int = 8
|
||||
FLOORS: int = 10
|
||||
MAX_LEVEL: int = 10
|
||||
FLOOR_COUNT: int = 10
|
||||
|
||||
# --- Base palette / colors -------------------------------------------------- #
|
||||
# Tiles
|
||||
COLORS: dict[str, tuple[int, int, int]] = {
|
||||
"wall_visible": (60, 60, 70),
|
||||
"wall_explored": (30, 30, 35),
|
||||
"floor_visible": (40, 35, 30),
|
||||
"floor_explored": (20, 18, 15),
|
||||
"void": (6, 5, 8),
|
||||
# entity accent hues (dominant sprite color per type)
|
||||
"player": (225, 225, 235),
|
||||
"rat": (150, 110, 75),
|
||||
"goblin": (95, 165, 75),
|
||||
"skeleton_archer": (215, 215, 205),
|
||||
"orc_warrior": (155, 55, 50),
|
||||
"wraith": (160, 95, 205),
|
||||
"green_slime": (125, 205, 85),
|
||||
"ancient_dragon": (205, 65, 50),
|
||||
# feature / item accents
|
||||
"stairs": (240, 220, 80),
|
||||
"weapon": (240, 220, 80), # yellow
|
||||
"armor": (95, 145, 230), # blue
|
||||
"potion": (220, 85, 85), # red
|
||||
"scroll": (95, 220, 220), # cyan
|
||||
# UI
|
||||
"ui_border": (150, 130, 95),
|
||||
"ui_border_hi": (200, 180, 130),
|
||||
"ui_bg": (15, 12, 18),
|
||||
"ui_panel": (24, 20, 28),
|
||||
"hp_full": (190, 55, 60),
|
||||
"hp_back": (60, 22, 24),
|
||||
"xp_full": (90, 170, 230),
|
||||
"xp_back": (26, 34, 48),
|
||||
"log_combat": (235, 235, 235),
|
||||
"log_damage": (225, 90, 90),
|
||||
"log_levelup": (130, 225, 100),
|
||||
"log_item": (240, 220, 90),
|
||||
"log_miss": (170, 170, 170),
|
||||
"prompt": (245, 235, 180),
|
||||
# --- dungeon generation ----------------------------------------------------
|
||||
ROOM_MIN_W: int = 4
|
||||
ROOM_MIN_H: int = 4
|
||||
ROOM_MAX_W: int = 10
|
||||
ROOM_MAX_H: int = 8
|
||||
BSP_MIN_HALF: int = 12 # min half-axis before a region may split
|
||||
BSP_LEAVES_MIN: int = 6
|
||||
BSP_LEAVES_MAX: int = 10
|
||||
BOSS_ROOM_W: int = 20
|
||||
BOSS_ROOM_H: int = 15
|
||||
WALL: int = 0
|
||||
FLOOR: int = 1
|
||||
|
||||
# --- player base stats (plan.md Core Data Model) ---------------------------
|
||||
PLAYER_BASE: dict = {
|
||||
"hp": 50,
|
||||
"max_hp": 50,
|
||||
"power": 4,
|
||||
"armor": 0,
|
||||
"accuracy": 5,
|
||||
"evasion": 2,
|
||||
"crit_chance": 0.10,
|
||||
"speed": 1,
|
||||
}
|
||||
|
||||
# --- leveling: (cumulative_xp_to_next_level, hp_gain, power_gain) ----------
|
||||
LEVEL_TABLE: list[tuple[int, int, int]] = [
|
||||
(30, 10, 1),
|
||||
(70, 10, 1),
|
||||
(140, 10, 1),
|
||||
(250, 10, 1),
|
||||
(400, 15, 2),
|
||||
(600, 15, 2),
|
||||
(850, 15, 2),
|
||||
(1150, 15, 2),
|
||||
(1500, 20, 3),
|
||||
]
|
||||
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),
|
||||
"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.
|
||||
# "." is transparent. Keys are intentionally short; phase 4 sprites use them.
|
||||
PALETTE: dict[str, tuple[int, int, int] | None] = {
|
||||
# --- single-char palette keys for procedural pixel-art grids (render layer) -
|
||||
PALETTE: dict = {
|
||||
".": None, # transparent
|
||||
"K": (18, 14, 20), # dark outline
|
||||
"k": (40, 32, 38), # soft outline
|
||||
"W": (95, 85, 72), # warm light shade (stone/skin highlight)
|
||||
"s": (62, 56, 50), # mid shade (stone/skin)
|
||||
"h": (38, 33, 30), # dark shade (stone/skin shadow)
|
||||
"d": (24, 20, 18), # deep shadow
|
||||
"w": (245, 245, 250), # white (bone / sclera)
|
||||
"g": (120, 200, 80), # green (goblin / slime)
|
||||
"G": (70, 150, 55), # dark green
|
||||
"r": (200, 60, 50), # red (orc / dragon)
|
||||
"R": (140, 35, 30), # dark red
|
||||
"p": (160, 95, 205), # purple (wraith)
|
||||
"P": (95, 55, 140), # dark purple
|
||||
"b": (95, 145, 230), # blue (armor / magic)
|
||||
"y": (240, 220, 80), # yellow (stairs / weapon / gold)
|
||||
"o": (225, 150, 60), # orange (fire / accents)
|
||||
"c": (95, 220, 220), # cyan (scroll)
|
||||
"m": (220, 85, 85), # muted red (potion)
|
||||
"e": (90, 230, 120), # eye glow green
|
||||
"E": (120, 200, 255), # eye glow blue
|
||||
" ": None,
|
||||
"K": (16, 14, 20), # darkest outline
|
||||
"k": (40, 36, 46), # outline shade
|
||||
"W": (60, 60, 70), # wall base
|
||||
"w": (82, 82, 96), # wall highlight (top edge)
|
||||
"e": (30, 30, 35), # explored wall
|
||||
"F": (40, 35, 30), # floor base
|
||||
"f": (54, 48, 41), # floor fleck
|
||||
"E": (20, 18, 15), # explored floor
|
||||
"s": (245, 215, 70), # stairs / yellow glow
|
||||
"y": (240, 200, 80), # yellow accent (weapons)
|
||||
"b": (90, 140, 220), # blue accent (armor)
|
||||
"r": (200, 60, 50), # red accent (dragon / potions)
|
||||
"g": (90, 200, 90), # green accent (goblin / slime)
|
||||
"p": (150, 90, 200), # purple accent (wraith)
|
||||
"c": (210, 210, 200), # bone white (skeleton)
|
||||
"C": (90, 220, 220), # cyan accent (scrolls)
|
||||
"G": (172, 178, 190), # steel (weapon blades)
|
||||
"o": (140, 100, 70), # brown (rat)
|
||||
"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) ----------------------- #
|
||||
# Cumulative XP required to REACH a given level (keyed by level 1..10).
|
||||
XP_THRESHOLDS: dict[int, int] = {
|
||||
1: 0, 2: 30, 3: 70, 4: 140, 5: 250,
|
||||
6: 400, 7: 600, 8: 850, 9: 1150, 10: 1500,
|
||||
}
|
||||
# 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}
|
||||
# --- combat tuning (plan.md Systems) ---------------------------------------
|
||||
HIT_BASE: float = 0.70
|
||||
HIT_PER_POINT: float = 0.05
|
||||
HIT_FLOOR: float = 0.10
|
||||
HIT_CEIL: float = 0.95
|
||||
|
||||
# --- Player base stats (plan.md §7) ---------------------------------------- #
|
||||
PLAYER_BASE: dict[str, int | float] = {
|
||||
"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"],
|
||||
}
|
||||
# --- persistence ----------------------------------------------------------------
|
||||
SAVE_FILE: str = "save.json"
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
(data/constants.PALETTE: "." transparent). Grids are drawn with small canvas
|
||||
primitives (rect, disc, triangle, line) so the art is symmetric and
|
||||
recognizable rather than hand-counted ASCII. render/sprites.py rasterizes a
|
||||
grid to a pygame.Surface once and caches it.
|
||||
|
||||
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.
|
||||
``render/sprites.get_sprite`` rasterizes a grid to a cached Surface, mapping each
|
||||
char to a color from ``data.constants.PALETTE``. ``.``/space = transparent. The
|
||||
marker char ``a`` is an item accent replaced at raster time by a per-kind tint
|
||||
(``TINTS``), so one category shape recolors into distinct items. Rows may be
|
||||
ragged; the rasterizer pads short rows with transparency.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
SIZE: int = 16
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Canvas primitives — operate on a mutable list[list[str]] grid of SIZE rows.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _blank() -> list[list[str]]:
|
||||
return [["." for _ in range(SIZE)] for _ in range(SIZE)]
|
||||
|
||||
|
||||
def _set(g: list[list[str]], x: int, y: int, k: str) -> None:
|
||||
if 0 <= x < SIZE and 0 <= y < SIZE:
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _rect(g, x0, y0, x1, y1, k) -> None:
|
||||
for y in range(max(0, y0), min(SIZE - 1, y1) + 1):
|
||||
for x in range(max(0, x0), min(SIZE - 1, x1) + 1):
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _frame(g, x0, y0, x1, y1, k) -> None:
|
||||
for x in range(x0, x1 + 1):
|
||||
_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)
|
||||
|
||||
|
||||
def _disc(g, cx, cy, rx, ry, k) -> None:
|
||||
rx = max(0.1, rx)
|
||||
ry = max(0.1, ry)
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
dx = (x - cx) / rx
|
||||
dy = (y - cy) / ry
|
||||
if dx * dx + dy * dy <= 1.0:
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _hline(g, x0, x1, y, k) -> None:
|
||||
for x in range(min(x0, x1), max(x0, x1) + 1):
|
||||
_set(g, x, y, k)
|
||||
|
||||
|
||||
def _vline(g, x, y0, y1, k) -> None:
|
||||
for y in range(min(y0, y1), max(y0, y1) + 1):
|
||||
_set(g, x, y, k)
|
||||
|
||||
|
||||
def _line(g, x0, y0, x1, y1, k) -> None:
|
||||
dx = abs(x1 - x0)
|
||||
dy = -abs(y1 - y0)
|
||||
sx = 1 if x0 < x1 else -1
|
||||
sy = 1 if y0 < y1 else -1
|
||||
err = dx + dy
|
||||
while True:
|
||||
_set(g, x0, y0, k)
|
||||
if x0 == x1 and y0 == y1:
|
||||
break
|
||||
e2 = 2 * err
|
||||
if e2 >= dy:
|
||||
err += dy
|
||||
x0 += sx
|
||||
if e2 <= dx:
|
||||
err += dx
|
||||
y0 += sy
|
||||
|
||||
|
||||
def _tri(g, ax, ay, bx, by, cx, cy, k) -> None:
|
||||
ymin = max(0, int(min(ay, by, cy)))
|
||||
ymax = min(SIZE - 1, int(max(ay, by, cy)))
|
||||
for y in range(ymin, ymax + 1):
|
||||
xs = []
|
||||
for (x0, y0, x1, y1) in ((ax, ay, bx, by), (bx, by, cx, cy), (cx, cy, ax, ay)):
|
||||
if y0 == y1:
|
||||
if y0 == y:
|
||||
xs.extend([x0, x1])
|
||||
continue
|
||||
t = (y - y0) / (y1 - y0)
|
||||
xs.append(x0 + t * (x1 - x0))
|
||||
if len(xs) >= 2:
|
||||
_hline(g, int(round(min(xs))), int(round(max(xs))), y, k)
|
||||
|
||||
|
||||
def _flip(g) -> list[list[str]]:
|
||||
return [row[::-1] for row in g]
|
||||
|
||||
|
||||
def _shift(g, dy: int) -> list[list[str]]:
|
||||
out = _blank()
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
ny = y + dy
|
||||
if 0 <= ny < SIZE:
|
||||
out[ny][x] = g[y][x]
|
||||
return out
|
||||
|
||||
|
||||
def _outline(g) -> list[list[str]]:
|
||||
"""1px dark 'K' border around the silhouette (keeps sprites off the floor)."""
|
||||
out = [row[:] for row in g]
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
if g[y][x] != ".":
|
||||
continue
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
||||
nx, ny = x + dx, y + dy
|
||||
if 0 <= nx < SIZE and 0 <= ny < SIZE and g[ny][nx] != ".":
|
||||
out[y][x] = "K"
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _rows(g) -> list[str]:
|
||||
return ["".join(row) for row in g]
|
||||
|
||||
|
||||
def _eframes(g) -> list[list[str]]:
|
||||
"""2 idle frames: base + 1px bob, both outlined."""
|
||||
ob = _outline(g)
|
||||
return [_rows(ob), _rows(_shift(ob, 1))]
|
||||
|
||||
|
||||
def _iframe(g) -> list[list[str]]:
|
||||
return [_rows(_outline(g))]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Player — hooded adventurer, 4 facings. Weapon/armor visibly change via the
|
||||
# renderer (held-weapon icon + armor shoulder tint), not extra grids.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _player_down():
|
||||
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
|
||||
_set(g, 4, 6, "w"); _set(g, 11, 6, "w") # shoulder highlights
|
||||
_rect(g, 5, 8, 10, 11, "W") # torso
|
||||
_hline(g, 5, 10, 11, "y") # belt
|
||||
_vline(g, 4, 8, 11, "W"); _vline(g, 11, 8, 11, "W") # arms
|
||||
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h") # legs
|
||||
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K") # boots
|
||||
return g
|
||||
|
||||
|
||||
def _player_up():
|
||||
g = _player_down()
|
||||
_rect(g, 6, 3, 9, 5, "W") # back of hood: no face/eyes
|
||||
_hline(g, 6, 9, 5, "k")
|
||||
return g
|
||||
|
||||
|
||||
def _player_right():
|
||||
g = _blank()
|
||||
_rect(g, 5, 1, 9, 1, "W")
|
||||
_rect(g, 5, 2, 11, 5, "W") # hood, extending right (point)
|
||||
_set(g, 12, 4, "W")
|
||||
_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")
|
||||
_rect(g, 5, 8, 10, 11, "W")
|
||||
_hline(g, 5, 10, 11, "y")
|
||||
_vline(g, 4, 8, 11, "W")
|
||||
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h")
|
||||
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K")
|
||||
return g
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Enemies — each a distinct silhouette + dominant hue.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _rat():
|
||||
g = _blank()
|
||||
_disc(g, 5, 5, 1.5, 1.5, "W"); _disc(g, 9, 5, 1.5, 1.5, "W") # ears
|
||||
_set(g, 5, 5, "o"); _set(g, 9, 5, "o") # inner ear
|
||||
_disc(g, 10, 8, 2.3, 2.0, "s") # head
|
||||
_disc(g, 6, 9, 3.8, 2.7, "s") # body
|
||||
_disc(g, 6, 8, 3.0, 1.5, "W") # back highlight
|
||||
_set(g, 11, 8, "K") # eye
|
||||
_set(g, 12, 9, "o") # nose
|
||||
_set(g, 13, 8, "w"); _set(g, 13, 9, "w") # whiskers
|
||||
_line(g, 3, 10, 0, 13, "o") # tail
|
||||
_set(g, 5, 12, "h"); _set(g, 8, 12, "h") # feet
|
||||
return g
|
||||
|
||||
|
||||
def _goblin():
|
||||
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
|
||||
_set(g, 7, 8, "w"); _set(g, 9, 8, "w") # tusks
|
||||
_rect(g, 6, 9, 10, 12, "g") # torso
|
||||
_rect(g, 6, 9, 10, 9, "G") # shoulder shade
|
||||
_hline(g, 6, 10, 12, "y") # loincloth
|
||||
_vline(g, 5, 9, 12, "g"); _vline(g, 10, 9, 12, "g") # arms
|
||||
_vline(g, 12, 6, 12, "W"); _set(g, 12, 5, "K") # crude club
|
||||
_rect(g, 6, 13, 7, 14, "G"); _rect(g, 9, 13, 10, 14, "G")
|
||||
return g
|
||||
|
||||
|
||||
def _skeleton_archer():
|
||||
g = _blank()
|
||||
# big drawn bow on the left (clear arc + taut string)
|
||||
_vline(g, 2, 4, 12, "w") # bow back
|
||||
_set(g, 1, 5, "w"); _set(g, 1, 6, "w")
|
||||
_set(g, 1, 10, "w"); _set(g, 1, 11, "w") # recurve curve
|
||||
_line(g, 2, 4, 9, 8, "K") # bowstring pulled to the hand
|
||||
_line(g, 2, 12, 9, 8, "K")
|
||||
_hline(g, 3, 7, 8, "w") # draw arm
|
||||
_disc(g, 9, 4, 2.0, 2.0, "w") # skull
|
||||
_set(g, 8, 4, "E"); _set(g, 10, 4, "E") # glowing sockets
|
||||
_hline(g, 8, 10, 6, "w"); _set(g, 8, 6, "K"); _set(g, 10, 6, "K")
|
||||
_rect(g, 8, 7, 10, 11, "w") # ribcage
|
||||
_hline(g, 8, 10, 8, "K"); _hline(g, 8, 10, 10, "K")
|
||||
_vline(g, 9, 7, 11, "K") # spine
|
||||
_vline(g, 12, 5, 11, "b"); _set(g, 12, 4, "y"); _set(g, 12, 5, "y") # quiver
|
||||
_vline(g, 8, 12, 14, "w"); _vline(g, 10, 12, 14, "w") # legs
|
||||
return g
|
||||
|
||||
|
||||
def _orc_warrior():
|
||||
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")
|
||||
_rect(g, 4, 8, 12, 9, "R") # shoulder plate
|
||||
_set(g, 4, 8, "r"); _set(g, 12, 8, "r")
|
||||
_rect(g, 5, 9, 11, 13, "r") # torso
|
||||
_rect(g, 5, 9, 11, 9, "R")
|
||||
_hline(g, 5, 12, 11, "K") # belt
|
||||
_line(g, 13, 13, 13, 4, "w") # great blade
|
||||
_line(g, 12, 13, 12, 4, "K") # edge
|
||||
_set(g, 13, 13, "y") # pommel
|
||||
_rect(g, 6, 13, 7, 14, "R"); _rect(g, 9, 13, 10, 14, "R")
|
||||
return g
|
||||
|
||||
|
||||
def _wraith():
|
||||
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
|
||||
_rect(g, 5, 9, 11, 12, "P") # cloak
|
||||
# tattered hem (no legs)
|
||||
_set(g, 5, 13, "p"); _set(g, 7, 13, "P"); _set(g, 9, 13, "p"); _set(g, 11, 13, "P")
|
||||
_set(g, 6, 14, "p"); _set(g, 10, 14, "p")
|
||||
_set(g, 4, 10, "P"); _set(g, 12, 10, "P") # wisps
|
||||
return g
|
||||
|
||||
|
||||
def _slime():
|
||||
g = _blank()
|
||||
for y in range(6, 13):
|
||||
for x in range(3, 13):
|
||||
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
|
||||
_set(g, 6, 10, "K"); _set(g, 10, 10, "K")
|
||||
_set(g, 8, 13, "g"); _set(g, 8, 14, "g") # drip
|
||||
return g
|
||||
|
||||
|
||||
def _small_slime():
|
||||
g = _blank()
|
||||
for y in range(7, 14):
|
||||
for x in range(4, 12):
|
||||
dx = (x - 8) / 3.8
|
||||
dy = (y - 10) / 3.4
|
||||
if dx * dx + dy * dy <= 1.0:
|
||||
g[y][x] = "g"
|
||||
_hline(g, 4, 11, 13, "G") # base
|
||||
_set(g, 6, 8, "w"); _set(g, 7, 9, "w") # gloss
|
||||
_disc(g, 6, 10, 1.1, 1.2, "w"); _disc(g, 10, 10, 1.1, 1.2, "w") # big eyes
|
||||
_set(g, 6, 10, "K"); _set(g, 10, 10, "K")
|
||||
_set(g, 8, 13, "g") # drip
|
||||
_hline(g, 7, 9, 12, "G") # smile
|
||||
return g
|
||||
|
||||
|
||||
def _dragon():
|
||||
g = _blank()
|
||||
# spread wings (membrane triangles)
|
||||
_tri(g, 6, 7, 0, 4, 1, 10, "R")
|
||||
_tri(g, 6, 7, 0, 4, 1, 10, "R")
|
||||
_tri(g, 10, 7, 15, 4, 14, 10, "R")
|
||||
_tri(g, 10, 7, 15, 4, 14, 10, "R")
|
||||
_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)}")
|
||||
# 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
|
||||
# H = blood/damage a = item accent (tinted per kind)
|
||||
|
||||
GRIDS: dict[str, list[str]] = {
|
||||
|
||||
# ---- stairs: glowing yellow descending staircase (3 steps down-right) ----
|
||||
"stairs": [
|
||||
"..............",
|
||||
".KKKKKK.......",
|
||||
".KyyyyyK......",
|
||||
".KsssssK......",
|
||||
".KKKKKKK......",
|
||||
"....KKKKKK....",
|
||||
"....KyyyyyK...",
|
||||
"....KsssssK...",
|
||||
"....KKKKKKK...",
|
||||
".......KKKKKK.",
|
||||
".......KyyyyyK",
|
||||
".......KsssssK",
|
||||
".......KKKKKKK",
|
||||
"..............",
|
||||
"..............",
|
||||
],
|
||||
|
||||
# ---- player: hooded adventurer, blue cloak, steel highlight ----
|
||||
"player": [
|
||||
"....KKKK....",
|
||||
"...KhKKhk...",
|
||||
"..KhhhhhhK..",
|
||||
"..KhccccKh..",
|
||||
"..KhhhhhhK..",
|
||||
".KbbbbbbbbK.",
|
||||
".KbhbbbbhbK.",
|
||||
".KbbbbbbbbK.",
|
||||
".KbbbbbbbbK.",
|
||||
".KbbKKKKbbK.",
|
||||
".KbK....KbK.",
|
||||
".KK......KK.",
|
||||
"............",
|
||||
"............",
|
||||
],
|
||||
|
||||
# ---- rat: small brown body, ears, pink tail ----
|
||||
"rat": [
|
||||
"..............",
|
||||
"...KK....KK...",
|
||||
"...KoK..KoK...",
|
||||
"..KooooooK....",
|
||||
".KooooooooK.KK",
|
||||
".KoohhooooKKK.",
|
||||
".KooooooooK...",
|
||||
".KooooooooK...",
|
||||
"..KooooooK....",
|
||||
"...KooooK.....",
|
||||
"....KhhK......",
|
||||
"....K..K...oo.",
|
||||
"...........oo.",
|
||||
"..............",
|
||||
],
|
||||
|
||||
# ---- goblin: green humanoid, pointed ears, crude blade ----
|
||||
"goblin": [
|
||||
"..............",
|
||||
"..K.K....K.K..",
|
||||
"..KgK....KgK..",
|
||||
".KggggggggggK.",
|
||||
".KgghhhhhggK..",
|
||||
".KggKrrKggK...", # eyes/mouth
|
||||
".KggggggggK...",
|
||||
".KgggggggggK..",
|
||||
".KgggKKKgggK..",
|
||||
".KggK...KggK..",
|
||||
".KgK.....KgK..",
|
||||
".KK.......KK..",
|
||||
".....yy.......", # crude blade
|
||||
".....yy.......",
|
||||
],
|
||||
|
||||
# ---- skeleton archer: thin bones, ribcage, drawn bow + quiver, glowing eyes ----
|
||||
"skeleton_archer": [
|
||||
"..............",
|
||||
".....KKKK.....",
|
||||
"....KccccK....",
|
||||
"....KqccqK....", # glowing eye sockets
|
||||
"....KccccK....",
|
||||
"....KchhcK....", # cheek bones
|
||||
".....KKKK.....", # teeth
|
||||
"y...KccccK..o.", # quiver fletch | shoulders | bow tip
|
||||
"yo..KcKKcK.o..", # ribs + bow limb
|
||||
"yo..KcKKcKo...", # bow belly (closest to body)
|
||||
"yo..KcKKcKo...",
|
||||
"yo..KcKKcK.o..",
|
||||
"yo..KcKKcK..o.", # bow tip
|
||||
"y...KcKKcK...o",
|
||||
"....KK..KK....", # pelvis
|
||||
"....Kc..cK....", # thin bony legs
|
||||
],
|
||||
|
||||
# ---- orc warrior: broad hulking brute, plate pauldrons, tusks, big blade ----
|
||||
"orc_warrior": [
|
||||
"..............",
|
||||
".....KKKK.....",
|
||||
"....KnnnnK....",
|
||||
"....KHnnHK....", # red eyes / heavy brow
|
||||
"....KnnnnK....",
|
||||
"...hKnnnnKh...", # jutting tusks
|
||||
"..KnnnnnnnnK..", # thick neck
|
||||
"KKnnnnnnnnnnKK", # massive plate shoulders
|
||||
"KnhhnnnnnnhhnK", # pauldron highlights
|
||||
"KnnnnnnnnnnnnK", # broad chest
|
||||
".KKnnnyynnnKK.", # fists + yellow crossguard
|
||||
"..KnGGGGGGnK..", # big steel blade
|
||||
"..KnhGGGGhnK..", # blade bright edge
|
||||
"...KKGGGKK....", # heavy blade tip
|
||||
"...KKK..KKK...", # legs
|
||||
"...KK....KK...", # feet
|
||||
],
|
||||
|
||||
# ---- wraith: translucent purple wisps, tattered cloak, no legs ----
|
||||
"wraith": [
|
||||
"..............",
|
||||
".....KKKK.....",
|
||||
"....KppppK....",
|
||||
"...KppppppK...",
|
||||
"...KpHHppK....", # glowing eyes
|
||||
"...KpppppK....",
|
||||
"..KpppppppK...",
|
||||
".KpppppppppK..",
|
||||
".KpKpKpKpKpK..", # tattered hem
|
||||
"KpK.pK.pK.pK..",
|
||||
"p.p..p...p..p.",
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
],
|
||||
|
||||
# ---- green slime: big glossy domed blob, highlight, googly eyes, drip ----
|
||||
"green_slime": [
|
||||
"..............",
|
||||
"...KKKKKKKK...",
|
||||
"..KggggggggK..",
|
||||
".KgghhhhgggK..", # glossy top-left highlight
|
||||
".KghhKKhhggK..", # sheen
|
||||
"KgggggggggggK.",
|
||||
"KgghKggKhgggK.", # two googly eyes
|
||||
"KgggggggggggK.",
|
||||
"KgggggggggggK.",
|
||||
".KgggggggggK..",
|
||||
".KgggggggggK..",
|
||||
"..KKKKKKKKKK..", # flat bottom (squished on ground)
|
||||
".....g........", # drip
|
||||
"....gg........",
|
||||
".....g........",
|
||||
"..............",
|
||||
],
|
||||
|
||||
# ---- small slime: smaller cuter variant ----
|
||||
"small_slime": [
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
"....KKKKKK....",
|
||||
"...KggggggK...",
|
||||
"..KggHHggggK..",
|
||||
"..KgghhggggK..",
|
||||
"..KggggggggK..",
|
||||
"..KggggggggK..",
|
||||
"...KKKKKKKK...",
|
||||
".....g........",
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
],
|
||||
|
||||
# ---- ancient dragon: large red boss, horns, wings, fangs ----
|
||||
"ancient_dragon": [
|
||||
"K............K",
|
||||
"KK..........KK",
|
||||
".KrK......KrK.", # wing tips
|
||||
"KrrrK....KrrrK",
|
||||
"KrrrrKKKKrrrrK",
|
||||
".KrrrrrrrrrrK.", # horns sweep
|
||||
"..KHHrrrrHHK..", # eyes
|
||||
"..KrrrrrrrrK...",
|
||||
"..KrKnnnrKrK...", # fanged maw
|
||||
".KrrrrrrrrrrK..",
|
||||
"KrrKrrrrrrKrrK.",
|
||||
"KrK..KrrK..KrK.",
|
||||
"K.....KK.....K.",
|
||||
"..............",
|
||||
],
|
||||
}
|
||||
|
||||
# ---- item category base shapes; the 'a' marker is tinted per kind (TINTS) ----
|
||||
GRIDS["_weapon"] = [
|
||||
"......Kh......", # pointed tip
|
||||
".....KhaK.....", # blade (a = per-kind tint) w/ bright edge (h)
|
||||
".....Khaa.....",
|
||||
"....Khaaa.....",
|
||||
"....KhaaK.....",
|
||||
"...Khaaaa.....",
|
||||
"...KhaaaK.....",
|
||||
"..Khaaaaa.....",
|
||||
"..KhaaaaK.....",
|
||||
".Khaaaaaa.....",
|
||||
".KhaaaaaK.....",
|
||||
"KKyyyyyyyyyKK.", # wide yellow crossguard
|
||||
"...KaaaaK.....", # grip
|
||||
"...KaaaaK.....",
|
||||
"...KaaaaK.....",
|
||||
"....KyyK......", # pommel
|
||||
]
|
||||
GRIDS["_armor"] = [
|
||||
"...KKKKKKKK...", # shield top
|
||||
"..KaaaaaaaaK..",
|
||||
".KaahhaaaaaaK.", # top-left highlight
|
||||
".KaahbhaaaaaK.", # blue boss
|
||||
"KaaabbbaaaaaK.", # blue cross (steel rim accents)
|
||||
"KaaabbbaaaaaK.",
|
||||
"KaaaabbbaaaK..",
|
||||
"KaaaaaaaaaK...",
|
||||
".KaaaaaaK.....",
|
||||
"..KaaaaK......",
|
||||
"...KaaK.......",
|
||||
"....KK........", # point
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
]
|
||||
GRIDS["_potion"] = [
|
||||
".....KKKK.....", # neck
|
||||
"....KooooK....", # cork
|
||||
"....KKKKKK....", # shoulder
|
||||
"..KKaaaaaaKK..",
|
||||
".KaaaaaaaaaaK.",
|
||||
".KaahaaaaaaaK.", # glass highlight
|
||||
"KaaaaaaaaaaaK.", # round bulb (a = per-kind liquid)
|
||||
"KaaaaaaaaaaaK.",
|
||||
"KaaaaaaaaaaaK.",
|
||||
"KaaaaaaaaaaaK.",
|
||||
".KaaaaaaaaaK..",
|
||||
".KaaaaaaaaaK..",
|
||||
"..KKaaaaaKK...", # base
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
]
|
||||
GRIDS["_scroll"] = [
|
||||
"..............",
|
||||
".KhC......ChK.", # rolled end caps (top)
|
||||
"KhCk......kChK", # cylindrical rolls: bright rim (h) + dark core (k)
|
||||
"KhCkCCCCCCkChK", # flat paper between the rolls
|
||||
"KhCkChCCCCkChK", # ruled line
|
||||
"KhCkaaaaaakChK", # ribbon tie (a = per-kind tint)
|
||||
"KhCkaaaaaakChK",
|
||||
"KhCkCCChCCkChK", # ruled line
|
||||
"KhCkCCCCCCkChK",
|
||||
"KhCkCCCCCCkChK",
|
||||
"KhCk......kChK", # rolls
|
||||
".KhC......ChK.", # rolled end caps (bottom)
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
"..............",
|
||||
]
|
||||
|
||||
# Point every item kind at its category base shape (shared list, read-only).
|
||||
_WEAPON_KINDS = ("rusty_dagger", "short_sword", "battle_axe", "war_hammer")
|
||||
_ARMOR_KINDS = ("leather_armor", "chain_mail", "plate_armor")
|
||||
_POTION_KINDS = ("healing_potion", "strength_potion", "invisibility_potion")
|
||||
_SCROLL_KINDS = ("fireball_scroll", "teleport_scroll", "mapping_scroll")
|
||||
for _k in _WEAPON_KINDS:
|
||||
GRIDS[_k] = GRIDS["_weapon"]
|
||||
for _k in _ARMOR_KINDS:
|
||||
GRIDS[_k] = GRIDS["_armor"]
|
||||
for _k in _POTION_KINDS:
|
||||
GRIDS[_k] = GRIDS["_potion"]
|
||||
for _k in _SCROLL_KINDS:
|
||||
GRIDS[_k] = GRIDS["_scroll"]
|
||||
|
||||
# Per-kind accent tint applied to the 'a' marker (category hue + per-kind flavor).
|
||||
TINTS: dict[str, tuple[int, int, int]] = {
|
||||
"rusty_dagger": (170, 130, 80),
|
||||
"short_sword": (210, 215, 225),
|
||||
"battle_axe": (150, 155, 165),
|
||||
"war_hammer": (120, 115, 130),
|
||||
"leather_armor": (150, 110, 60),
|
||||
"chain_armor": (120, 130, 145),
|
||||
"chain_mail": (120, 130, 145),
|
||||
"plate_armor": (170, 175, 190),
|
||||
"healing_potion": (220, 80, 80),
|
||||
"strength_potion": (230, 150, 60),
|
||||
"invisibility_potion": (200, 160, 220),
|
||||
"fireball_scroll": (240, 150, 60),
|
||||
"teleport_scroll": (150, 120, 220),
|
||||
"mapping_scroll": (90, 220, 220),
|
||||
}
|
||||
@@ -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,
|
||||
runs enemy AI, recomputes FOV, ticks effect timers, and checks for death.
|
||||
`pickup` / `descend` / `use_item` / `equip` are resolution actions; they log and
|
||||
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).
|
||||
``apply_input(session, key)`` is the only entry point the game loop calls. It
|
||||
never raises on valid game state; every combat event, pickup, level-up and
|
||||
status change logs a human-readable message (the log is the feedback channel).
|
||||
|
||||
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 data import constants as C
|
||||
from ai.behaviors import on_death, take_enemy_turn
|
||||
from engine.combat import attack
|
||||
from engine import game_state
|
||||
from engine.game_state import recompute_fov
|
||||
from engine.map_gen import is_walkable
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Effect
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from engine.combat import roll_attack
|
||||
from engine.fov import compute_fov
|
||||
from engine.serializers import session_to_dict
|
||||
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),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Movement / melee
|
||||
# --------------------------------------------------------------------------- #
|
||||
def try_move(session, dx: int, dy: int) -> bool:
|
||||
"""Move the player by (dx, dy) or melee an enemy there. Returns whether the
|
||||
player acted (and thus a turn elapsed)."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
nx, ny = player.x + dx, player.y + dy
|
||||
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
return False
|
||||
if dx or dy:
|
||||
player.facing = _facing(dx, dy)
|
||||
|
||||
target = _enemy_at(floor, nx, ny)
|
||||
if target is not None:
|
||||
res = attack(player, target, rng=session.rng, log=session.log)
|
||||
if res["killed"]:
|
||||
on_death(target, session)
|
||||
# --------------------------------------------------------------------- dispatch
|
||||
def apply_input(session: Any, key: str) -> None:
|
||||
"""Apply one logical input to ``session``. Unknown keys are ignored."""
|
||||
if not isinstance(key, str):
|
||||
return
|
||||
if key in _DIRS:
|
||||
dx, dy = _DIRS[key]
|
||||
_move(session, dx, dy)
|
||||
return
|
||||
if key == "g":
|
||||
_pickup(session)
|
||||
elif key == "f":
|
||||
_descend(session)
|
||||
elif key == "q":
|
||||
_quaff(session)
|
||||
elif key == "r":
|
||||
_read(session)
|
||||
elif key == "e":
|
||||
_equip(session)
|
||||
elif key == "i":
|
||||
_inventory_info(session)
|
||||
elif key == "S":
|
||||
_save(session)
|
||||
elif key == "wait":
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
if floor.tiles[ny][nx] == 1 and not _blocked_at(floor, nx, ny):
|
||||
player.x, player.y = nx, ny
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
return False
|
||||
elif key in ("?", "m", "escape"):
|
||||
# Overlays / mute live in the presentation layer (main.py); safe no-op.
|
||||
return
|
||||
|
||||
|
||||
def _end_turn(session) -> None:
|
||||
"""One turn elapsed: counter up, FOV, enemy turns, effect timers, death."""
|
||||
session.turn += 1
|
||||
recompute_fov(session)
|
||||
_enemy_turns(session)
|
||||
# --------------------------------------------------------------------- queries
|
||||
def item_under_player(session: Any) -> Any:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
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)
|
||||
if session.player.hp <= 0 and session.state == "playing":
|
||||
game_state.mark_dead(session)
|
||||
session.log.append("You have died.")
|
||||
session.turn += 1
|
||||
|
||||
|
||||
def _enemy_turns(session) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Enemy) and e.hp > 0:
|
||||
take_enemy_turn(e, session, rng=session.rng)
|
||||
if session.player.hp <= 0:
|
||||
def _advance_enemies(session: Any, visible: set[tuple[int, int]]) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
vis = visible
|
||||
if p.effect_timers.get("invisibility", 0) > 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
|
||||
|
||||
|
||||
def _tick_effects(session) -> None:
|
||||
player = session.player
|
||||
if not player.effects:
|
||||
p = session.player
|
||||
gm = session.dungeon[session.current_floor]
|
||||
tx, ty = p.x + dx, p.y + dy
|
||||
enemy = _enemy_at(gm, tx, ty)
|
||||
if enemy is not None:
|
||||
_player_attack(session, enemy)
|
||||
_end_turn(session)
|
||||
return
|
||||
remaining: list = []
|
||||
for eff in player.effects:
|
||||
eff.duration -= 1
|
||||
if eff.duration > 0:
|
||||
remaining.append(eff)
|
||||
elif eff.kind == "invisibility":
|
||||
player.invisible = False
|
||||
session.log.append("You fade back into view.")
|
||||
player.effects = remaining
|
||||
if gm.walkable(tx, ty):
|
||||
p.x, p.y = tx, ty
|
||||
_end_turn(session)
|
||||
return
|
||||
# Bumped a wall: no turn spent (standard roguelike convention).
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Pickup / descend
|
||||
# --------------------------------------------------------------------------- #
|
||||
def pickup(session) -> bool:
|
||||
"""Move the item under the player into inventory. False if nothing there."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Item) and e.x == player.x and e.y == player.y:
|
||||
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)
|
||||
def _player_attack(session: Any, enemy: Any) -> None:
|
||||
roll = roll_attack(session.player, enemy, random)
|
||||
name = getattr(enemy, "name", "enemy")
|
||||
if not roll.hit:
|
||||
_log(session, f"You miss the {name}.")
|
||||
return
|
||||
enemy.hp -= roll.damage
|
||||
if roll.crit:
|
||||
_log(session, f"Critical! You strike the {name} for {roll.damage} damage!")
|
||||
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:
|
||||
"""Place an equippable in its slot; the previous item returns to inventory."""
|
||||
player = session.player
|
||||
if item.item_type not in ("weapon", "armor"):
|
||||
session.log.append(f"You can't equip the {item.name}.")
|
||||
def _defeat_enemy(session: Any, enemy: Any) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
_log(session, f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)")
|
||||
levels = session.player.gain_xp(enemy.xp_value)
|
||||
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
|
||||
slot = item.item_type
|
||||
old = player.equipped.get(slot)
|
||||
player.equipped[slot] = item
|
||||
if item in player.inventory:
|
||||
player.inventory.remove(item)
|
||||
if old is not None:
|
||||
player.inventory.append(old)
|
||||
session.log.append(f"You unequip the {old.name}.")
|
||||
session.log.append(f"You equip the {item.name}.")
|
||||
item = item_under_player(session)
|
||||
if item is None:
|
||||
_log(session, "There is nothing here to pick up.")
|
||||
return
|
||||
gm = session.dungeon[session.current_floor]
|
||||
gm.entities.remove(item)
|
||||
session.player.inventory.append(item)
|
||||
_log(session, f"You pick up the {item.name}.")
|
||||
_end_turn(session)
|
||||
|
||||
|
||||
def _use_potion(session, item) -> None:
|
||||
player = session.player
|
||||
if item.subtype == "healing":
|
||||
amount = item.stats.get("heal", 30)
|
||||
player.hp = min(player.max_hp, player.hp + amount)
|
||||
session.log.append(f"You quaff a Healing Potion and recover {amount} HP.")
|
||||
elif item.subtype == "strength":
|
||||
player.effects.append(Effect(
|
||||
kind="strength",
|
||||
power=item.stats.get("power", 5),
|
||||
duration=item.stats.get("duration", 20),
|
||||
))
|
||||
session.log.append("Your muscles surge! (+5 power for 20 turns)")
|
||||
elif item.subtype == "invisibility":
|
||||
player.effects.append(Effect(
|
||||
kind="invisibility",
|
||||
duration=item.stats.get("duration", 15),
|
||||
))
|
||||
player.invisible = True
|
||||
session.log.append("You fade from sight!")
|
||||
def _descend(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
gm = session.dungeon[session.current_floor]
|
||||
if gm.stairs_down is None or (p.x, p.y) != gm.stairs_down:
|
||||
_log(session, "Stand on the yellow > stairs, then press F to descend.")
|
||||
return
|
||||
session.current_floor += 1
|
||||
ngm = session.dungeon[session.current_floor]
|
||||
sp = ngm.spawn or (1, 1)
|
||||
p.x, p.y = sp
|
||||
_log(session, f"You descend to floor {session.current_floor + 1}.")
|
||||
_recompute_fov(session)
|
||||
session.turn += 1
|
||||
|
||||
|
||||
def _use_scroll(session, item) -> None:
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
if item.subtype == "fireball":
|
||||
radius = item.stats.get("radius", 3)
|
||||
dmg = item.stats.get("damage", 20)
|
||||
hit = [e for e in floor.entities
|
||||
if isinstance(e, Enemy)
|
||||
and max(abs(e.x - player.x), abs(e.y - player.y)) <= radius]
|
||||
for e in hit:
|
||||
def _quaff(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
potion = next((it for it in p.inventory if getattr(it, "category", "") == "potion"), None)
|
||||
if potion is None:
|
||||
_log(session, "You have no potions to quaff.")
|
||||
return
|
||||
p.inventory.remove(potion)
|
||||
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
|
||||
session.log.append(f"The fireball erupts! {len(hit)} foe(s) burn for {dmg} damage.")
|
||||
for e in hit:
|
||||
_log(session, f"The {e.name} is caught in the blast. ({dmg} damage)")
|
||||
if e.hp <= 0:
|
||||
on_death(e, session)
|
||||
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!")
|
||||
_defeat_enemy(session, e)
|
||||
|
||||
|
||||
def _consume(session, item) -> None:
|
||||
if item in session.player.inventory:
|
||||
session.player.inventory.remove(item)
|
||||
def _teleport(session: Any) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
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)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _enemy_at(floor, x: int, y: int):
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return e
|
||||
def _equip(session: Any) -> None:
|
||||
p = session.player
|
||||
improved = False
|
||||
best_w = max((it for it in p.inventory if getattr(it, "category", "") == "weapon"),
|
||||
key=lambda it: it.stats.get("power", 0), default=None)
|
||||
cur_w = p.equipped_weapon.stats.get("power", 0) if p.equipped_weapon else -1
|
||||
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
|
||||
|
||||
|
||||
def _blocked_at(floor, x: int, y: int) -> bool:
|
||||
"""True if a blocking entity (enemy) occupies (x, y). Items never block."""
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return True
|
||||
return False
|
||||
def delete_save() -> None:
|
||||
try:
|
||||
os.remove(_save_path())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _facing(dx: int, dy: int) -> str:
|
||||
if dy < 0:
|
||||
return "up"
|
||||
if dy > 0:
|
||||
return "down"
|
||||
if dx < 0:
|
||||
return "left"
|
||||
if dx > 0:
|
||||
return "right"
|
||||
return "down"
|
||||
if __name__ == "__main__":
|
||||
# Self-check: pickup + descent work on a fresh session.
|
||||
from engine.game_state import new_session
|
||||
s = new_session(seed=1)
|
||||
gm = s.dungeon[0]
|
||||
from data import items as I
|
||||
px, py = s.player.x, s.player.y
|
||||
gm.entities.append(I.make_item("healing_potion", px, py))
|
||||
n0 = len(s.player.inventory)
|
||||
apply_input(s, "g")
|
||||
assert len(s.player.inventory) == n0 + 1, "pickup failed"
|
||||
s.player.x, s.player.y = gm.stairs_down
|
||||
f0 = s.current_floor
|
||||
apply_input(s, "f")
|
||||
assert s.current_floor == f0 + 1, "descent failed"
|
||||
print("actions self-check: OK")
|
||||
@@ -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
|
||||
asset files. The mixer is initialized once, lazily and defensively: if the audio
|
||||
driver is missing, `mixer.init` fails, or `Sound` creation throws, audio is
|
||||
disabled and the game keeps running silently. No public method ever raises.
|
||||
A handful of short tones are synthesized in memory with stdlib ``array`` (no
|
||||
asset files). Audio is feedback only: it never mutates game state and never
|
||||
blocks input. If the mixer cannot initialize (no device, headless run) the
|
||||
engine degrades to silent no-ops and never raises.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
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),
|
||||
# kind (sine | square | noise | sweep), optional freq2 (sweep target).
|
||||
_SPECS: dict[str, dict] = {
|
||||
"hit": dict(freq=330, dur=0.07, decay=9.0, kind="square"),
|
||||
"miss": dict(freq=180, dur=0.06, decay=10.0, kind="sine"),
|
||||
"damage": dict(freq=120, dur=0.18, decay=5.0, kind="noise"),
|
||||
"pickup": dict(freq=660, dur=0.10, decay=8.0, kind="sweep", freq2=990),
|
||||
"use": dict(freq=520, dur=0.12, decay=7.0, kind="sweep", freq2=780),
|
||||
"stairs": dict(freq=400, dur=0.16, decay=5.0, kind="sweep", freq2=600),
|
||||
"levelup": dict(freq=523, dur=0.30, decay=3.0, kind="sweep", freq2=1046),
|
||||
"death": dict(freq=200, dur=0.45, decay=2.5, kind="sweep", freq2=80),
|
||||
"victory": dict(freq=523, dur=0.50, decay=2.0, kind="sweep", freq2=1568),
|
||||
# (base_freq_hz, duration_ms, volume, sweep_to_freq). sweep 0 => steady tone.
|
||||
_SFX: dict[str, tuple[int, int, float, int]] = {
|
||||
"hit": (330, 70, 0.35, 180),
|
||||
"crit": (660, 110, 0.45, 990),
|
||||
"miss": (200, 60, 0.20, 120),
|
||||
"damage": (140, 120, 0.40, 70),
|
||||
"pickup": (520, 70, 0.30, 780),
|
||||
"use": (700, 90, 0.30, 520),
|
||||
"stairs": (440, 140, 0.35, 880),
|
||||
"levelup": (523, 220, 0.40, 1046),
|
||||
"death": (300, 420, 0.45, 70),
|
||||
"victory": (523, 480, 0.45, 1568),
|
||||
"menu": (600, 50, 0.22, 600),
|
||||
}
|
||||
|
||||
|
||||
class AudioManager:
|
||||
"""Generates and plays short SFX; degrades to silence on any audio fault."""
|
||||
def _synth(freq: int, ms: int, volume: float, sweep: int) -> bytes:
|
||||
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._ok: bool = False
|
||||
self._sounds: dict = {}
|
||||
self._init()
|
||||
self.available: bool = False
|
||||
self._sounds: dict[str, Any] = {}
|
||||
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:
|
||||
try:
|
||||
if self.muted or not self._ok:
|
||||
if not self.available or self.muted:
|
||||
return
|
||||
snd = self._sounds.get(name)
|
||||
if snd is not None:
|
||||
snd = self._sounds.get(name) or self._sounds.get("hit")
|
||||
if snd is None:
|
||||
return
|
||||
try:
|
||||
snd.play()
|
||||
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
|
||||
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):
|
||||
info = pygame.mixer.get_init()
|
||||
if info is None:
|
||||
raise RuntimeError("mixer not initialized")
|
||||
rate, size, channels = info
|
||||
code = "h" if abs(size) == 16 else "b"
|
||||
maxv = (1 << (abs(size) - 1)) - 1
|
||||
n = max(1, int(rate * spec["dur"]))
|
||||
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())
|
||||
if __name__ == "__main__":
|
||||
pygame.init()
|
||||
eng = AudioEngine(enabled=True)
|
||||
print("available:", eng.available, "muted:", eng.muted)
|
||||
eng.play("hit")
|
||||
eng.toggle_mute()
|
||||
print("toggled mute ->", eng.muted)
|
||||
pygame.quit()
|
||||
@@ -1,60 +1,27 @@
|
||||
"""Turn-based combat resolution (plan.md §4).
|
||||
|
||||
`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.
|
||||
"""
|
||||
"""Combat resolution: hit chance, armor reduction, critical hits."""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
def attack(attacker, defender, rng=None, log=None) -> dict:
|
||||
r = rng if rng is not None else random.Random()
|
||||
|
||||
acc = getattr(attacker, "accuracy", 0)
|
||||
eva = getattr(defender, "evasion", 0)
|
||||
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}
|
||||
@dataclass
|
||||
class AttackRoll:
|
||||
hit: bool
|
||||
crit: bool
|
||||
damage: int
|
||||
|
||||
|
||||
def _log_swing(log: list, attacker, defender, hit: bool, crit: bool,
|
||||
damage: int, attacker_is_player: bool) -> None:
|
||||
if not hit:
|
||||
if attacker_is_player:
|
||||
log.append(f"You miss the {defender.name}")
|
||||
else:
|
||||
log.append(f"{attacker.name} misses you")
|
||||
return
|
||||
if attacker_is_player:
|
||||
if crit:
|
||||
log.append(f"Critical hit! You hit the {defender.name} for {damage} damage!")
|
||||
else:
|
||||
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!")
|
||||
def roll_attack(attacker: Any, defender: Any, rng: random.Random = random) -> AttackRoll:
|
||||
hit_chance = 0.7 + (attacker.accuracy - defender.evasion) * 0.05
|
||||
hit_chance = max(0.1, min(0.95, hit_chance))
|
||||
base = attacker.power + getattr(attacker, "weapon_power", 0)
|
||||
# Player exposes effective armor via total_armor(); plain objects/enemies use .armor.
|
||||
total_armor = getattr(defender, "total_armor", None)
|
||||
armor = total_armor() if callable(total_armor) else getattr(defender, "armor", 0)
|
||||
reduced = max(0, base - armor)
|
||||
if rng.random() >= hit_chance:
|
||||
return AttackRoll(hit=False, crit=False, damage=0)
|
||||
crit = rng.random() < attacker.crit_chance
|
||||
return AttackRoll(hit=True, crit=crit, damage=reduced * (2 if crit else 1))
|
||||
@@ -1,87 +1,94 @@
|
||||
"""Recursive shadowcasting field of view over 8 octants (plan.md §2).
|
||||
|
||||
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.
|
||||
"""
|
||||
"""Recursive shadowcasting field of view over 8 octants."""
|
||||
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], ...] = (
|
||||
(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),
|
||||
( 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]]:
|
||||
"""Return the set of visible tiles from (ox, oy); also set game_map.visible."""
|
||||
width, height = game_map.width, game_map.height
|
||||
def compute_fov(
|
||||
game_map: Any, origin: tuple[int, int], radius: int = SIGHT_RADIUS
|
||||
) -> 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
|
||||
|
||||
# Fresh visible grid every call so stale tiles never linger.
|
||||
for y in range(height):
|
||||
vrow = game_map.visible[y]
|
||||
for x in range(width):
|
||||
vrow[x] = False
|
||||
|
||||
visible: set[tuple[int, int]] = set()
|
||||
cx, cy = origin
|
||||
r2 = radius * radius
|
||||
visible: set[tuple[int, int]] = {(cx, cy)}
|
||||
|
||||
def blocks(x: int, y: int) -> bool:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
return tiles[y][x] == 0
|
||||
return True # out of bounds behaves as wall
|
||||
|
||||
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
|
||||
if not game_map.in_bounds(x, y):
|
||||
return True
|
||||
return tiles[y][x] != FLOOR
|
||||
|
||||
def cast(row: int, start: float, end: float,
|
||||
xx: int, xy: int, yx: int, yy: int) -> None:
|
||||
if start < end:
|
||||
return
|
||||
new_start = start
|
||||
for j in range(row, radius + 1):
|
||||
dy = -j
|
||||
dx = -j - 1
|
||||
dy = -j
|
||||
blocked = False
|
||||
new_start = end
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
mx = ox + dx * xx + dy * xy
|
||||
my = oy + dx * yx + dy * yy
|
||||
mx = cx + dx * xx + dy * xy
|
||||
my = cy + dx * yx + dy * yy
|
||||
l_slope = (dx - 0.5) / (dy + 0.5)
|
||||
r_slope = (dx + 0.5) / (dy - 0.5)
|
||||
if start < r_slope:
|
||||
continue
|
||||
elif end > l_slope:
|
||||
if end > l_slope:
|
||||
break
|
||||
else:
|
||||
if dx * dx + dy * dy <= r2:
|
||||
light(mx, my)
|
||||
if dx * dx + dy * dy <= r2 and game_map.in_bounds(mx, my):
|
||||
visible.add((mx, my))
|
||||
if blocked:
|
||||
if blocks(mx, my):
|
||||
new_start = r_slope
|
||||
continue
|
||||
else:
|
||||
blocked = False
|
||||
start = new_start
|
||||
else:
|
||||
if blocks(mx, my) and j < radius:
|
||||
elif blocks(mx, my) and j < radius:
|
||||
blocked = True
|
||||
cast(j + 1, start, l_slope, xx, xy, yx, yy)
|
||||
new_start = r_slope
|
||||
# Row ended inside a wall run: deeper rows are fully occluded.
|
||||
if blocked:
|
||||
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)
|
||||
|
||||
for (x, y) in visible:
|
||||
game_map.visible[y][x] = True
|
||||
|
||||
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())
|
||||
@@ -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
|
||||
state string. `new_game` builds a fresh dive; `recompute_fov` refreshes the
|
||||
player's sight and merges it into the explored memory.
|
||||
``new_session`` generates all 10 floors AND populates them with enemies/items
|
||||
(keep generation in map_gen, content spawning here). Floor 9 always carries the
|
||||
Ancient Dragon so the boss is killable/victory-triggerable on a real playthrough.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
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 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)
|
||||
class GameSession:
|
||||
player: Player
|
||||
dungeon: list
|
||||
player: Any = None
|
||||
dungeon: list = field(default_factory=list)
|
||||
current_floor: int = 0
|
||||
log: list = field(default_factory=list)
|
||||
turn: int = 0
|
||||
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)
|
||||
# generate_dungeon draws from the global random module; seed it too so the
|
||||
# entire dive is deterministic from `seed`.
|
||||
random.seed(seed)
|
||||
|
||||
player = Player(0, 0)
|
||||
|
||||
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(
|
||||
dungeon = map_gen.generate_dungeon(seed=seed)
|
||||
for gm in dungeon:
|
||||
populate_floor(gm, rng)
|
||||
spawn = dungeon[0].spawn or (1, 1)
|
||||
player = Player(x=spawn[0], y=spawn[1])
|
||||
return GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=["You enter the Underdepths. Find the stairs and descend."],
|
||||
log=["You descend into the Underdepths."],
|
||||
turn=0,
|
||||
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()
|
||||
@@ -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
|
||||
|
||||
import random
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data import constants as C
|
||||
from entities.enemy import make_enemy, kinds_for_floor
|
||||
from entities.item import make_item, item_pool_for_floor
|
||||
|
||||
# BSP / room sizing. Rooms are 4x4..10x8 (plan.md §1); leaves must hold one.
|
||||
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
|
||||
from data.constants import (
|
||||
MAP_W, MAP_H, FLOOR_COUNT, WALL, FLOOR,
|
||||
ROOM_MIN_W, ROOM_MIN_H, ROOM_MAX_W, ROOM_MAX_H,
|
||||
BSP_MIN_HALF, BSP_LEAVES_MIN, BSP_LEAVES_MAX,
|
||||
BOSS_ROOM_W, BOSS_ROOM_H,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@dataclass
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
@@ -29,281 +33,175 @@ class Rect:
|
||||
def center(self) -> tuple[int, int]:
|
||||
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)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: list[list[int]] # 0 = wall, 1 = floor
|
||||
tiles: list[list[int]]
|
||||
rooms: list[Rect]
|
||||
explored: list[list[bool]]
|
||||
visible: list[list[bool]]
|
||||
entities: list # enemies + items present on this floor
|
||||
stairs_down: tuple[int, int]
|
||||
entities: list
|
||||
stairs_down: tuple[int, int] | None
|
||||
spawn: tuple[int, int] | None
|
||||
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:
|
||||
"""True if (x, y) is in bounds and a floor tile."""
|
||||
if not (0 <= x < game_map.width and 0 <= y < game_map.height):
|
||||
return False
|
||||
return game_map.tiles[y][x] == 1
|
||||
def walkable(self, x: int, y: int) -> bool:
|
||||
return self.in_bounds(x, y) and self.tiles[y][x] == FLOOR
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Generation
|
||||
# --------------------------------------------------------------------------- #
|
||||
def generate_dungeon(floor_index: int, width: int = C.MAP_WIDTH,
|
||||
height: int = C.MAP_HEIGHT) -> GameMap:
|
||||
"""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)
|
||||
# --------------------------------------------------------------------- carving
|
||||
def _carve_rect(tiles: list[list[int]], r: Rect) -> None:
|
||||
for y in range(r.y, r.y + r.h):
|
||||
for x in range(r.x, r.x + r.w):
|
||||
tiles[y][x] = FLOOR
|
||||
|
||||
|
||||
def _build_bsp(root: dict, target_splits: int) -> None:
|
||||
"""Split the largest splittable leaf until target_splits splits are done."""
|
||||
splittable = [root]
|
||||
done = 0
|
||||
prefer_horiz = True
|
||||
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 _carve_h(tiles: list[list[int]], x1: int, x2: int, y: int) -> None:
|
||||
if x2 < x1:
|
||||
x1, x2 = x2, x1
|
||||
for x in range(x1, x2 + 1):
|
||||
tiles[y][x] = FLOOR
|
||||
|
||||
|
||||
def _split_node(node: dict, prefer_horiz: bool) -> tuple[dict, dict] | None:
|
||||
"""Split a region on the preferred axis, falling back to the other.
|
||||
def _carve_v(tiles: list[list[int]], y1: int, y2: int, x: int) -> None:
|
||||
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.
|
||||
"""
|
||||
use_horiz = prefer_horiz
|
||||
if use_horiz and node["w"] < 2 * MIN_LEAF:
|
||||
use_horiz = False
|
||||
if not use_horiz and node["h"] < 2 * MIN_LEAF:
|
||||
use_horiz = True
|
||||
length = node["w"] if use_horiz else node["h"]
|
||||
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"]}
|
||||
|
||||
def _carve_corridor(tiles: list[list[int]], a: tuple[int, int],
|
||||
b: tuple[int, int], rng: random.Random) -> None:
|
||||
ax, ay = a
|
||||
bx, by = b
|
||||
if rng.random() < 0.5:
|
||||
_carve_h(tiles, ax, bx, ay)
|
||||
_carve_v(tiles, ay, by, bx)
|
||||
else:
|
||||
left = {"x": node["x"], "y": node["y"], "w": node["w"], "h": p}
|
||||
right = {"x": node["x"], "y": node["y"] + p, "w": node["w"], "h": node["h"] - p}
|
||||
return left, right
|
||||
_carve_v(tiles, ay, by, ax)
|
||||
_carve_h(tiles, ax, bx, by)
|
||||
|
||||
|
||||
def _collect_leaves(node: dict, out: list[dict]) -> None:
|
||||
if "left" in node:
|
||||
_collect_leaves(node["left"], out)
|
||||
_collect_leaves(node["right"], out)
|
||||
# --------------------------------------------------------------------- bsp tree
|
||||
def _bsp(root: Rect, rng: random.Random) -> list[Rect]:
|
||||
target = rng.randint(BSP_LEAVES_MIN, BSP_LEAVES_MAX)
|
||||
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:
|
||||
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:
|
||||
"""Carve a room (4x4..10x8) inside the leaf, shrunk from its edges."""
|
||||
shrink = random.randint(1, 2)
|
||||
max_w = max(MIN_ROOM_W, leaf["w"] - 2 * shrink)
|
||||
max_h = max(MIN_ROOM_H, leaf["h"] - 2 * shrink)
|
||||
rw = random.randint(MIN_ROOM_W, min(MAX_ROOM_W, max_w))
|
||||
rh = random.randint(MIN_ROOM_H, min(MAX_ROOM_H, max_h))
|
||||
ox = random.randint(shrink, max(shrink, leaf["w"] - rw - shrink))
|
||||
oy = random.randint(shrink, max(shrink, leaf["h"] - rh - shrink))
|
||||
rx = leaf["x"] + ox
|
||||
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 _room_in(leaf: Rect, tiles: list[list[int]], rng: random.Random) -> Rect:
|
||||
max_w = leaf.w - 2
|
||||
max_h = leaf.h - 2
|
||||
w = rng.randint(ROOM_MIN_W, min(ROOM_MAX_W, max_w))
|
||||
h = rng.randint(ROOM_MIN_H, min(ROOM_MAX_H, max_h))
|
||||
x = rng.randint(leaf.x + 1, leaf.x + 1 + max(0, max_w - w))
|
||||
y = rng.randint(leaf.y + 1, leaf.y + 1 + max(0, max_h - h))
|
||||
room = Rect(x, y, w, h)
|
||||
_carve_rect(tiles, room)
|
||||
return room
|
||||
|
||||
|
||||
def _connect(node: dict, tiles: list[list[int]], width: int, height: int) -> Rect | None:
|
||||
"""Carve L-corridors between sibling subtree rooms so all rooms connect."""
|
||||
if "left" not in node:
|
||||
return node.get("room")
|
||||
lr = _connect(node["left"], tiles, width, height)
|
||||
rr = _connect(node["right"], tiles, width, height)
|
||||
if lr is not None and rr is not None:
|
||||
_carve_corridor(lr.center, rr.center, tiles, width, height)
|
||||
return lr if lr is not None else rr
|
||||
|
||||
|
||||
def _carve_corridor(a: tuple[int, int], b: tuple[int, int],
|
||||
tiles: list[list[int]], width: int, height: int) -> None:
|
||||
x1, y1 = a
|
||||
x2, y2 = b
|
||||
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)
|
||||
# ---------------------------------------------------------------- reachability
|
||||
def _flood(tiles: list[list[int]], start: tuple[int, int],
|
||||
width: int, height: int) -> set[tuple[int, int]]:
|
||||
sx, sy = start
|
||||
seen = {(sx, sy)}
|
||||
dq = deque([(sx, sy)])
|
||||
while dq:
|
||||
x, y = dq.popleft()
|
||||
for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
||||
if (nx, ny) in seen:
|
||||
continue
|
||||
if 0 <= nx < width and 0 <= ny < height and tiles[ny][nx] == FLOOR:
|
||||
seen.add((nx, ny))
|
||||
dq.append((nx, ny))
|
||||
return seen
|
||||
|
||||
|
||||
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Population
|
||||
# --------------------------------------------------------------------------- #
|
||||
def populate(game_map: GameMap, floor_index: int, rng: random.Random | None = None) -> None:
|
||||
"""Place enemies AND items per the plan's per-floor distribution. Never raises.
|
||||
|
||||
Floor 9 (boss) gets the dragon plus exactly two healing potions near the
|
||||
entrance; every other floor gets enemies and items drawn from the roster /
|
||||
catalog, depth-gated.
|
||||
"""
|
||||
r = rng if rng is not None else random
|
||||
|
||||
if floor_index == C.FLOORS - 1:
|
||||
room = game_map.rooms[0]
|
||||
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)
|
||||
# --------------------------------------------------------------------- builders
|
||||
def _boss_floor(floor_index: int) -> GameMap:
|
||||
width, height = MAP_W, MAP_H
|
||||
tiles = [[WALL] * width for _ in range(height)]
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
|
||||
rx = (width - rw) // 2
|
||||
ry = (height - rh) // 2
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
_carve_rect(tiles, room)
|
||||
spawn = (rx + 1, ry + rh // 2)
|
||||
return GameMap(width, height, tiles, [room], explored, visible,
|
||||
[], None, spawn, floor_index)
|
||||
|
||||
|
||||
def _place_items(game_map: GameMap, floor_index: int, r) -> None:
|
||||
"""Scatter ITEM_COUNT items from the depth-weighted pool across floor tiles."""
|
||||
lo, hi = C.ITEM_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
|
||||
r.shuffle(pool)
|
||||
names = item_pool_for_floor(floor_index)
|
||||
placed = 0
|
||||
for tile in pool:
|
||||
if placed >= n:
|
||||
break
|
||||
game_map.entities.append(make_item(r.choice(names), tile[0], tile[1]))
|
||||
placed += 1
|
||||
def _standard_floor(floor_index: int, rng: random.Random) -> GameMap:
|
||||
width, height = MAP_W, MAP_H
|
||||
tiles = [[WALL] * width for _ in range(height)]
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
|
||||
leaves = _bsp(Rect(1, 1, width - 2, height - 2), rng)
|
||||
rooms = [_room_in(leaf, tiles, rng) for leaf in leaves]
|
||||
|
||||
# Chain-connect consecutive rooms -> connected spanning path of floor tiles.
|
||||
for i in range(len(rooms) - 1):
|
||||
_carve_corridor(tiles, rooms[i].center, rooms[i + 1].center, rng)
|
||||
|
||||
spawn = rooms[0].center
|
||||
far = max(rooms, key=lambda r: _dist2(r.center, spawn))
|
||||
stairs = far.center
|
||||
|
||||
# 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:
|
||||
"""Put two Healing Potions by the boss-room entrance (far side from the dragon)."""
|
||||
ex, ey = room.center[0], room.y + room.h - 2
|
||||
placed = 0
|
||||
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 generate_floor(floor_index: int, rng: random.Random) -> GameMap:
|
||||
if floor_index == FLOOR_COUNT - 1:
|
||||
return _boss_floor(floor_index)
|
||||
return _standard_floor(floor_index, rng)
|
||||
|
||||
|
||||
def _first_floor_tile(game_map: GameMap) -> tuple[int, int] | None:
|
||||
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 None
|
||||
def generate_dungeon(seed: int) -> list[GameMap]:
|
||||
rng = random.Random(seed)
|
||||
return [generate_floor(i, rng) for i in range(FLOOR_COUNT)]
|
||||
@@ -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
|
||||
|
||||
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:
|
||||
"""Shortest floor path from start to goal, or None if unreachable.
|
||||
def find_path(
|
||||
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
|
||||
tiles (other entities) except that the goal is always reachable even if it
|
||||
sits in `blocked` (an enemy may path up to its target). Returns the path
|
||||
including both endpoints; None if start/goal is a wall or out of bounds.
|
||||
The path excludes ``start`` and includes ``goal``. Returns ``[]`` when
|
||||
``start == goal`` and ``None`` when no route exists. Walls and every tile
|
||||
in ``blocked`` are impassable.
|
||||
"""
|
||||
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
|
||||
|
||||
if not _is_floor(game_map, sx, sy) or not _is_floor(game_map, gx, gy):
|
||||
return None
|
||||
if start == goal:
|
||||
return [(sx, sy)]
|
||||
def h(x: int, y: int) -> int:
|
||||
return abs(x - gx) + abs(y - gy)
|
||||
|
||||
blocked_set = set(blocked)
|
||||
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
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()
|
||||
|
||||
while open_heap:
|
||||
@@ -33,37 +44,44 @@ def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] |
|
||||
if current in closed:
|
||||
continue
|
||||
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)
|
||||
cx, cy = current
|
||||
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
|
||||
nb = (nx, ny)
|
||||
if nb in closed or not _is_floor(game_map, nx, ny):
|
||||
base = g_score[current]
|
||||
for dx, dy in _DIRS:
|
||||
nxt = (cx + dx, cy + dy)
|
||||
if nxt in closed or nxt in blocked or not game_map.walkable(*nxt):
|
||||
continue
|
||||
if nb in blocked_set and nb != goal:
|
||||
continue
|
||||
tentative = g_score[current] + 1
|
||||
if tentative < g_score.get(nb, 1_000_000):
|
||||
g_score[nb] = tentative
|
||||
came_from[nb] = current
|
||||
tentative = base + 1
|
||||
if tentative < g_score.get(nxt, float("inf")):
|
||||
g_score[nxt] = tentative
|
||||
came_from[nxt] = current
|
||||
counter += 1
|
||||
heapq.heappush(open_heap, (tentative + _manhattan(nb, goal), counter, nb))
|
||||
heapq.heappush(open_heap, (tentative + h(*nxt), counter, nxt))
|
||||
return None
|
||||
|
||||
|
||||
def _is_floor(game_map, x: int, y: int) -> bool:
|
||||
return (0 <= x < game_map.width and 0 <= y < game_map.height
|
||||
and game_map.tiles[y][x] == 1)
|
||||
if __name__ == "__main__":
|
||||
from engine.map_gen import generate_dungeon
|
||||
|
||||
|
||||
def _manhattan(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _reconstruct(came_from: dict, current: tuple[int, int]) -> list[tuple[int, int]]:
|
||||
path = [current]
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append(current)
|
||||
path.reverse()
|
||||
return path
|
||||
gm = generate_dungeon(seed=1)[0]
|
||||
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
|
||||
# identity
|
||||
assert find_path(gm, (sx, sy), (sx, sy)) == []
|
||||
# reach stairs
|
||||
if gm.stairs_down is not None:
|
||||
p = find_path(gm, (sx, sy), gm.stairs_down)
|
||||
assert p is not None and p[-1] == gm.stairs_down, (sx, sy, gm.stairs_down, p)
|
||||
assert (sx, sy) not in p
|
||||
assert all(gm.walkable(*t) for t in p)
|
||||
print(f"path spawn->stairs: {len(p)} steps, first {p[:3]}")
|
||||
# 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")
|
||||
@@ -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
|
||||
`recompute_fov` on load. Every other field of Player / Enemy / Item is preserved
|
||||
verbatim, including per-instance enemy state (damaged HP, last-known position,
|
||||
small-slime `can_split=False`, act counters) so a loaded dive matches the saved
|
||||
dive exactly. Entities are reconstructed directly from their serialized fields
|
||||
rather than via `make_enemy`/`make_item`, which would reset mutable state to the
|
||||
roster/catalog defaults.
|
||||
The volatile `visible` grid is deliberately excluded from the saved form: it is
|
||||
recomputed from FOV on load, so persisting it would only bloat the save and risk
|
||||
a stale view. Everything else that survives across a save/quit/relaunch is kept.
|
||||
|
||||
Tuples are preserved as tuples (not flattened to lists) so a to_dict -> from_dict
|
||||
-> to_dict cycle is byte-stable under Python dict equality.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from engine.game_state import GameSession, recompute_fov
|
||||
from engine.map_gen import GameMap, Rect
|
||||
from dataclasses import fields
|
||||
from typing import Any
|
||||
|
||||
from entities.player import Player
|
||||
from entities.enemy import Enemy
|
||||
from entities.entity import Entity
|
||||
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:
|
||||
return {
|
||||
"player": _player_to_dict(session.player),
|
||||
"dungeon": [_map_to_dict(m) for m in session.dungeon],
|
||||
"player": _to_json(session.player),
|
||||
"dungeon": [_floor_to_dict(gm) for gm in session.dungeon],
|
||||
"current_floor": session.current_floor,
|
||||
"turn": session.turn,
|
||||
"log": list(session.log),
|
||||
@@ -32,193 +113,12 @@ def session_to_dict(session: GameSession) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def dict_to_session(d: dict) -> GameSession:
|
||||
session = GameSession(
|
||||
player=_dict_to_player(d["player"]),
|
||||
dungeon=[_dict_to_map(m) for m in d["dungeon"]],
|
||||
def session_from_dict(d: dict) -> GameSession:
|
||||
return GameSession(
|
||||
player=_from_json(d["player"]),
|
||||
dungeon=[_floor_from_dict(fd) for fd in d["dungeon"]],
|
||||
current_floor=d["current_floor"],
|
||||
log=list(d["log"]),
|
||||
turn=d["turn"],
|
||||
log=list(d["log"]),
|
||||
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"],
|
||||
)
|
||||
@@ -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 dataclasses import dataclass
|
||||
|
||||
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),
|
||||
),
|
||||
}
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Enemy(Entity):
|
||||
class Enemy:
|
||||
x: int = 0
|
||||
y: int = 0
|
||||
kind: str = ""
|
||||
name: str = ""
|
||||
sprite_key: str = "enemy"
|
||||
hp: int = 1
|
||||
max_hp: int = 1
|
||||
power: int = 0
|
||||
power: int = 1
|
||||
armor: int = 0
|
||||
accuracy: int = 0
|
||||
accuracy: int = 4
|
||||
evasion: int = 0
|
||||
crit_chance: float = 0.0
|
||||
ranged_power: int = 0
|
||||
speed: int = 1
|
||||
behavior: str = "wander"
|
||||
xp_value: int = 0
|
||||
last_known_pos: tuple[int, int] | None = None
|
||||
act_counter: int = 0
|
||||
can_split: bool = True
|
||||
ranged_power: int = 0
|
||||
last_known_pos: Any = None
|
||||
can_split: bool = False
|
||||
sprite_key: str = ""
|
||||
|
||||
|
||||
def make_enemy(kind: str, x: int, y: int) -> Enemy:
|
||||
"""Construct an Enemy of the given kind at (x, y) with full roster stats."""
|
||||
s = _ROSTER[kind]
|
||||
return Enemy(
|
||||
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]
|
||||
]
|
||||
@property
|
||||
def xp(self) -> int:
|
||||
# Contract field is xp_value; gates/tests read .xp. One descriptor,
|
||||
# no extra storage (slots-safe: name is not a slot).
|
||||
return self.xp_value
|
||||
@@ -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 dataclasses import dataclass
|
||||
@@ -6,11 +6,6 @@ from dataclasses import dataclass
|
||||
|
||||
@dataclass(slots=True)
|
||||
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
|
||||
y: int
|
||||
name: str
|
||||
|
||||
@@ -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;
|
||||
`item_pool_for_floor` gives a depth-weighted name list for dungeon population.
|
||||
Matches the tests/smoke.py contract: x, y, kind, name, category, stats(dict).
|
||||
``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 dataclasses import dataclass, field
|
||||
|
||||
from entities.entity import Entity
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Item(Entity):
|
||||
"""A carryable thing. `blocks` is False — items never occupy a tile alone."""
|
||||
item_type: str = "misc" # weapon | armor | potion | scroll
|
||||
subtype: str = "" # healing | strength | invisibility | fireball | teleport | mapping
|
||||
class Item:
|
||||
x: int = 0
|
||||
y: int = 0
|
||||
kind: str = ""
|
||||
name: str = ""
|
||||
category: str = ""
|
||||
stats: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
# 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
|
||||
sprite_key: str = ""
|
||||
blocks: bool = False
|
||||
@@ -1,87 +1,81 @@
|
||||
"""The player adventurer: stats, inventory, equipment, leveling."""
|
||||
"""Player: stats, inventory, equipment, and leveling."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from data import constants as C
|
||||
from entities.entity import Entity
|
||||
from data.constants import LEVEL_TABLE, LEVEL_CAP, PLAYER_BASE, STRENGTH_POTION_POWER
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Effect:
|
||||
"""A timed status effect on the player (plan.md §6 potions).
|
||||
|
||||
`kind` is "strength" (+power) or "invisibility". `duration` is turns left;
|
||||
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"
|
||||
class Player:
|
||||
x: int = 0
|
||||
y: int = 0
|
||||
name: str = "Adventurer"
|
||||
sprite_key: str = "player"
|
||||
# stats
|
||||
hp: int = 50
|
||||
max_hp: int = 50
|
||||
power: int = 4
|
||||
armor: int = 0
|
||||
accuracy: int = 5
|
||||
evasion: int = 2
|
||||
crit_chance: float = 0.10
|
||||
speed: int = 1
|
||||
# progression
|
||||
blocks: bool = True
|
||||
hp: int = PLAYER_BASE["hp"]
|
||||
max_hp: int = PLAYER_BASE["max_hp"]
|
||||
power: int = PLAYER_BASE["power"]
|
||||
armor: int = PLAYER_BASE["armor"]
|
||||
accuracy: int = PLAYER_BASE["accuracy"]
|
||||
evasion: int = PLAYER_BASE["evasion"]
|
||||
crit_chance: float = PLAYER_BASE["crit_chance"]
|
||||
speed: int = PLAYER_BASE["speed"]
|
||||
level: int = 1
|
||||
xp: int = 0
|
||||
# gear / effects
|
||||
inventory: list = field(default_factory=list)
|
||||
equipped: dict = field(default_factory=dict)
|
||||
effects: list = field(default_factory=list)
|
||||
facing: str = "down"
|
||||
invisible: bool = False
|
||||
# transient: level-up messages the game loop flushes into the session log
|
||||
pending_log: list = field(default_factory=list)
|
||||
equipped_weapon: Any = None
|
||||
equipped_armor: Any = None
|
||||
effect_timers: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
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:
|
||||
"""Base power + equipped weapon bonus + active strength effect."""
|
||||
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)
|
||||
return self.power + self.weapon_power
|
||||
|
||||
def total_armor(self) -> int:
|
||||
"""Base armor + equipped armor bonus."""
|
||||
a = self.armor
|
||||
armor = self.equipped.get("armor")
|
||||
if armor is not None and hasattr(armor, "stats"):
|
||||
a += armor.stats.get("armor", 0)
|
||||
return int(a)
|
||||
if self.equipped_armor is not None:
|
||||
a += self.equipped_armor.stats.get("armor", 0)
|
||||
return a
|
||||
|
||||
def gain_xp(self, amount: int) -> bool:
|
||||
"""Award XP, applying chained level-ups from the plan table.
|
||||
def equip(self, item: Any) -> None:
|
||||
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
|
||||
are buffered into `pending_log` for the game loop to flush. Returns
|
||||
True if any level-up occurred.
|
||||
"""
|
||||
def gain_xp(self, amount: int) -> int:
|
||||
self.xp += amount
|
||||
levelled = False
|
||||
while self.level < C.MAX_LEVEL and self.xp >= C.XP_THRESHOLDS[self.level + 1]:
|
||||
new_level = self.level + 1
|
||||
hp_gain = C.LEVEL_HP_GAIN[new_level]
|
||||
pow_gain = C.LEVEL_POWER_GAIN[new_level]
|
||||
self.level = new_level
|
||||
gained = 0
|
||||
while self.level < LEVEL_CAP and self.level - 1 < len(LEVEL_TABLE):
|
||||
need = LEVEL_TABLE[self.level - 1][0]
|
||||
if self.xp < need:
|
||||
break
|
||||
_need, hp_gain, pow_gain = LEVEL_TABLE[self.level - 1]
|
||||
self.level += 1
|
||||
self.max_hp += hp_gain
|
||||
self.power += pow_gain
|
||||
gained += 1
|
||||
if gained:
|
||||
self.hp = self.max_hp
|
||||
levelled = True
|
||||
self.pending_log.append(
|
||||
f"You reach level {self.level}! (HP +{hp_gain}, Power +{pow_gain})"
|
||||
)
|
||||
return levelled
|
||||
return gained
|
||||
@@ -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
|
||||
ENVIRONMENT the test harness sets (SDL_VIDEODRIVER==dummy). When headless, run
|
||||
a scripted self-check of `max_frames` frames then return. With no environment
|
||||
variables, `python main.py` opens a real window with real audio.
|
||||
Headless detection honors ``SDL_VIDEODRIVER=='dummy'`` (never forced in code);
|
||||
``UNDERDEPTHS_MAX_FRAMES`` bounds a run so the harness can launch this headless
|
||||
and exit cleanly. ``new_game(seed)`` builds a fresh ``GameSession``.
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
from engine.audio import AudioManager # noqa: E402
|
||||
from render import renderer as R # noqa: E402
|
||||
from render import sprites as RS # noqa: E402
|
||||
SCREEN_W = 960
|
||||
SCREEN_H = 600
|
||||
FONT_STACK = "monospace,consolas,couriernew,dejavusans"
|
||||
MAXFRAMES_ENV = "UNDERDEPTHS_MAX_FRAMES"
|
||||
|
||||
SAVE = "save.json"
|
||||
FPS = 60
|
||||
MOVE_DELAY = 0.11
|
||||
_MENU = ["New Game", "Continue", "How to Play", "Quit"]
|
||||
_HOWTO = [
|
||||
"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):
|
||||
m = re.search(r"for (\d+) damage", s)
|
||||
return int(m.group(1)) if m else None
|
||||
def new_game(seed: int = 0) -> Any:
|
||||
return new_session(seed)
|
||||
|
||||
|
||||
def _facing_delta(facing: str):
|
||||
return {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}.get(facing, (0, 1))
|
||||
|
||||
|
||||
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
|
||||
# --------------------------------------------------------------------- helpers
|
||||
def _font(size: int, bold: bool = False) -> pygame.font.Font:
|
||||
try:
|
||||
self.session = game_state.load(SAVE)
|
||||
return pygame.font.SysFont(FONT_STACK, size, bold=bold)
|
||||
except Exception:
|
||||
return False
|
||||
self._prev_log = len(self.session.log)
|
||||
self._prev_hp = self.session.player.hp
|
||||
self.view = "play"
|
||||
self.overlay = None
|
||||
return True
|
||||
return pygame.font.Font(None, size)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
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()
|
||||
running = True
|
||||
while running:
|
||||
dt = clock.tick(FPS) / 1000.0
|
||||
self.t += dt
|
||||
self.move_cd = max(0.0, self.move_cd - dt)
|
||||
frame = 0
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if self._keydown(event.key):
|
||||
running = False
|
||||
break
|
||||
|
||||
if self.view == "play" and self.overlay is None:
|
||||
self._poll_move(dt)
|
||||
|
||||
self.r.update(dt)
|
||||
self._render()
|
||||
pygame.display.flip()
|
||||
|
||||
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]
|
||||
k = event.key
|
||||
if ui == "menu":
|
||||
if k in (pygame.K_DOWN, pygame.K_s):
|
||||
menu_idx = (menu_idx + 1) % len(_MENU)
|
||||
audio.play("menu")
|
||||
elif k in (pygame.K_UP, pygame.K_w):
|
||||
menu_idx = (menu_idx - 1) % len(_MENU)
|
||||
audio.play("menu")
|
||||
elif k in (pygame.K_RETURN, pygame.K_KP_ENTER):
|
||||
choice = _MENU[menu_idx]
|
||||
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":
|
||||
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":
|
||||
self.overlay = "help"
|
||||
ui = "howto"
|
||||
elif choice == "Quit":
|
||||
return True
|
||||
elif key == pygame.K_ESCAPE:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _play_key(self, key) -> bool:
|
||||
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)
|
||||
running = False
|
||||
elif k == pygame.K_ESCAPE:
|
||||
running = False
|
||||
elif ui == "howto":
|
||||
if k == pygame.K_ESCAPE:
|
||||
ui = "playing" if session is not None else "menu"
|
||||
else:
|
||||
game.run()
|
||||
finally:
|
||||
try:
|
||||
ui = "playing" if session is not None else "menu"
|
||||
elif ui == "playing" and session is not None:
|
||||
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()
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -1,470 +1,383 @@
|
||||
#!/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
|
||||
# passes --model/--provider), one dispatch per build phase, each gated by
|
||||
# `python3 tests/smoke.py --phase N`. Resumable across crashes via .build_state.
|
||||
# A goal backstop after phase 4 verifies EVERY acceptance criterion and loops
|
||||
# fixes until all pass.
|
||||
# Drives the whole game build with `pi -p` (DEFAULT model only — never
|
||||
# --model/--provider). Resumable via .build_state (single int = last completed
|
||||
# phase). Re-run after a crash picks up where it left off.
|
||||
#
|
||||
# Phases run SEQUENTIALLY (a hung worker would block bash `&`+`wait` forever;
|
||||
# learned the hard way on this very project). Every dispatch is wrapped in
|
||||
# `timeout --kill-after=30` because the pi (node) process ignores SIGTERM.
|
||||
#
|
||||
# State machine (.build_state = index of last completed phase):
|
||||
# 0 -> nothing 1 -> P1 2 -> P2 3 -> P3 4 -> P4(4a+4b+gate) 5 -> goal
|
||||
# =============================================================================
|
||||
# Hardening (learned the hard way on this exact challenge):
|
||||
# * SEQUENTIAL dispatches only — parallel `pi -p` agents corrupt shared files.
|
||||
# * Watchdog SIGKILL of the whole process group: `pi` is node, ignores
|
||||
# SIGTERM, so plain `timeout` lets hung workers linger. setsid -w puts the
|
||||
# worker in its own session; we kill -$pgid to reap the whole tree.
|
||||
# * 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
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
STATE=.build_state
|
||||
PIDF=.pipeline.pid
|
||||
LOG_DIR=logs
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$DIR"
|
||||
|
||||
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"
|
||||
|
||||
MAX_RETRIES=${MAX_RETRIES:-3}
|
||||
TTL=${TTL:-3000} # ~50 min ceiling per dispatch
|
||||
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"
|
||||
TTL="${UNDERDEPTHS_TTL:-3000}" # per-dispatch ceiling, seconds (50 min)
|
||||
MAX_RETRIES=3
|
||||
|
||||
# --- concurrency guard: never two pipelines in one directory ---------------
|
||||
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
|
||||
PY="${PYTHON:-python3}"
|
||||
|
||||
get_state() { [[ -f "$STATE" ]] && cat "$STATE" 2>/dev/null || echo 0; }
|
||||
set_state() { echo "$1" > "$STATE"; }
|
||||
halt() { echo "!!! PIPELINE HALTED at the phase above — see logs/ !!!" >&2; exit 1; }
|
||||
log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" | tee -a "$LOG"; }
|
||||
|
||||
# dispatch NAME PROMPT GATE_CMD
|
||||
# Ralph loop: up to MAX_RETRIES, feeding the actual gate error back on retry.
|
||||
dispatch() {
|
||||
local name="$1" prompt="$2" gate="$3"
|
||||
local attempt=0 gate_out gate_rc full_prompt
|
||||
while (( attempt < MAX_RETRIES )); do
|
||||
attempt=$((attempt + 1))
|
||||
echo "==================================================================="
|
||||
echo ">>> $name (attempt $attempt/$MAX_RETRIES) $(date +%H:%M:%S)"
|
||||
echo "==================================================================="
|
||||
if (( attempt == 1 )); then
|
||||
full_prompt="$prompt"
|
||||
else
|
||||
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' \
|
||||
"$prompt" "$(printf '%s' "${gate_out}" | tail -n 70)" "$prompt")"
|
||||
fi
|
||||
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" &
|
||||
# ---------------------------------------------------------------------------
|
||||
# run_dispatch <prompt> : run `pi -p "<prompt>"` under a watchdog. Always
|
||||
# returns (never hangs). Output appended to $DISPATCH_LOG.
|
||||
# ---------------------------------------------------------------------------
|
||||
run_dispatch() {
|
||||
local prompt="$1"
|
||||
: > "$DISPATCH_LOG"
|
||||
: > "$PIDFILE"
|
||||
log " dispatch: pi -p (<${#prompt} chars>) TTL=${TTL}s"
|
||||
|
||||
# setsid -w: child becomes session leader (pid==pgid); parent waits => $! is a
|
||||
# synchronous handle. Inner bash records its pid+pgid for the watchdog.
|
||||
setsid -w bash -c '
|
||||
echo "$$ $(ps -o pgid= -p $$ | tr -d " ")" > "$1"
|
||||
exec pi -p "$2"
|
||||
' bash "$PIDFILE" "$prompt" >>"$DISPATCH_LOG" 2>&1 &
|
||||
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
|
||||
local rc=$?
|
||||
kill "$wd" 2>/dev/null; wait "$wd" 2>/dev/null
|
||||
if (( rc != 0 )); then
|
||||
echo " ! dispatch ended (rc=$rc; timeout or error); tail of log:" >&2
|
||||
tail -n 8 "$logf" >&2
|
||||
fi
|
||||
echo " gate: $gate"
|
||||
gate_out="$(eval "$gate" 2>&1)"
|
||||
gate_rc=$?
|
||||
printf '%s\n' "${gate_out}" | tail -n 35
|
||||
if (( gate_rc == 0 )); then
|
||||
echo "<<< $name PASS"
|
||||
kill "$wdog" 2>/dev/null
|
||||
wait "$wdog" 2>/dev/null
|
||||
log " dispatch returned rc=$rc"
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# run_gate <args...> : run the smoke gate. Sets GATE_OUT to combined output.
|
||||
# Returns 0 on PASS, 1 on FAIL.
|
||||
# ---------------------------------------------------------------------------
|
||||
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
|
||||
fi
|
||||
echo " ! gate failed (attempt $attempt, rc=$gate_rc)"
|
||||
done
|
||||
echo "<<< $name FAILED after $MAX_RETRIES attempts — full log: $LOG_DIR/${name}.attempt${MAX_RETRIES}.log" >&2
|
||||
log " GATE $*: FAIL"
|
||||
return 1
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Shared preamble prepended to every worker prompt.
|
||||
# =============================================================================
|
||||
read -r -d '' SHARED <<'SHARED_EOF' || true
|
||||
You are building "Underdepths", a turn-based roguelike in Python 3 + pygame-ce.
|
||||
@plan.md is the COMPLETE design spec — READ IT before writing anything.
|
||||
AGENTS.md (auto-loaded) holds the project conventions; follow them.
|
||||
# ---------------------------------------------------------------------------
|
||||
# dispatch_fix <kind> <gate_error> : targeted fix dispatch with the real error.
|
||||
# ---------------------------------------------------------------------------
|
||||
dispatch_fix() {
|
||||
local kind="$1" err="$2"
|
||||
local prompt
|
||||
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
|
||||
module docstring defines the EXACT public API you must implement — dataclass
|
||||
fields, function names + signatures, return shapes. Implement to that API.
|
||||
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.
|
||||
Read tests/smoke.py: its module docstring is the API CONTRACT every module must
|
||||
match, and the phaseN() functions are the acceptance tests. Read AGENTS.md and
|
||||
plan.md for full design context.
|
||||
|
||||
HEADLESS RULE (getting this wrong fails the whole build): smoke.py sets
|
||||
SDL_VIDEODRIVER=dummy. In main.py NEVER force headless with
|
||||
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.
|
||||
FAILED GATE: python tests/smoke.py $kind
|
||||
Full gate output (stdout+stderr):
|
||||
|
||||
IMPLEMENTATION RULES:
|
||||
- @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
|
||||
$err
|
||||
|
||||
# =============================================================================
|
||||
# Phase 1 — Foundation
|
||||
# =============================================================================
|
||||
read -r -d '' P1 <<'P1_EOF' || true
|
||||
BUILD PHASE 1 — Foundation. Make `python3 tests/smoke.py --phase 1` print PASS.
|
||||
After fixing, run: python tests/smoke.py $kind
|
||||
Repeat until it prints PASS. Then stop. Do not touch unrelated files.
|
||||
EOF
|
||||
)"
|
||||
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
|
||||
TILE=20, MAP_WIDTH=80, MAP_HEIGHT=50, SIGHT_RADIUS=8, FLOORS=10
|
||||
COLORS / PALETTE dicts (wall dark gray ~ (60,60,70) visible / (30,30,35)
|
||||
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.
|
||||
phase1_build() {
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
entities/entity.py
|
||||
@dataclass(slots=True) Entity(x:int, y:int, name:str, sprite_key:str,
|
||||
blocks:bool=True).
|
||||
PHASE 1 — Foundation. Create these modules implementing the contract in
|
||||
tests/smoke.py:
|
||||
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
|
||||
@dataclass(slots=True) Player(Entity) with the base stats from plan
|
||||
(hp=50,max_hp=50,power=4,armor=0,accuracy=5,evasion=2,crit_chance=0.10,
|
||||
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.
|
||||
Verify before finishing: python tests/smoke.py --phase 1 (must print PASS)
|
||||
Also eyeball the ASCII render it prints — '>' must appear on a reachable floor tile.
|
||||
EOF
|
||||
)"
|
||||
}
|
||||
|
||||
entities/enemy.py
|
||||
@dataclass(slots=True) Enemy(Entity) with hp,max_hp,power,armor,accuracy,
|
||||
evasion,crit_chance,speed,behavior,xp_value, plus last_known_pos (tuple|None),
|
||||
act_counter:int=0, can_split:bool=True, ranged_power:int=0.
|
||||
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.
|
||||
phase2_build() {
|
||||
# Four independent systems, built SEQUENTIALLY (never parallel — shared files).
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
engine/map_gen.py
|
||||
@dataclass(slots=True) Rect(x,y,w,h) with a .center property returning (x+w//2,
|
||||
y+h//2). @dataclass(slots=True) GameMap(width,height,tiles,rooms,explored,
|
||||
visible,entities,stairs_down,floor_index) exactly per the contract docstring.
|
||||
generate_dungeon(floor_index,width=80,height=50)->GameMap using BSP: all walls,
|
||||
5-8 recursive splits alternating axis, carve a room (4x4..10x8, shrunk 1-2 from
|
||||
region edge) per leaf, connect siblings with L-shaped corridors, place stairs_down
|
||||
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,
|
||||
a solid 1-tile wall border on all four edges, no overlapping rooms, and every
|
||||
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.
|
||||
PHASE 2a — Field of View. Create engine/fov.py: recursive shadowcasting over 8
|
||||
octants, radius SIGHT_RADIUS=8. Function compute_fov(game_map, origin, radius=8)
|
||||
-> set[tuple[int,int]] of visible tiles. Walls block sight but are themselves
|
||||
visible when adjacent to a visible floor tile. Do NOT modify map_gen.py.
|
||||
Verify: python tests/smoke.py --phase 2 (it tests fov now; other phase-2 parts
|
||||
may still fail — that's fine, just don't break phase 1). Finish fov only.
|
||||
EOF
|
||||
)"
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
main.py
|
||||
A MINIMAL entry for now: define main(max_frames=None) that, when
|
||||
SDL_VIDEODRIVER==dummy, runs a tiny headless self-check (generate a dungeon,
|
||||
print nothing fatal) and returns; otherwise prints "Underdepths — phase 1
|
||||
scaffold". It will be FULLY rebuilt in phase 4. Obey the HEADLESS RULE.
|
||||
P1_EOF
|
||||
P1="$(printf '%s\n\n%s' "$SHARED" "$P1")"
|
||||
PHASE 2b — A* pathfinding. Create engine/pathfinding.py: grid A* with Manhattan
|
||||
heuristic. find_path(game_map, start, goal, blocked=frozenset()) ->
|
||||
list[tuple]|None. Path EXCLUDES start, INCLUDES goal, [] when start==goal, None
|
||||
when unreachable. Treat walls + the `blocked` set as impassable. Do NOT modify
|
||||
map_gen.py or fov.py. Verify: python tests/smoke.py --phase 2 (pathfinding
|
||||
assertions should pass).
|
||||
EOF
|
||||
)"
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
# =============================================================================
|
||||
# Phase 2 — Core systems (FOV, A*, combat, minimal game state, chase AI)
|
||||
# =============================================================================
|
||||
read -r -d '' P2 <<'P2_EOF' || true
|
||||
BUILD PHASE 2 — Core systems. Make `python3 tests/smoke.py --phase 2` print PASS.
|
||||
Do NOT regress phase 1 (re-run --phase 1 if unsure).
|
||||
PHASE 2c — Combat. Create engine/combat.py: @dataclass AttackRoll(hit,crit,
|
||||
damage) and roll_attack(attacker, defender, rng=random)->AttackRoll. Read
|
||||
.accuracy .evasion .power .armor .crit_chance (+optional .weapon_power) off the
|
||||
arguments (duck-typed). Formulas from plan.md:
|
||||
hit_chance = clamp(0.7 + (atk.accuracy - def.evasion)*0.05, 0.1, 0.95)
|
||||
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
|
||||
compute_fov(game_map, ox, oy, radius=8) -> set of (x,y) visible tiles, using
|
||||
RECURSIVE SHADOWCASTING over 8 octants (write it from scratch, no library).
|
||||
Walls block sight but a wall adjacent to a visible floor tile is itself
|
||||
visible. Mutate game_map.visible accordingly and RETURN the visible set.
|
||||
PHASE 2d — Enemy AI. Create ai/behaviors.py: act_enemy(enemy, game_map, player,
|
||||
visible:set, rng)->None. Dispatch on enemy.behavior: wander / chase (A* toward
|
||||
player when in `visible`, else last_known_pos; adjacent=>melee via combat) /
|
||||
flee (hp<30% => move away) / ranged (shoot/kite per plan) / phase (move toward
|
||||
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
|
||||
astar(game_map, start, goal, blocked=frozenset()) -> list[(x,y)] | None, grid
|
||||
A* with Manhattan heuristic. Walkable = in-bounds floor tile not in `blocked`
|
||||
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.
|
||||
phase3_build() {
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
engine/combat.py
|
||||
attack(attacker, defender, rng=None, log=None) -> dict with keys
|
||||
hit:bool, damage:int, crit:bool, killed:bool. Use plan's formulas:
|
||||
hit_chance = clamp(0.7 + (attacker.accuracy - defender.evasion)*0.05, 0.1, 0.95);
|
||||
on hit, base = attacker.power(+weapon bonus via total_power for the player),
|
||||
reduced = max(0, base - defender.armor), crit doubles damage, apply to
|
||||
defender.hp, killed = defender.hp <= 0. If log is a list, append the plan's
|
||||
human messages ("You hit the Goblin for 8 damage!", "Critical hit! ...",
|
||||
"Goblin misses you"). The attacker may be Player (use total_power/total_armor)
|
||||
or Enemy (use raw stats). rng defaults to random.Random().
|
||||
PHASE 3 — Content. Create/flesh out:
|
||||
data/enemies.py ENEMY_DEFS dict + make_enemy(kind,x,y)->Enemy. Kinds:
|
||||
rat,goblin,skeleton_archer,orc_warrior,wraith,green_slime,
|
||||
ancient_dragon,small_slime. Stats EXACTLY per plan.md Enemy
|
||||
Roster (hp/power/armor/speed/behavior/xp). green_slime
|
||||
can_split=True. ancient_dragon armor 8 hp 120 power 15.
|
||||
data/items.py ITEM_DEFS dict + make_item(kind,x,y)->Item. Catalog per
|
||||
plan.md: rusty_dagger..war_hammer, leather/chain/plate
|
||||
armor, healing/strength/invisibility potions, fireball/
|
||||
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
|
||||
@dataclass(slots=True) GameSession holding player, dungeon (list of 10
|
||||
GameMap), current_floor:int, log:list[str], turn:int, state:str
|
||||
("playing"/"dead"/"victory"/"menu"), plus an rng. new_game(seed=None)->
|
||||
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.)
|
||||
phase4_build() {
|
||||
# Large phase — split into sequential sub-builds BEFORE the single phase gate.
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
ai/behaviors.py
|
||||
take_enemy_turn(enemy, session, rng=None) dispatching on enemy.behavior.
|
||||
Implement at least: wander (random walkable step or wait), chase (A* toward
|
||||
player when player visible via FOV, else toward last_known_pos; adjacent ->
|
||||
melee via combat.attack into session.log), and a stub for the others (you will
|
||||
finish flee/ranged/phase/split in phase 3). Respect speed (speed==2 acts every
|
||||
other turn via act_counter). Enemies must not stack (treat other entities as
|
||||
blocked). Update last_known_pos when the player is visible.
|
||||
P2_EOF
|
||||
P2="$(printf '%s\n\n%s' "$SHARED" "$P2")"
|
||||
PHASE 4a — State + persistence. engine/game_state.py: full GameSession
|
||||
(player,dungeon,current_floor,log,turn,state) + new_session(seed)->GameSession
|
||||
that generates all 10 floors, places the player at floor-0 spawn, state='menu'/
|
||||
'playing'. engine/serializers.py: session_to_dict(session)->dict and
|
||||
session_from_dict(d)->GameSession (JSON-safe). Persist player (stats, level, xp,
|
||||
inventory, equipped, effect_timers, position), all 10 floors (tiles, explored,
|
||||
entities, stairs_down, spawn), current_floor, turn, log. Do NOT serialize the
|
||||
volatile `visible` grid (recomputed from FOV on load). Verify with a quick
|
||||
python -c round-trip; do not break earlier phases.
|
||||
EOF
|
||||
)"
|
||||
run_dispatch "$(cat <<EOF
|
||||
$P_COMMON
|
||||
|
||||
# =============================================================================
|
||||
# Phase 3 — Content: items, inventory, equipment, scrolls, full AI, XP wiring
|
||||
# =============================================================================
|
||||
read -r -d '' P3 <<'P3_EOF' || true
|
||||
BUILD PHASE 3 — Content layer. Make `python3 tests/smoke.py --phase 3` pass.
|
||||
Do NOT regress phases 1-2.
|
||||
PHASE 4b — Actions + audio + main loop. engine/actions.py: apply_input(session,
|
||||
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;
|
||||
after the player acts, advance enemies via ai.behaviors + log messages), 'g'
|
||||
(pick up item under player into inventory), 'f' (descend ONLY if player stands
|
||||
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
|
||||
@dataclass(slots=True) Item(Entity) with item_type ("weapon"/"armor"/
|
||||
"potion"/"scroll"), subtype (e.g. "healing","strength","invisibility",
|
||||
"fireball","teleport","mapping"), stats:dict, name, sprite_key.
|
||||
make_item(name,x,y)->Item implementing the FULL catalog from plan: Rusty
|
||||
Dagger(+2), Short Sword(+4), Battle Axe(+7), War Hammer(+10 power, crit -5%),
|
||||
Leather Armor(armor 2), Chain Mail(armor 4), Plate Armor(armor 7, evasion -10%),
|
||||
Healing Potion(heal 30), Strength Potion(+5 power/20 turns), Invisibility
|
||||
Potion(invisible/15 turns), Scroll of Fireball(20 dmg radius 3), Scroll of
|
||||
Teleport, Scroll of Mapping. Player.total_power/total_armor must read the
|
||||
equipped weapon/armor stats.
|
||||
PHASE 4c — Rendering (procedural pixel-art). data/sprites.py: 2D palette-key
|
||||
grids per entity/tile/item (12x12..16x16). render/sprites.py: get_sprite(name)
|
||||
-> cached pygame.Surface, rasterized once via pygame.draw from the grids —
|
||||
MUST include a 'stairs' sprite that is DISTINCT, non-empty, and glowing YELLOW
|
||||
(R>120,G>100,B<110), plus distinct sprites for player + all 7 enemies + items.
|
||||
render/renderer.py: Renderer.render(surface, session, camera_xy=(0,0)) draws
|
||||
map tiles + entities + items, and MUST blit the 'stairs' sprite on EVERY
|
||||
stairs_down tile (invisible stairs make the game unwinnable — a build failure).
|
||||
render/effects.py: radial torch-light from player (SIGHT_RADIUS falloff),
|
||||
explored-but-not-visible tiles dimmed, wall occlusion, screen vignette, particle
|
||||
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
|
||||
(combat.attack player->enemy, log, award XP + handle death/split, check win);
|
||||
else move player if walkable & unblocked; then advance enemy turns + recompute
|
||||
FOV + tick effect timers. Return whether the player acted.
|
||||
pickup(session)->bool: if an Item is under the player, move it to inventory
|
||||
(or auto-consume potions? NO — into inventory), log "You pick up X", return True.
|
||||
descend(session)->bool: if player on stairs_down, current_floor+=1, place
|
||||
player at that floor's spawn/first room center, recompute FOV, log descent.
|
||||
Return False if not on stairs or already on floor 9 (no stairs there pre-win).
|
||||
use_item(session, item): potions -> apply effect (heal capped at max_hp;
|
||||
strength/invisibility push a timed Effect into player.effects), scrolls ->
|
||||
fireball (20 dmg to all enemies within 3 of player), teleport (random walkable
|
||||
tile), mapping (set entire current floor explored True); consume (remove from
|
||||
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".
|
||||
# ---------------------------------------------------------------------------
|
||||
# run_phase <n> : attempt-1 build dispatches, then gate->fix Ralph loop.
|
||||
# Returns 0 on gate PASS, 1 after MAX_RETRIES exhausted.
|
||||
# ---------------------------------------------------------------------------
|
||||
run_phase() {
|
||||
local n=$1
|
||||
log "===== PHASE $n: build (attempt 1) ====="
|
||||
case "$n" in
|
||||
1) phase1_build ;;
|
||||
2) phase2_build ;;
|
||||
3) phase3_build ;;
|
||||
4) phase4_build ;;
|
||||
*) log "unknown phase $n"; return 1 ;;
|
||||
esac
|
||||
|
||||
ai/behaviors.py (COMPLETE the behavior set)
|
||||
Finish flee (HP<30% -> move away, else chase), ranged/kiting (skeleton archer:
|
||||
fire ranged_attack at range>3 using ranged_power with a distance penalty;
|
||||
step away when adjacent <=2; wander when no sight), phase (wraith: move toward
|
||||
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
|
||||
local attempt
|
||||
for attempt in $(seq 1 "$MAX_RETRIES"); do
|
||||
if run_gate --phase "$n"; then
|
||||
return 0
|
||||
fi
|
||||
s="$(get_state)"
|
||||
if (( s < 5 )); then dispatch goal-backstop "$PGOAL" "$GATE --goal" && set_state 5 || halt; fi
|
||||
if [ "$attempt" -lt "$MAX_RETRIES" ]; then
|
||||
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 "==================================================================="
|
||||
echo "BUILD COMPLETE — all phase gates + goal backstop PASS."
|
||||
echo "Play it: python3 main.py"
|
||||
echo "Verify: python3 tests/smoke.py --goal"
|
||||
echo "==================================================================="
|
||||
# ---------------------------------------------------------------------------
|
||||
# Goal backstop: after all 4 phases, verify EVERY acceptance criterion headlessly.
|
||||
# ---------------------------------------------------------------------------
|
||||
goal_loop() {
|
||||
log "===== GOAL BACKSTOP ====="
|
||||
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 "$@"
|
||||
@@ -75,7 +75,7 @@ class GameMap:
|
||||
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).
|
||||
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).
|
||||
|
||||
**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).
|
||||
|
||||
### 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)
|
||||
|
||||
**Algorithm: Recursive Shadowcasting** (8 octants).
|
||||
@@ -333,7 +342,7 @@ feel.
|
||||
- **Ancient Dragon:** large multi-hue red boss — horns, spread wings, scales, fangs.
|
||||
- **Items:** pixel-art icons (weapon, armor, potion flask, scroll) with the
|
||||
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
|
||||
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.
|
||||
@@ -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
|
||||
- [ ] 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
|
||||
- [ ] 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)
|
||||
- [ ] **A* pathfinding** — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you.
|
||||
|
||||
@@ -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
|
||||
stairs and press `f`, level up, save, quit, relaunch, and continue
|
||||
— 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.
|
||||
Build the game.
|
||||
@@ -0,0 +1 @@
|
||||
"""Rendering package: pure read-and-draw of GameSession."""
|
||||
@@ -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
|
||||
|
||||
import math
|
||||
from data.constants import MAP_W, MAP_H, TILE
|
||||
|
||||
|
||||
class Camera:
|
||||
"""Pixel-space camera top-left. Eases toward its target; can snap."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, smoothing: float = 0.18) -> None:
|
||||
self.x: float = 0.0
|
||||
self.y: float = 0.0
|
||||
self._tx: float = 0.0
|
||||
self._ty: float = 0.0
|
||||
self.smoothing = max(0.0, min(1.0, smoothing))
|
||||
|
||||
def set_target(self, px: float, py: float) -> None:
|
||||
self._tx = px
|
||||
self._ty = py
|
||||
def reset(self, player_xy: tuple[int, int]) -> None:
|
||||
self.x = float(player_xy[0] * TILE)
|
||||
self.y = float(player_xy[1] * TILE)
|
||||
|
||||
def snap(self, px: float, py: float) -> None:
|
||||
self.x = self._tx = px
|
||||
self.y = self._ty = py
|
||||
def update(self, player_xy: tuple[int, int]) -> tuple[int, int]:
|
||||
tx = player_xy[0] * TILE
|
||||
ty = player_xy[1] * TILE
|
||||
self.x += (tx - self.x) * self.smoothing
|
||||
self.y += (ty - self.y) * self.smoothing
|
||||
return int(self.x), int(self.y)
|
||||
|
||||
def update(self, dt: float, ease: float = 7.0) -> None:
|
||||
k = 1.0 - math.exp(-ease * dt)
|
||||
self.x += (self._tx - self.x) * k
|
||||
self.y += (self._ty - self.y) * k
|
||||
def offset_for(self, surface_wh: tuple[int, int], player_xy: tuple[int, int]) -> tuple[int, int]:
|
||||
"""Center the player on screen, clamped to the map bounds (pixel offset)."""
|
||||
sw, sh = surface_wh
|
||||
px = int(self.x)
|
||||
py = int(self.y)
|
||||
ox = px - sw // 2
|
||||
oy = py - sh // 2
|
||||
max_ox = MAP_W * TILE - sw
|
||||
max_oy = MAP_H * TILE - sh
|
||||
if max_ox <= 0:
|
||||
ox = (MAP_W * TILE - sw) // 2
|
||||
else:
|
||||
ox = max(0, min(max_ox, ox))
|
||||
if max_oy <= 0:
|
||||
oy = (MAP_H * TILE - sh) // 2
|
||||
else:
|
||||
oy = max(0, min(max_oy, oy))
|
||||
return ox, oy
|
||||
@@ -1,181 +1,124 @@
|
||||
"""Procedural visual effects: particles, floating combat text, screen shake,
|
||||
lighting helpers (torch falloff, vignette). All drawn from state; none mutate it.
|
||||
"""Render-only effects: screen-shake, particles, and a vignette.
|
||||
|
||||
All state here is view state owned by the Renderer instance, never game state.
|
||||
Lighting (visible bright / explored dimmed / unexplored black + radial falloff)
|
||||
is applied per-tile inside ``renderer``; this module supplies the juice and the
|
||||
edge-darkening vignette overlay.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
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:
|
||||
def __init__(self, cap: int = 260) -> None:
|
||||
self._pool: list[dict] = []
|
||||
self._cap = cap
|
||||
"""Pooled, capped particle bursts (hit sparks, blood, level-up stars, etc.)."""
|
||||
|
||||
def clear(self) -> None:
|
||||
self._pool.clear()
|
||||
def __init__(self) -> None:
|
||||
self._parts: list[dict[str, Any]] = []
|
||||
|
||||
def burst(self, x: float, y: float, color, n: int = 10, speed: float = 70.0,
|
||||
life: float = 0.45, gravity: float = 0.0, size: int = 2) -> None:
|
||||
for _ in range(n):
|
||||
if len(self._pool) >= self._cap:
|
||||
self._pool.pop(0)
|
||||
ang = random.random() * math.tau
|
||||
spd = random.uniform(speed * 0.25, speed)
|
||||
self._pool.append(dict(
|
||||
x=x, y=y, vx=math.cos(ang) * spd, vy=math.sin(ang) * spd,
|
||||
life=life, max=life, color=color, g=gravity, size=size))
|
||||
def burst(self, x: float, y: float, color: tuple[int, int, int],
|
||||
count: int = 10, speed: float = 60.0, life: float = 0.4) -> None:
|
||||
for _ in range(count):
|
||||
if len(self._parts) >= _MAX_PARTICLES:
|
||||
break
|
||||
ang = random.uniform(0, math.tau)
|
||||
spd = speed * random.uniform(0.4, 1.0)
|
||||
self._parts.append({
|
||||
"x": x, "y": y,
|
||||
"vx": math.cos(ang) * spd, "vy": math.sin(ang) * spd,
|
||||
"life": life * random.uniform(0.7, 1.2), "age": 0.0,
|
||||
"color": color, "size": random.randint(2, 3),
|
||||
})
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
drag = max(0.0, 1.0 - 2.2 * dt)
|
||||
for p in self._pool:
|
||||
p["life"] -= dt
|
||||
if p["life"] <= 0:
|
||||
alive: list[dict[str, Any]] = []
|
||||
for p in self._parts:
|
||||
p["age"] += dt
|
||||
if p["age"] >= p["life"]:
|
||||
continue
|
||||
p["x"] += p["vx"] * dt
|
||||
p["y"] += p["vy"] * dt
|
||||
p["vy"] += p["g"] * dt
|
||||
p["vx"] *= drag
|
||||
p["vy"] *= drag
|
||||
out.append(p)
|
||||
self._pool = out
|
||||
p["vy"] += 90.0 * dt # gentle gravity
|
||||
alive.append(p)
|
||||
self._parts = alive
|
||||
|
||||
def draw(self, surf, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for p in self._pool:
|
||||
frac = max(0.0, p["life"] / p["max"])
|
||||
a = max(0, min(255, int(255 * frac)))
|
||||
r = max(1, int(p["size"] * (0.6 + 0.4 * frac)))
|
||||
sx = int(p["x"] - cam[0])
|
||||
sy = int(p["y"] - cam[1])
|
||||
if -8 <= sx <= surf.get_width() + 8 and -8 <= sy <= surf.get_height() + 8:
|
||||
s = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
|
||||
pygame.draw.rect(s, (*p["color"], a), (0, 0, r * 2, r * 2))
|
||||
surf.blit(s, (sx - r, sy - r))
|
||||
def draw(self, surface: pygame.Surface, cam_xy: tuple[int, int]) -> None:
|
||||
ox, oy = cam_xy
|
||||
for p in self._parts:
|
||||
t = 1.0 - p["age"] / p["life"]
|
||||
r = max(1, int(p["size"] * t))
|
||||
c = p["color"]
|
||||
col = (int(c[0] * t), int(c[1] * t), int(c[2] * t))
|
||||
pygame.draw.circle(surface, col, (int(p["x"] - ox), int(p["y"] - oy)), r)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Floating combat text.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class FloatText:
|
||||
def __init__(self) -> None:
|
||||
self._items: list[dict] = []
|
||||
|
||||
def clear(self) -> None:
|
||||
self._items.clear()
|
||||
|
||||
def add(self, x: float, y: float, text: str, color, big: bool = False) -> None:
|
||||
self._items.append(dict(
|
||||
x=x, y=y, text=text, color=color, life=0.95, max=0.95,
|
||||
vy=-30.0, big=big))
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
for it in self._items:
|
||||
it["life"] -= dt
|
||||
if it["life"] <= 0:
|
||||
continue
|
||||
it["y"] += it["vy"] * dt
|
||||
it["vy"] *= max(0.0, 1.0 - 1.6 * dt)
|
||||
out.append(it)
|
||||
self._items = out
|
||||
|
||||
def draw(self, surf, font, font_big, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for it in self._items:
|
||||
frac = max(0.0, it["life"] / it["max"])
|
||||
a = max(0, min(255, int(255 * (frac ** 0.6))))
|
||||
f = font_big if it["big"] else font
|
||||
txt = f.render(it["text"], True, it["color"])
|
||||
txt.set_alpha(a)
|
||||
surf.blit(txt, (int(it["x"] - cam[0] - txt.get_width() // 2),
|
||||
int(it["y"] - cam[1])))
|
||||
def vignette(size: tuple[int, int]) -> pygame.Surface:
|
||||
"""Soft edge-darkening overlay (cached by size via module dict)."""
|
||||
key = size
|
||||
surf = _VIGNETTE_CACHE.get(key)
|
||||
if surf is not None:
|
||||
return surf
|
||||
w, h = size
|
||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
||||
cx, cy = w / 2, h / 2
|
||||
max_d = math.hypot(cx, cy)
|
||||
# Subtle edge-only vignette: concentric non-overlapping annuli (width=step)
|
||||
# so alpha never accumulates. Only the outer ~38% of the screen darkens; the
|
||||
# center stays clear. Max alpha is gentle so edges are never crushed to black.
|
||||
step = 8
|
||||
inner_t = 0.62 # no darkening inside 62% of the corner distance
|
||||
max_alpha = 78
|
||||
r = int(max_d)
|
||||
while r > 0:
|
||||
t = r / max_d
|
||||
if t > inner_t:
|
||||
u = (t - inner_t) / (1.0 - inner_t)
|
||||
alpha = int(max_alpha * u * u)
|
||||
if alpha > 0:
|
||||
pygame.draw.circle(surf, (0, 0, 0, alpha), (int(cx), int(cy)), r, step)
|
||||
r -= step
|
||||
_VIGNETTE_CACHE[key] = surf
|
||||
return surf
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 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))
|
||||
_VIGNETTE_CACHE: dict[tuple[int, int], pygame.Surface] = {}
|
||||
@@ -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):
|
||||
+---------------------------------------------+----
|
||||
| TOP BAR floor | HP bar | level | XP bar | } SIDE panel
|
||||
+---------------------------------------------+ ) (log)
|
||||
| | )
|
||||
| MAP VIEWPORT (camera follows player)| )
|
||||
| | )
|
||||
+---------------------------------------------+----
|
||||
| BOTTOM BAR equipment | effects | sound | prompt|
|
||||
+---------------------------------------------+
|
||||
Reads ``GameSession`` and draws — never mutates game state. Visibility for
|
||||
lighting is DERIVED here via FOV (read-only) so a freshly-built session renders
|
||||
correctly even before the action layer has ticked. Stairs are ALWAYS blitted on
|
||||
``stairs_down`` when in view/remembered (invisible stairs make the game
|
||||
unwinnable).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import math
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
from data import constants as C
|
||||
from data import sprites as S
|
||||
from render import sprites as RS
|
||||
from render.camera import Camera
|
||||
from render.effects import (
|
||||
FloatText, Particles, Shake, make_torch, make_vignette, torch_factor,
|
||||
from data.constants import (
|
||||
TILE, SIGHT_RADIUS, COLORS, MAP_W, MAP_H,
|
||||
)
|
||||
from engine.fov import compute_fov
|
||||
from render.sprites import get_tile_sprite
|
||||
from render.effects import Particles, Shake, vignette, torch_factor
|
||||
|
||||
TILE: int = C.TILE
|
||||
VIEW_TW: int = 48
|
||||
VIEW_TH: int = 28
|
||||
MAP_W_PX: int = VIEW_TW * TILE
|
||||
MAP_H_PX: int = VIEW_TH * TILE
|
||||
TOP_H: int = 34
|
||||
BOT_H: int = 50
|
||||
SIDE_W: int = 230
|
||||
WIN_W: int = MAP_W_PX + SIDE_W
|
||||
WIN_H: int = TOP_H + MAP_H_PX + BOT_H
|
||||
MAP_X: int = 0
|
||||
MAP_Y: int = TOP_H
|
||||
|
||||
COL = C.COLORS
|
||||
WALL_V = COL["wall_visible"]
|
||||
WALL_E = COL["wall_explored"]
|
||||
FLOOR_V = COL["floor_visible"]
|
||||
FLOOR_E = COL["floor_explored"]
|
||||
VOID = COL["void"]
|
||||
_BG = COLORS["bg"]
|
||||
_FONT_STACK = "monospace,consolas,couriernew,dejavusans"
|
||||
# Sprites rendered larger than one tile (centered on their tile).
|
||||
_BIG_SPRITES = frozenset({"ancient_dragon"})
|
||||
|
||||
|
||||
def _shade(color, f: float):
|
||||
return (max(0, min(255, int(color[0] * f))),
|
||||
max(0, min(255, int(color[1] * f))),
|
||||
max(0, min(255, int(color[2] * f))))
|
||||
def _dim(color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
|
||||
return (int(color[0] * factor), int(color[1] * factor), int(color[2] * factor))
|
||||
|
||||
|
||||
def _hash(tx: int, ty: int) -> float:
|
||||
n = (tx * 73856093) ^ (ty * 19349663)
|
||||
n = (n ^ (n >> 13)) * 1274126177 & 0xFFFFFFFF
|
||||
n = (n ^ (n >> 16)) & 0xFFFFFFFF
|
||||
return n / 0xFFFFFFFF
|
||||
|
||||
|
||||
def _log_color(line: str):
|
||||
low = line.lower()
|
||||
if any(k in low for k in ("level", "defeated", "conquered", "slew")):
|
||||
return COL["log_levelup"]
|
||||
if any(k in low for k in ("you", "miss")) and "miss" in low and "you miss" in low:
|
||||
return COL["log_miss"]
|
||||
if any(k in low for k in ("hits you", "damage", "died", "burn", "critically", "shoots")):
|
||||
return COL["log_damage"]
|
||||
if any(k in low for k in ("pick up", "equip", "unequip", "quaff", "scroll", "potion",
|
||||
"teleport", "map", "surge", "fade")):
|
||||
return COL["log_item"]
|
||||
if "miss" in low:
|
||||
return COL["log_miss"]
|
||||
return COL["log_combat"]
|
||||
|
||||
|
||||
# armor sprite_key -> pauldron color cue shown on the player
|
||||
_ARMOR_TINT = {
|
||||
"armor_leather": COL["floor_visible"],
|
||||
"armor_chain": COL["armor"],
|
||||
"armor_plate": (210, 210, 220),
|
||||
}
|
||||
def _hash2(x: int, y: int) -> int:
|
||||
return (x * 73856093 ^ y * 19349663) & 0xFF
|
||||
|
||||
|
||||
class Renderer:
|
||||
def __init__(self, size, audio) -> None:
|
||||
self.W, self.H = size
|
||||
self.audio = audio
|
||||
self.cam = Camera()
|
||||
def __init__(self) -> None:
|
||||
self.particles = Particles()
|
||||
self.floats = FloatText()
|
||||
self.shake = Shake()
|
||||
self._dt = 0.0
|
||||
self._cam_world = (0.0, 0.0)
|
||||
self._fx_cam = (0.0, 0.0)
|
||||
fname = "dejavusans,arial,helvetica,sans"
|
||||
self.font = pygame.font.SysFont(fname, 13)
|
||||
self.font_s = pygame.font.SysFont(fname, 11)
|
||||
self.font_b = pygame.font.SysFont(fname, 15, bold=True)
|
||||
self.font_l = pygame.font.SysFont(fname, 30, bold=True)
|
||||
self.font_xl = pygame.font.SysFont(fname, 46, bold=True)
|
||||
self.vignette = make_vignette(MAP_W_PX, MAP_H_PX)
|
||||
self.torch = make_torch(C.SIGHT_RADIUS * TILE)
|
||||
self._anim = 0.0
|
||||
self._last_hp: int | None = None
|
||||
self._last_log_len = 0
|
||||
self._font_big: pygame.font.Font | None = None
|
||||
self._font_small: pygame.font.Font | None = None
|
||||
self._font: pygame.font.Font | None = None
|
||||
self._fonts_ok = True
|
||||
self._torch: pygame.Surface | None = None
|
||||
self._glow_surf: pygame.Surface | None = None
|
||||
self._shadow_cache: dict[int, pygame.Surface] = {}
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
def update(self, dt: float) -> None:
|
||||
self._dt = max(0.001, dt)
|
||||
self.particles.update(dt)
|
||||
self.floats.update(dt)
|
||||
# --------------------------------------------------------------- fonts
|
||||
def _fonts(self) -> None:
|
||||
if not self._fonts_ok or self._font is not None:
|
||||
return
|
||||
try:
|
||||
self._font = pygame.font.SysFont(_FONT_STACK, 16, bold=True)
|
||||
self._font_big = pygame.font.SysFont(_FONT_STACK, 22, bold=True)
|
||||
self._font_small = pygame.font.SysFont(_FONT_STACK, 13, bold=True)
|
||||
except Exception:
|
||||
self._fonts_ok = False
|
||||
|
||||
def world_px(self, tx: int, ty: int):
|
||||
"""Screen-pixel center of a world tile (for spawning effects)."""
|
||||
cx, cy = self._cam_world
|
||||
wx = tx * TILE + TILE / 2
|
||||
wy = ty * TILE + TILE / 2
|
||||
return (wx - cx + MAP_X, wy - cy + MAP_Y)
|
||||
def _text(self, surf: pygame.Surface, msg: str, pos: tuple[int, int],
|
||||
color: tuple[int, int, int], big: bool = False,
|
||||
small: bool = False) -> None:
|
||||
if self._font is None:
|
||||
return
|
||||
f = self._font_big if big else (self._font_small if small else self._font)
|
||||
try:
|
||||
img = f.render(msg, True, color)
|
||||
surf.blit(img, pos)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# World
|
||||
# ------------------------------------------------------------------ #
|
||||
def render_world(self, screen, session, t: float) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
map_pw = C.MAP_WIDTH * TILE
|
||||
map_ph = C.MAP_HEIGHT * TILE
|
||||
# --------------------------------------------------------------- entry
|
||||
def render(self, surface: pygame.Surface, session: Any,
|
||||
camera_xy: tuple[int, int] = (0, 0)) -> None:
|
||||
self._fonts()
|
||||
self._anim += 0.016
|
||||
self.particles.update(0.016)
|
||||
|
||||
tgt_x = p.x * TILE + TILE / 2 - MAP_W_PX / 2
|
||||
tgt_y = p.y * TILE + TILE / 2 - MAP_H_PX / 2
|
||||
tgt_x = max(0.0, min(tgt_x, max(0.0, map_pw - MAP_W_PX)))
|
||||
tgt_y = max(0.0, min(tgt_y, max(0.0, map_ph - MAP_H_PX)))
|
||||
if self.cam.x == 0.0 and self.cam.y == 0.0:
|
||||
self.cam.snap(tgt_x, tgt_y)
|
||||
self.cam.set_target(tgt_x, tgt_y)
|
||||
self.cam.update(self._dt)
|
||||
self.shake.update(self._dt)
|
||||
sox, soy = self.shake.offset()
|
||||
cx, cy = self.cam.x, self.cam.y
|
||||
self._cam_world = (cx - sox, cy - soy)
|
||||
self._fx_cam = (cx - sox, cy - soy - MAP_Y)
|
||||
gm = session.dungeon[session.current_floor]
|
||||
player = session.player
|
||||
vis = compute_fov(gm, (player.x, player.y), SIGHT_RADIUS)
|
||||
|
||||
screen.fill(VOID)
|
||||
vis = floor.visible
|
||||
expl = floor.explored
|
||||
tx0 = max(0, int(cx // TILE) - 1)
|
||||
tx1 = min(C.MAP_WIDTH - 1, int((cx + MAP_W_PX) // TILE) + 1)
|
||||
ty0 = max(0, int(cy // TILE) - 1)
|
||||
ty1 = min(C.MAP_HEIGHT - 1, int((cy + MAP_H_PX) // TILE) + 1)
|
||||
px, py = p.x, p.y
|
||||
for ty in range(ty0, ty1 + 1):
|
||||
row_v = vis[ty]
|
||||
row_e = expl[ty]
|
||||
row_t = floor.tiles[ty]
|
||||
sy = round(ty * TILE - cy + soy) + MAP_Y
|
||||
for tx in range(tx0, tx1 + 1):
|
||||
if not row_e[tx] and not row_v[tx]:
|
||||
cam_x, cam_y = camera_xy
|
||||
sh_x, sh_y = self.shake.offset()
|
||||
ox, oy = cam_x - sh_x, cam_y - sh_y
|
||||
sw, sh = surface.get_size()
|
||||
|
||||
surface.fill(_BG)
|
||||
|
||||
x0 = max(0, ox // TILE)
|
||||
y0 = max(0, oy // TILE)
|
||||
x1 = min(gm.width, (ox + sw) // TILE + 1)
|
||||
y1 = min(gm.height, (oy + sh) // TILE + 1)
|
||||
|
||||
# Visible terrain/entities are drawn to a light layer at FULL brightness,
|
||||
# then a smooth radial torch gradient is multiplied in. That gives a soft
|
||||
# circular falloff with no tile-sized banding. Explored-but-unseen tiles
|
||||
# are drawn dim (cool blue-gray) straight onto the surface; unexplored
|
||||
# stays black. Walls occlude because only FOV-visible tiles reach the
|
||||
# light layer.
|
||||
light = pygame.Surface((sw, sh), pygame.SRCALPHA)
|
||||
|
||||
# ---- terrain ----
|
||||
for ty in range(y0, y1):
|
||||
for tx in range(x0, x1):
|
||||
px, py = tx * TILE - ox, ty * TILE - oy
|
||||
visible = (tx, ty) in vis
|
||||
explored = gm.explored[ty][tx]
|
||||
if not (visible or explored):
|
||||
continue
|
||||
sx = round(tx * TILE - cx + sox) + MAP_X
|
||||
if row_v[tx]:
|
||||
light = torch_factor(math.hypot(tx - px, ty - py), C.SIGHT_RADIUS)
|
||||
if row_t[tx] == 0:
|
||||
self._wall(screen, sx, sy, tx, ty, light)
|
||||
is_wall = not gm.walkable(tx, ty)
|
||||
if visible:
|
||||
if is_wall:
|
||||
self._wall(light, px, py, tx, ty, 1.0)
|
||||
else:
|
||||
self._floor(screen, sx, sy, tx, ty, light)
|
||||
self._floor(light, px, py, tx, ty, 1.0)
|
||||
else:
|
||||
col = WALL_E if row_t[tx] == 0 else FLOOR_E
|
||||
pygame.draw.rect(screen, col, (sx, sy, TILE, TILE))
|
||||
if row_t[tx] == 0:
|
||||
pygame.draw.rect(screen, _shade(col, 0.7), (sx, sy + TILE - 3, TILE, 3))
|
||||
if is_wall:
|
||||
self._wall_explored(surface, px, py, tx, ty)
|
||||
else:
|
||||
self._floor_explored(surface, px, py, tx, ty)
|
||||
if (tx, ty) == gm.stairs_down:
|
||||
target = light if visible else surface
|
||||
gsh = self._shadow_surf(TILE)
|
||||
target.blit(gsh, (px + (TILE - gsh.get_width()) // 2,
|
||||
py + TILE - gsh.get_height()))
|
||||
target.blit(get_tile_sprite("stairs"), (px, py))
|
||||
|
||||
if self.torch is not None:
|
||||
ts = self.torch.get_width()
|
||||
gx = round(px * TILE + TILE / 2 - (cx - sox)) + MAP_X - ts // 2
|
||||
gy = round(py * TILE + TILE / 2 - (cy - soy)) + MAP_Y - ts // 2
|
||||
screen.blit(self.torch, (gx, gy), special_flags=pygame.BLEND_RGB_ADD)
|
||||
# ---- entities (items under, enemies over, player on top) ----
|
||||
for e in gm.entities:
|
||||
if self._is_item(e):
|
||||
if (e.x, e.y) in vis:
|
||||
self._draw_entity(light, e, ox, oy, shadow=True)
|
||||
elif gm.explored[e.y][e.x]:
|
||||
self._draw_entity(surface, e, ox, oy, shadow=True)
|
||||
for e in gm.entities:
|
||||
if self._is_enemy(e) and (e.x, e.y) in vis:
|
||||
self._draw_entity(light, e, ox, oy, shadow=True)
|
||||
# player is always on-screen
|
||||
self._draw_entity(light, player, ox, oy, shadow=True, is_player=True)
|
||||
# keep the descent discoverable: when a sprite stands on the stairs, draw
|
||||
# a translucent yellow '>' peek on top so the staircase is never hidden.
|
||||
if gm.stairs_down is not None:
|
||||
ssx, ssy = gm.stairs_down
|
||||
on_stairs = (player.x, player.y) == (ssx, ssy) or any(
|
||||
getattr(e, "x", -9) == ssx and getattr(e, "y", -9) == ssy for e in gm.entities)
|
||||
if on_stairs and (ssx, ssy) in vis:
|
||||
_peek = get_tile_sprite("stairs").copy()
|
||||
_peek.set_alpha(150)
|
||||
light.blit(_peek, (ssx * TILE - ox, ssy * TILE - oy))
|
||||
|
||||
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:
|
||||
screen.blit(self.vignette, (MAP_X, MAP_Y))
|
||||
self.particles.draw(surface, (ox, oy))
|
||||
self._sense_events(session, vis, ox, oy)
|
||||
surface.blit(vignette((sw, sh)), (0, 0))
|
||||
self._ui(surface, session, sw, sh)
|
||||
|
||||
self.particles.draw(screen, self._fx_cam)
|
||||
self.floats.draw(screen, self.font_s, self.font_b, self._fx_cam)
|
||||
# --------------------------------------------------------------- tiles
|
||||
def _floor(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
|
||||
f: float) -> None:
|
||||
base = _dim(COLORS["floor_visible"], f)
|
||||
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
|
||||
h = _hash2(tx, ty)
|
||||
fleck = _dim(COLORS["floor_explored"], f)
|
||||
# two deterministic flecks per tile for subtle texture
|
||||
fx = px + (h % (TILE - 4)) + 2
|
||||
fy = py + ((h >> 3) % (TILE - 4)) + 2
|
||||
pygame.draw.rect(surf, fleck, (fx, fy, 2, 2))
|
||||
fx2 = px + ((h >> 2) % (TILE - 4)) + 2
|
||||
fy2 = py + ((h >> 5) % (TILE - 4)) + 2
|
||||
pygame.draw.rect(surf, _dim(COLORS["floor_visible"], f * 1.15), (fx2, fy2, 2, 2))
|
||||
|
||||
self._ui_top(screen, session)
|
||||
self._ui_log(screen, session)
|
||||
self._ui_bottom(screen, session)
|
||||
def _wall(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
|
||||
f: float = 1.0) -> None:
|
||||
pygame.draw.rect(surf, _dim(COLORS["wall_visible"], f), (px, py, TILE, TILE))
|
||||
pygame.draw.rect(surf, _dim(COLORS["wall_top"], f), (px, py, TILE, 4)) # lit top edge
|
||||
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py + TILE - 4, TILE, 4)) # shaded base
|
||||
# brick seams via per-tile hash
|
||||
h = _hash2(tx, ty)
|
||||
seam = COLORS["wall_explored"]
|
||||
if h & 1:
|
||||
pygame.draw.rect(surf, seam, (px + TILE // 2, py + 4, 1, TILE - 8))
|
||||
if h & 2:
|
||||
pygame.draw.rect(surf, seam, (px + 4, py + TILE // 2, TILE - 8, 1))
|
||||
|
||||
def _wall(self, surf, sx, sy, tx, ty, light) -> None:
|
||||
h = _hash(tx, ty)
|
||||
h2 = _hash(tx + 101, ty - 57)
|
||||
bevel = max(2, TILE // 7)
|
||||
# per-tile base shade so no two walls read identically
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * (0.82 + 0.36 * h)), (sx, sy, TILE, TILE))
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 1.45), (sx, sy, TILE, bevel)) # lit top bevel
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.5),
|
||||
(sx, sy + TILE - bevel, TILE, bevel)) # shadow base
|
||||
# brick mortar: horizontal seam mid-wall + offset vertical seams per row
|
||||
mid = sy + TILE // 2
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.58), (sx, mid, TILE, 1))
|
||||
v1 = int(h2 * (TILE // 2))
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v1, sy + bevel, 1, mid - sy - bevel))
|
||||
v2 = (int(h * (TILE // 2)) + TILE // 2) % (TILE - 1)
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v2, mid + 1, 1, sy + TILE - bevel - mid - 1))
|
||||
# stable speckles (highlight + grit)
|
||||
for k in range(4):
|
||||
fx = sx + int((h * (97 + k * 53)) % (TILE - 1))
|
||||
fy = sy + bevel + int((h2 * (31 + k * 29)) % (TILE - 2 * bevel))
|
||||
f = 1.4 if ((h * (k + 2)) % 1) > 0.5 else 0.55
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * f), (fx, fy, 1, 1))
|
||||
def _floor_explored(self, surf: pygame.Surface, px: int, py: int,
|
||||
tx: int, ty: int) -> None:
|
||||
base = COLORS["floor_explored"]
|
||||
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
|
||||
h = _hash2(tx, ty)
|
||||
pygame.draw.rect(surf, _dim(base, 0.7),
|
||||
(px + (h % (TILE - 4)) + 2, py + ((h >> 3) % (TILE - 4)) + 2, 2, 2))
|
||||
pygame.draw.rect(surf, _dim(base, 1.3),
|
||||
(px + ((h >> 2) % (TILE - 4)) + 2, py + ((h >> 5) % (TILE - 4)) + 2, 2, 2))
|
||||
|
||||
def _floor(self, surf, sx, sy, tx, ty, light) -> None:
|
||||
h = _hash(tx, ty)
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * (0.86 + 0.28 * h)), (sx, sy, TILE, TILE))
|
||||
# subtle checkerboard dither (stable per tile parity)
|
||||
if (tx + ty) & 1:
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * 1.16), (sx, sy, 2, 2))
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * 0.8), (sx + TILE - 2, sy + TILE - 2, 2, 2))
|
||||
# flecks / specular grit
|
||||
for k in range(5):
|
||||
fx = sx + int((h * (97 + k * 31)) % (TILE - 1))
|
||||
fy = sy + int((h * (53 + k * 17)) % (TILE - 1))
|
||||
f = 1.4 if ((h * (k + 1)) % 1) > 0.5 else 0.62
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * f), (fx, fy, 1, 1))
|
||||
def _wall_explored(self, surf: pygame.Surface, px: int, py: int,
|
||||
tx: int, ty: int) -> None:
|
||||
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py, TILE, TILE))
|
||||
pygame.draw.rect(surf, _dim(COLORS["wall_explored"], 1.35), (px, py, TILE, 3)) # faint top edge
|
||||
|
||||
def _draw_entities(self, surf, floor, player, cx, cy, t) -> None:
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
def _torch_mask(self) -> pygame.Surface:
|
||||
"""Cached smooth radial brightness mask (white core -> gray rim).
|
||||
|
||||
vis = floor.visible
|
||||
# ground features first (remembered on explored tiles)
|
||||
ground = [e for e in floor.entities
|
||||
if isinstance(e, Item) or (not isinstance(e, Enemy) and getattr(e, "sprite_key", "") == "stairs")]
|
||||
for e in ground:
|
||||
if not (vis[e.y][e.x] or floor.explored[e.y][e.x]):
|
||||
continue
|
||||
self._blit_entity(surf, e, cx, cy, t, shadow=True)
|
||||
# actors: visible enemies + the player, sorted by y for overlap
|
||||
actors = [e for e in floor.entities
|
||||
if isinstance(e, Enemy) and e.hp > 0 and vis[e.y][e.x]]
|
||||
actors.append(player)
|
||||
actors.sort(key=lambda e: e.y)
|
||||
for e in actors:
|
||||
self._blit_entity(surf, e, cx, cy, t, shadow=True, is_actor=True)
|
||||
Built tiny then smooth-scaled so the falloff is bilinear-smooth with no
|
||||
tile-sized bands. Multiplied (BLEND_RGB_MULT) onto the light layer.
|
||||
"""
|
||||
if self._torch is not None:
|
||||
return self._torch
|
||||
diam = (SIGHT_RADIUS * TILE + TILE) * 2 # covers the whole FOV disc + rim
|
||||
s = 64
|
||||
small = pygame.Surface((s, s), pygame.SRCALPHA)
|
||||
c = (s - 1) / 2
|
||||
for yy in range(s):
|
||||
for xx in range(s):
|
||||
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
|
||||
b = 0.45 + 0.55 * (1.0 - t) ** 1.5 # 1.0 core -> ~0.45 rim
|
||||
g = int(b * 255)
|
||||
small.set_at((xx, yy), (g, g, g, 255))
|
||||
self._torch = pygame.transform.smoothscale(small, (diam, diam))
|
||||
return self._torch
|
||||
|
||||
def _blit_entity(self, surf, e, cx, cy, t, shadow=False, is_actor=False) -> None:
|
||||
from entities.enemy import Enemy
|
||||
sx = round(e.x * TILE - cx) + MAP_X
|
||||
sy = round(e.y * TILE - cy) + MAP_Y
|
||||
if shadow:
|
||||
sh = pygame.Surface((TILE - 4, 5), pygame.SRCALPHA)
|
||||
pygame.draw.ellipse(sh, (0, 0, 0, 90), sh.get_rect())
|
||||
surf.blit(sh, (sx + 2, sy + TILE - 5))
|
||||
def _glow(self) -> pygame.Surface:
|
||||
"""Cached warm radial glow added (BLEND_RGB_ADD) at the torch core so the
|
||||
bright center reads clearly against the dimmer rim."""
|
||||
if self._glow_surf is not None:
|
||||
return self._glow_surf
|
||||
diam = SIGHT_RADIUS * TILE * 2
|
||||
s = 48
|
||||
small = pygame.Surface((s, s), pygame.SRCALPHA)
|
||||
c = (s - 1) / 2
|
||||
for yy in range(s):
|
||||
for xx in range(s):
|
||||
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
|
||||
a = int(78 * (1.0 - t) ** 2.2) # warm add, concentrated at center
|
||||
small.set_at((xx, yy), (a, int(a * 0.85), int(a * 0.4), 255))
|
||||
self._glow_surf = pygame.transform.smoothscale(small, (diam, diam))
|
||||
return self._glow_surf
|
||||
|
||||
name = e.sprite_key
|
||||
if name == "player":
|
||||
name = "player_" + getattr(e, "facing", "down")
|
||||
if name not in S.SPRITES:
|
||||
name = "player_down"
|
||||
frame = int(t * 2.5 + (e.x * 7 + e.y * 13)) % max(1, RS.frame_count(name))
|
||||
bob = -1 if (frame == 1 and is_actor) else 0
|
||||
spr = RS.get(name, frame, TILE)
|
||||
if spr is not None:
|
||||
surf.blit(spr, (sx, sy + bob))
|
||||
|
||||
if isinstance(e, Enemy) and e.hp < e.max_hp:
|
||||
self._hp_pip(surf, sx, sy - 3, e.hp / max(1, e.max_hp))
|
||||
if getattr(e, "sprite_key", "") == "player":
|
||||
self._player_gear(surf, e, sx, sy)
|
||||
|
||||
def _hp_pip(self, surf, sx, sy, frac) -> None:
|
||||
w = TILE - 6
|
||||
pygame.draw.rect(surf, (30, 12, 12), (sx + 3, sy, w, 3))
|
||||
fw = max(0, int(w * frac))
|
||||
col = (90, 200, 90) if frac > 0.5 else ((220, 180, 60) if frac > 0.25 else (210, 70, 60))
|
||||
pygame.draw.rect(surf, col, (sx + 3, sy, fw, 3))
|
||||
|
||||
def _player_gear(self, surf, player, sx, sy) -> None:
|
||||
# held weapon icon at the lower-right
|
||||
wpn = player.equipped.get("weapon")
|
||||
if wpn is not None:
|
||||
ico = RS.get(wpn.sprite_key, 0, TILE // 2 + 2)
|
||||
if ico is not None:
|
||||
surf.blit(ico, (sx + TILE - 8, sy + 6))
|
||||
# armor pauldron tint on the shoulders
|
||||
arm = player.equipped.get("armor")
|
||||
if arm is not None:
|
||||
tint = _ARMOR_TINT.get(arm.sprite_key, (180, 180, 180))
|
||||
pygame.draw.rect(surf, tint, (sx + 3, sy + int(TILE * 0.30), 3, 4))
|
||||
pygame.draw.rect(surf, tint, (sx + TILE - 6, sy + int(TILE * 0.30), 3, 4))
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# UI
|
||||
# ------------------------------------------------------------------ #
|
||||
def _panel(self, surf, rect, fill=None) -> None:
|
||||
fill = fill or COL["ui_panel"]
|
||||
pygame.draw.rect(surf, fill, rect)
|
||||
pygame.draw.rect(surf, COL["ui_border"], rect, 1)
|
||||
pygame.draw.line(surf, COL["ui_border_hi"], (rect[0] + 1, rect[1] + 1),
|
||||
(rect[0] + rect[2] - 2, rect[1] + 1)) # top bevel
|
||||
|
||||
def _text(self, surf, s, pos, font=None, color=None) -> None:
|
||||
color = color or COL["log_combat"]
|
||||
surf.blit((font or self.font).render(s, True, color), pos)
|
||||
|
||||
def _bar(self, surf, rect, frac, full, back, icon=None) -> None:
|
||||
x, y, w, h = rect
|
||||
pygame.draw.rect(surf, back, (x, y, w, h))
|
||||
fw = max(0, int(w * max(0.0, min(1.0, frac))))
|
||||
if fw:
|
||||
pygame.draw.rect(surf, full, (x, y, fw, h))
|
||||
pygame.draw.rect(surf, COL["ui_border"], (x, y, w, h), 1)
|
||||
if icon is not None:
|
||||
surf.blit(icon, (x - 2, y - 2))
|
||||
|
||||
def _heart(self, size=12):
|
||||
s = pygame.Surface((size, size), pygame.SRCALPHA)
|
||||
col = (200, 60, 65)
|
||||
r = size // 4
|
||||
pygame.draw.circle(s, col, (size // 2 - r, size // 3), r)
|
||||
pygame.draw.circle(s, col, (size // 2 + r, size // 3), r)
|
||||
pygame.draw.polygon(s, col, [(0, size // 3 + 1), (size, size // 3 + 1), (size // 2, size - 1)])
|
||||
def _shadow_surf(self, size: int) -> pygame.Surface:
|
||||
"""Cached soft elliptical ground shadow (~90% tile wide) drawn under an
|
||||
entity/stairs so sprites read as grounded. Built from concentric ellipses
|
||||
with rising alpha toward the center for a feathered edge."""
|
||||
s = self._shadow_cache.get(size)
|
||||
if s is not None:
|
||||
return s
|
||||
w = max(10, int(size * 0.92))
|
||||
h = max(5, int(size * 0.32))
|
||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
||||
for frac, alpha in ((1.0, 95), (0.78, 150), (0.52, 215)):
|
||||
rw = max(2, int(w * frac))
|
||||
rh = max(2, int(h * frac))
|
||||
rect = pygame.Rect((w - rw) // 2, (h - rh) // 2, rw, rh)
|
||||
pygame.draw.ellipse(surf, (0, 0, 0, alpha), rect)
|
||||
self._shadow_cache[size] = surf
|
||||
return surf
|
||||
|
||||
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
|
||||
self._panel(surf, (0, 0, WIN_W, TOP_H), COL["ui_bg"])
|
||||
self._text(surf, f"Floor {session.current_floor + 1}/{C.FLOORS}", (8, 9), self.font_b, COL["prompt"])
|
||||
# HP bar
|
||||
hx = 150
|
||||
self._bar(surf, (hx, 10, 240, 14), p.hp / max(1, p.max_hp),
|
||||
COL["hp_full"], COL["hp_back"], icon=self._heart())
|
||||
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + 246, 9), self.font_s)
|
||||
# Level + XP
|
||||
self._text(surf, f"Lv {p.level}", (hx + 320, 9), self.font_b, COL["prompt"])
|
||||
xp_next = C.XP_THRESHOLDS.get(min(p.level + 1, C.MAX_LEVEL), p.xp)
|
||||
xp_cur = C.XP_THRESHOLDS.get(p.level, 0)
|
||||
frac = (p.xp - xp_cur) / max(1, xp_next - xp_cur) if xp_next > xp_cur else 1.0
|
||||
self._bar(surf, (WIN_W - SIDE_W - 150, 10, 130, 14), frac, COL["xp_full"], COL["xp_back"])
|
||||
self._text(surf, "XP", (WIN_W - SIDE_W - 172, 9), self.font_s, COL["xp_full"])
|
||||
cx = p.x * TILE - ox + TILE // 2
|
||||
cy = p.y * TILE - oy + TILE // 2
|
||||
# player took damage since last frame
|
||||
hp = getattr(p, "hp", None)
|
||||
if self._last_hp is not None and hp is not None and hp < self._last_hp:
|
||||
self.shake.trigger(6.0)
|
||||
self.particles.burst(cx, cy, COLORS["hp_empty"], count=10, speed=80)
|
||||
if hp <= 0:
|
||||
self.particles.burst(cx, cy, (220, 220, 220), count=22, speed=120, life=0.7)
|
||||
self._last_hp = hp
|
||||
# new log lines -> spawn flavor at the player
|
||||
new_lines = session.log[self._last_log_len:]
|
||||
self._last_log_len = len(session.log)
|
||||
for line in new_lines:
|
||||
low = line.lower()
|
||||
if "critical" in low:
|
||||
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=110)
|
||||
elif "you hit" in low:
|
||||
self.particles.burst(cx, cy, COLORS["player"], count=5, speed=70) # hit sparks
|
||||
elif "defeated" in low or "slew" in low:
|
||||
self.particles.burst(cx, cy, COLORS["hp_empty"], count=16, speed=100, life=0.6)
|
||||
elif "reach level" in low:
|
||||
self.particles.burst(cx, cy, COLORS["xp_bar"], count=18, speed=90, life=0.8)
|
||||
elif "pick up" in low or "pickup" in low:
|
||||
self.particles.burst(cx, cy, COLORS["stairs"], count=10, speed=60)
|
||||
elif "descend" in low:
|
||||
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=70)
|
||||
|
||||
def _ui_log(self, surf, session) -> None:
|
||||
x = MAP_W_PX
|
||||
y = TOP_H
|
||||
self._panel(surf, (x, y, SIDE_W, MAP_H_PX), COL["ui_bg"])
|
||||
self._text(surf, "Messages", (x + 8, y + 6), self.font_b, COL["prompt"])
|
||||
pygame.draw.line(surf, COL["ui_border"], (x + 4, y + 24), (x + SIDE_W - 4, y + 24))
|
||||
lines = session.log[-9:]
|
||||
ly = y + MAP_H_PX - 12
|
||||
for line in reversed(lines):
|
||||
txt = self._crop(line, _log_color(line), SIDE_W - 16)
|
||||
surf.blit(txt, (x + 8, ly - txt.get_height()))
|
||||
ly -= txt.get_height() + 1
|
||||
|
||||
def _crop(self, text, color, maxw):
|
||||
full = self.font_s.render(text, True, color)
|
||||
if full.get_width() <= maxw:
|
||||
return full
|
||||
keep = max(3, int(len(text) * maxw / full.get_width()) - 1)
|
||||
return self.font_s.render(text[:keep] + "...", True, color)
|
||||
|
||||
def _ui_bottom(self, surf, session) -> None:
|
||||
# --------------------------------------------------------------- UI
|
||||
def _ui(self, surf: pygame.Surface, session: Any, sw: int, sh: int) -> None:
|
||||
p = session.player
|
||||
y = WIN_H - BOT_H
|
||||
self._panel(surf, (0, y, WIN_W, BOT_H), COL["ui_bg"])
|
||||
# equipment slots
|
||||
self._text(surf, "WPN", (8, y + 6), self.font_s, COL["weapon"])
|
||||
wpn = p.equipped.get("weapon")
|
||||
self._slot(surf, 8, y + 20, wpn)
|
||||
self._text(surf, "ARM", (42, y + 6), self.font_s, COL["armor"])
|
||||
self._slot(surf, 42, y + 20, p.equipped.get("armor"))
|
||||
# active effect timers
|
||||
ex = 90
|
||||
self._text(surf, "Effects", (ex, y + 6), self.font_s, COL["prompt"])
|
||||
if p.effects:
|
||||
tx = ex
|
||||
for eff in p.effects:
|
||||
label = ("STR" if eff.kind == "strength" else "INV")
|
||||
col = COL["weapon"] if eff.kind == "strength" else COL["wraith"]
|
||||
self._text(surf, f"{label} {eff.duration}", (tx, y + 22), self.font_s, col)
|
||||
tx += 52
|
||||
else:
|
||||
self._text(surf, "-", (ex, y + 22), self.font_s, (90, 90, 100))
|
||||
# sound icon
|
||||
self._text(surf, "[m] sound " + ("OFF" if self.audio.muted else "ON"),
|
||||
(WIN_W - SIDE_W - 110, y + 22), self.font_s,
|
||||
(120, 120, 130) if self.audio.muted else COL["log_levelup"])
|
||||
# context prompt
|
||||
prompt = self._context(session)
|
||||
# ---- top bar ----
|
||||
self._panel(surf, (0, 0, sw, 28))
|
||||
floor_n = session.current_floor + 1
|
||||
self._text(surf, f"Floor {floor_n}/10", (6, 6), COLORS["text"])
|
||||
|
||||
# HP: pixel-art heart icon + red track / green fill
|
||||
hx, hy, hw = 156, 8, 140
|
||||
self._heart(surf, 134, 6)
|
||||
pygame.draw.rect(surf, COLORS["hp_empty"], (hx, hy, hw, 12))
|
||||
frac = max(0.0, p.hp / max(1, p.max_hp))
|
||||
pygame.draw.rect(surf, COLORS["hp_full"], (hx, hy, int(hw * frac), 12))
|
||||
pygame.draw.rect(surf, COLORS["panel_border"], (hx, hy, hw, 12), 1)
|
||||
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + hw + 5, 6), COLORS["text"])
|
||||
|
||||
# Level/XP: star icon + Lv + XP bar (right side)
|
||||
star_x = sw - 252
|
||||
self._star(surf, star_x, 6)
|
||||
self._text(surf, f"Lv {p.level}", (star_x + 16, 6), COLORS["text"])
|
||||
xx, xw = sw - 170, 112
|
||||
pygame.draw.rect(surf, (30, 30, 40), (xx, 10, xw, 8))
|
||||
lvl = min(max(1, p.level), 9)
|
||||
need = [30, 70, 140, 250, 400, 600, 850, 1150, 1500][lvl - 1]
|
||||
prev = [0, 30, 70, 140, 250, 400, 600, 850, 1150][lvl - 1]
|
||||
xpfrac = max(0.0, min(1.0, (p.xp - prev) / max(1, need - prev)))
|
||||
pygame.draw.rect(surf, COLORS["xp_bar"], (xx, 10, int(xw * xpfrac), 8))
|
||||
pygame.draw.rect(surf, COLORS["panel_border"], (xx, 10, xw, 8), 1)
|
||||
|
||||
# ---- right log panel: full-height side panel, color-coded, no clipping ----
|
||||
panel_x, panel_w, line_h = sw - 262, 258, 14
|
||||
panel_top, panel_bottom = 34, sh - 34
|
||||
self._panel(surf, (panel_x, panel_top, panel_w, panel_bottom - panel_top))
|
||||
self._text(surf, "Messages", (panel_x + 6, panel_top + 4), COLORS["text_dim"], small=True)
|
||||
text_x, max_w = panel_x + 6, panel_w - 12
|
||||
# newest at the bottom; word-wrap long lines so nothing is cut off
|
||||
shown = session.log[-8:]
|
||||
wrapped: list[tuple[str, tuple[int, int, int]]] = []
|
||||
for line in shown:
|
||||
wrapped.extend((w, self._log_color(line)) for w in self._wrap(line, max_w))
|
||||
y = panel_bottom - 6 - line_h * len(wrapped)
|
||||
for msg, col in wrapped:
|
||||
if y >= panel_top + 20:
|
||||
self._text(surf, msg, (text_x, y), col, small=True)
|
||||
y += line_h
|
||||
|
||||
# ---- bottom equipment bar: icon slots, not bare text ----
|
||||
self._panel(surf, (0, sh - 30, sw, 30))
|
||||
slot_y = sh - 27
|
||||
nx = self._equip_slot(surf, 6, slot_y, p.equipped_weapon)
|
||||
nx = self._equip_slot(surf, nx + 8, slot_y, p.equipped_armor)
|
||||
self._text(surf, f"Pack: {len(p.inventory)}", (nx + 10, sh - 22), COLORS["text_dim"])
|
||||
eff = ", ".join(f"{k}:{v}" for k, v in p.effect_timers.items())
|
||||
if eff:
|
||||
self._text(surf, f"[{eff}]", (sw // 2 - 40, sh - 22), COLORS["xp_bar"])
|
||||
|
||||
# ---- styled context prompt ----
|
||||
prompt = self._context_prompt(session)
|
||||
if prompt:
|
||||
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:
|
||||
rect = (x, y, 28, 22)
|
||||
pygame.draw.rect(surf, COL["ui_panel"], rect)
|
||||
pygame.draw.rect(surf, COL["ui_border"], rect, 1)
|
||||
# --------------------------------------------------------------- UI helpers
|
||||
@staticmethod
|
||||
def _log_color(line: str) -> tuple[int, int, int]:
|
||||
low = line.lower()
|
||||
if any(w in low for w in ("slain", "died", "wound", "damage to you", "fizzle")):
|
||||
return COLORS["log_bad"] # damage-taken / death -> red
|
||||
if any(w in low for w in ("reach level", "defeated", "slew", "level up")):
|
||||
return COLORS["log_good"] # level-up / kill -> green
|
||||
if any(w in low for w in ("pick up", "pickup", "descend", "quaff",
|
||||
"you read", "equip", "stairs", "reveals")):
|
||||
return COLORS["stairs"] # items / stairs -> yellow
|
||||
return COLORS["text"] # combat / hit / miss / crit -> white
|
||||
|
||||
def _fit_text(self, text: str, max_w: int, small: bool = False) -> str:
|
||||
f = self._font_small if small else self._font
|
||||
if f is None or f.size(text)[0] <= max_w:
|
||||
return text
|
||||
ell = "…"
|
||||
while text and f.size(text + ell)[0] > max_w:
|
||||
text = text[:-1]
|
||||
return (text + ell) if text else ""
|
||||
|
||||
def _wrap(self, text: str, max_w: int) -> list[str]:
|
||||
"""Word-wrap text to <= max_w px per line (greedy). Returns >=1 line."""
|
||||
f = self._font_small
|
||||
if f is None:
|
||||
return [text]
|
||||
words = text.split()
|
||||
lines: list[str] = []
|
||||
cur = ""
|
||||
for w in words:
|
||||
trial = w if not cur else cur + " " + w
|
||||
if f.size(trial)[0] <= max_w or not cur:
|
||||
cur = trial
|
||||
else:
|
||||
lines.append(cur)
|
||||
cur = w
|
||||
if cur:
|
||||
lines.append(cur)
|
||||
return lines or [""]
|
||||
|
||||
@staticmethod
|
||||
def _heart(surf: pygame.Surface, x: int, y: int) -> None:
|
||||
c = COLORS["heart"]
|
||||
pygame.draw.circle(surf, c, (x + 4, y + 4), 4)
|
||||
pygame.draw.circle(surf, c, (x + 10, y + 4), 4)
|
||||
pygame.draw.polygon(surf, c, [(x, y + 5), (x + 14, y + 5), (x + 7, y + 13)])
|
||||
surf.set_at((x + 7, y + 2), (90, 16, 20)) # top cleft
|
||||
surf.set_at((x + 3, y + 3), (255, 160, 170)) # highlight
|
||||
|
||||
@staticmethod
|
||||
def _star(surf: pygame.Surface, x: int, y: int) -> None:
|
||||
cx, cy = x + 7, y + 7
|
||||
pts = []
|
||||
for i in range(10):
|
||||
ang = -math.pi / 2 + i * math.pi / 5
|
||||
rr = 7 if i % 2 == 0 else 3
|
||||
pts.append((cx + rr * math.cos(ang), cy + rr * math.sin(ang)))
|
||||
pygame.draw.polygon(surf, COLORS["star"], pts)
|
||||
pygame.draw.polygon(surf, (120, 80, 20), pts, 1)
|
||||
|
||||
def _equip_slot(self, surf: pygame.Surface, x: int, y: int,
|
||||
item: Any) -> int:
|
||||
box = 24
|
||||
pygame.draw.rect(surf, COLORS["panel"], (x, y, box, box))
|
||||
pygame.draw.rect(surf, COLORS["panel_border"], (x, y, box, box), 1)
|
||||
if item is not None:
|
||||
ico = RS.get(item.sprite_key, 0, 20)
|
||||
if ico is not None:
|
||||
surf.blit(ico, (x + 4, y + 1))
|
||||
kind = getattr(item, "kind", "") or getattr(item, "sprite_key", "")
|
||||
surf.blit(get_tile_sprite(kind, 20), (x + 2, y + 2))
|
||||
name = self._fit_text(item.name, 124)
|
||||
self._text(surf, name, (x + box + 3, y + 6), COLORS["text"])
|
||||
return x + box + 130
|
||||
self._text(surf, "—", (x + 9, y + 5), COLORS["text_dim"])
|
||||
self._text(surf, "empty", (x + box + 3, y + 6), COLORS["text_dim"])
|
||||
return x + box + 52
|
||||
|
||||
def _context(self, session) -> str:
|
||||
from entities.item import Item
|
||||
def _context_prompt(self, session: Any) -> str:
|
||||
p = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Item) and e.x == p.x and e.y == p.y:
|
||||
return f"Press G to pick up {e.name}"
|
||||
if (p.x, p.y) == floor.stairs_down and session.current_floor < C.FLOORS - 1:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
item = next((e for e in gm.entities
|
||||
if self._is_item(e) and e.x == p.x and e.y == p.y), None)
|
||||
if item is not None:
|
||||
return f"Press G to pick up {item.name}"
|
||||
if gm.stairs_down == (p.x, p.y):
|
||||
return "Press F to descend"
|
||||
return ""
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Screens
|
||||
# ------------------------------------------------------------------ #
|
||||
def render_menu(self, screen, index, has_save, t) -> None:
|
||||
screen.fill(VOID)
|
||||
bob = math.sin(t * 2.0) * 4
|
||||
self._text(screen, "UNDERDEPTHS", (WIN_W // 2 - 150, 90 + bob), self.font_xl, COL["prompt"])
|
||||
self._text(screen, "A turn-based roguelike descent", (WIN_W // 2 - 110, 150 + bob),
|
||||
self.font, (150, 140, 120))
|
||||
dragon = RS.get("ancient_dragon", int(t * 2.5) % 2, 96)
|
||||
if dragon is not None:
|
||||
screen.blit(dragon, (WIN_W // 2 - 48, 190))
|
||||
options = ["New Game"]
|
||||
if has_save:
|
||||
options.append("Continue")
|
||||
options += ["How to Play", "Quit"]
|
||||
oy = 320
|
||||
for i, opt in enumerate(options):
|
||||
sel = (i == index)
|
||||
col = COL["highlight"] if sel else (170, 160, 150)
|
||||
prefix = "> " if sel else " "
|
||||
self._text(screen, prefix + opt, (WIN_W // 2 - 90, oy + i * 30), self.font_b, col)
|
||||
self._text(screen, "arrows/hjkl select - enter confirm", (WIN_W // 2 - 130, WIN_H - 40),
|
||||
self.font_s, (110, 105, 100))
|
||||
|
||||
_HELP_LINES = [
|
||||
("HOW TO PLAY", COL["prompt"], True),
|
||||
("", None, False),
|
||||
("Move / attack: Arrows or H J K L (walk into an enemy to hit)", COL["log_combat"], False),
|
||||
("Pick up item: stand on it, press G", COL["log_item"], False),
|
||||
("Descend: stand on the yellow > stairs, press F", COL["prompt"], False),
|
||||
("Inventory: I Equipment: E", COL["log_combat"], False),
|
||||
("Quaff potion: Q Read scroll: R", COL["log_combat"], False),
|
||||
("Save & quit: S Help: ? Mute: M Cancel: Esc", COL["log_combat"], False),
|
||||
("", None, False),
|
||||
("Slay the Ancient Dragon on floor 10 to win. Permadeath: die and the", (170, 160, 150), False),
|
||||
("run ends. Explore, loot, level up, and descend.", (170, 160, 150), False),
|
||||
("", None, False),
|
||||
("Press any key to return.", COL["prompt"], False),
|
||||
]
|
||||
|
||||
def render_help(self, screen, t) -> None:
|
||||
screen.fill(VOID)
|
||||
self._panel(screen, (WIN_W // 2 - 290, 70, 580, 460), COL["ui_bg"])
|
||||
y = 96
|
||||
for line, col, big in self._HELP_LINES:
|
||||
self._text(screen, line, (WIN_W // 2 - 270, y), self.font_l if big else self.font,
|
||||
col or COL["log_combat"])
|
||||
y += 40 if big else 26
|
||||
|
||||
def render_end(self, screen, session, kind, t) -> None:
|
||||
screen.fill(VOID)
|
||||
p = session.player
|
||||
if kind == "victory":
|
||||
self._text(screen, "VICTORY", (WIN_W // 2 - 130, 150), self.font_xl, COL["log_levelup"])
|
||||
self._text(screen, "You slew the Ancient Dragon!", (WIN_W // 2 - 150, 230), self.font_b, COL["prompt"])
|
||||
self._text(screen, "You conquered Underdepths.", (WIN_W // 2 - 130, 260), self.font_b, COL["prompt"])
|
||||
else:
|
||||
self._text(screen, "YOU DIED", (WIN_W // 2 - 120, 150), self.font_xl, COL["hp_full"])
|
||||
self._text(screen, f"You died on floor {session.current_floor + 1}.",
|
||||
(WIN_W // 2 - 130, 230), self.font_b, COL["log_combat"])
|
||||
self._text(screen, f"You reached level {p.level}.", (WIN_W // 2 - 110, 290), self.font_b, COL["log_levelup"])
|
||||
self._text(screen, "Press any key to return to the menu.", (WIN_W // 2 - 150, WIN_H - 90),
|
||||
self.font, (150, 140, 120))
|
||||
|
||||
def render_inventory(self, screen, session, mode, t) -> None:
|
||||
p = session.player
|
||||
# main.py passes overlay modes 'inv' | 'equip' | 'quaff' | 'read'
|
||||
title = {"inv": "Inventory", "equip": "Equipment",
|
||||
"quaff": "Quaff a Potion", "read": "Read a Scroll"}.get(mode, "Inventory")
|
||||
|
||||
def wanted(it):
|
||||
if mode == "quaff":
|
||||
return it.item_type == "potion"
|
||||
if mode == "read":
|
||||
return it.item_type == "scroll"
|
||||
return True
|
||||
items = [it for it in p.inventory if wanted(it)]
|
||||
|
||||
pw, ph = WIN_W - 160, WIN_H - 160
|
||||
px, py = 80, 80
|
||||
self._panel(screen, (px, py, pw, ph), COL["ui_bg"])
|
||||
self._text(screen, title, (px + 16, py + 12), self.font_l, COL["prompt"])
|
||||
if mode == "equip":
|
||||
self._text(screen, f"Weapon: {_name(p.equipped.get('weapon'))}", (px + 16, py + 60), self.font, COL["weapon"])
|
||||
self._text(screen, f"Armor: {_name(p.equipped.get('armor'))}", (px + 16, py + 82), self.font, COL["armor"])
|
||||
self._text(screen, "Equip from inventory (I).", (px + 16, py + 110), self.font_s, (150, 140, 120))
|
||||
ly = py + 64 if mode != "equip" else py + 150
|
||||
if mode != "equip" and not items:
|
||||
self._text(screen, "(empty)", (px + 16, ly), self.font, (130, 125, 120))
|
||||
for i, it in enumerate(items):
|
||||
letter = chr(ord("a") + i) if i < 26 else str(i)
|
||||
ico = RS.get(it.sprite_key, 0, 20)
|
||||
row_y = ly + i * 26
|
||||
if ico is not None:
|
||||
screen.blit(ico, (px + 16, row_y - 2))
|
||||
kind = it.item_type.capitalize()
|
||||
self._text(screen, f"[{letter}] {it.name}", (px + 42, row_y), self.font, COL["log_item"])
|
||||
self._text(screen, kind, (px + pw - 130, row_y), self.font_s, (150, 140, 120))
|
||||
hint = "press a letter to use/equip - Esc closes" if mode != "equip" else "Esc closes"
|
||||
self._text(screen, hint, (px + 16, py + ph - 28), self.font_s, (130, 125, 120))
|
||||
|
||||
|
||||
def _name(item) -> str:
|
||||
return item.name if item is not None else "(none)"
|
||||
def _panel(self, surf: pygame.Surface, rect: tuple[int, int, int, int]) -> None:
|
||||
pygame.draw.rect(surf, COLORS["panel"], rect)
|
||||
pygame.draw.rect(surf, COLORS["panel_border"], rect, 1)
|
||||
@@ -1,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
|
||||
caches it. The renderer blits the cached surface directly. Pixel-art is kept
|
||||
crisp with nearest-neighbour `transform.scale` (never smoothscale).
|
||||
``get_sprite(name)`` returns the native-size cached Surface; the renderer scales
|
||||
it to ``TILE`` via ``get_tile_sprite``. All art is procedural (pygame.draw /
|
||||
set_at from in-code palettes); no external image files are loaded.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
from typing import Any
|
||||
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
from data import sprites as S
|
||||
from data.constants import PALETTE, TILE as _TILE
|
||||
from data import sprites as SPRITE_DATA
|
||||
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):
|
||||
"""Return the cached Surface for `name` scaled to `tile`x`tile`."""
|
||||
if pygame is None:
|
||||
return None
|
||||
key = (name, frame, tile)
|
||||
cached = _cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
grid = S.grid(name, frame)
|
||||
def _color(ch: str, tint: tuple[int, int, int] | None) -> tuple[int, int, int] | None:
|
||||
if ch == "a":
|
||||
return tint if tint is not None else (200, 200, 200)
|
||||
return PALETTE.get(ch)
|
||||
|
||||
|
||||
def _rasterize(grid: list[str], tint: tuple[int, int, int] | None) -> pygame.Surface:
|
||||
h = len(grid)
|
||||
w = max(len(r) for r in grid) if grid else 1
|
||||
w = max((len(row) for row in grid), default=1)
|
||||
w = max(1, w)
|
||||
cell = 3 # fixed >=2 internal px/cell; crisp nearest-scale to any tile size
|
||||
surf = pygame.Surface((w * cell, h * cell), pygame.SRCALPHA)
|
||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
||||
for y, row in enumerate(grid):
|
||||
for x, ch in enumerate(row):
|
||||
col = PALETTE.get(ch)
|
||||
if col is not None:
|
||||
pygame.draw.rect(surf, col, (x * cell, y * cell, cell, cell))
|
||||
if (w * cell, h * cell) != (tile, tile):
|
||||
surf = pygame.transform.scale(surf, (tile, tile))
|
||||
_cache[key] = surf
|
||||
c = _color(ch, tint)
|
||||
if c is not None:
|
||||
surf.set_at((x, y), (c[0], c[1], c[2], 255))
|
||||
return surf
|
||||
|
||||
|
||||
def frame_count(name: str) -> int:
|
||||
return S.frames_count(name)
|
||||
def _convert(surf: pygame.Surface) -> pygame.Surface:
|
||||
try:
|
||||
return surf.convert_alpha()
|
||||
except Exception:
|
||||
return surf # no display yet (e.g. constructed before set_mode): use raw
|
||||
|
||||
|
||||
def warm(tile: int = _TILE) -> None:
|
||||
"""Pre-rasterize every sprite frame so the first frame is hitch-free."""
|
||||
if pygame is None:
|
||||
return
|
||||
for name in S.NAMES:
|
||||
for f in range(S.frames_count(name)):
|
||||
get(name, f, tile)
|
||||
def _make_dragon() -> pygame.Surface:
|
||||
"""Procedural 2x2 boss dragon: ONE connected silhouette (wings+body+head+tail
|
||||
drawn in the same red with no internal outlines, so it reads as a single
|
||||
creature, not separate blobs), then details layered on top."""
|
||||
size = TILE * 2
|
||||
s = pygame.Surface((size, size), pygame.SRCALPHA)
|
||||
K = (16, 14, 20); n = (140, 42, 42); r = (208, 66, 54); H = (172, 54, 54)
|
||||
h = (235, 235, 235); y = (246, 206, 86); amber = (222, 156, 60)
|
||||
|
||||
def poly(col, pts):
|
||||
pygame.draw.polygon(s, col, pts)
|
||||
|
||||
def ell(col, cx, cy, rw, rh):
|
||||
pygame.draw.ellipse(s, col, pygame.Rect(cx - rw, cy - rh, rw * 2, rh * 2))
|
||||
|
||||
# ---- single connected red silhouette: wings sweep up-out, body+head capsule ----
|
||||
poly(r, [(20, 16), (5, 7), (2, 15), (7, 20), (13, 17), (20, 21)]) # left wing
|
||||
poly(r, [(20, 16), (35, 7), (38, 15), (33, 20), (27, 17), (20, 21)]) # right wing
|
||||
ell(r, 20, 22, 7, 13) # body + head capsule
|
||||
poly(r, [(17, 34), (23, 34), (27, 39), (13, 39)]) # tail
|
||||
# wing membrane shading (darker), inside the wings only
|
||||
poly(n, [(16, 15), (6, 9), (4, 14), (9, 18), (13, 16)])
|
||||
poly(n, [(24, 15), (34, 9), (36, 14), (31, 18), (27, 16)])
|
||||
pygame.draw.line(s, H, (20, 17), (6, 9), 1) # finger bones
|
||||
pygame.draw.line(s, H, (20, 17), (13, 16), 1)
|
||||
pygame.draw.line(s, H, (20, 17), (34, 9), 1)
|
||||
pygame.draw.line(s, H, (20, 17), (27, 16), 1)
|
||||
# ---- details ----
|
||||
for sx in (16, 20, 24): # dorsal spines
|
||||
poly(H, [(sx - 1, 10), (sx + 1, 10), (sx, 5)])
|
||||
ell(y, 20, 28, 4, 5) # fiery belly
|
||||
for by in (26, 29, 32):
|
||||
pygame.draw.line(s, amber, (17, by), (23, by), 1)
|
||||
poly(h, [(15, 10), (10, 2), (13, 2), (17, 9)]) # horns
|
||||
poly(h, [(25, 10), (30, 2), (27, 2), (23, 9)])
|
||||
pygame.draw.line(s, H, (14, 14), (17, 14), 1) # brows
|
||||
pygame.draw.line(s, H, (23, 14), (26, 14), 1)
|
||||
pygame.draw.circle(s, y, (17, 16), 2) # eyes
|
||||
pygame.draw.circle(s, y, (23, 16), 2)
|
||||
pygame.draw.line(s, K, (17, 15), (17, 17), 1)
|
||||
pygame.draw.line(s, K, (23, 15), (23, 17), 1)
|
||||
pygame.draw.circle(s, K, (19, 19), 1) # nostrils
|
||||
pygame.draw.circle(s, K, (21, 19), 1)
|
||||
poly(h, [(18, 18), (17, 21), (19, 19)]) # fangs
|
||||
poly(h, [(22, 18), (23, 21), (21, 19)])
|
||||
for fx in (16, 24): # claws
|
||||
pygame.draw.line(s, h, (fx - 2, 35), (fx - 2, 38), 1)
|
||||
pygame.draw.line(s, h, (fx, 35), (fx, 38), 1)
|
||||
pygame.draw.line(s, h, (fx + 2, 35), (fx + 2, 38), 1)
|
||||
return s
|
||||
|
||||
|
||||
def get_sprite(name: str) -> pygame.Surface:
|
||||
"""Native-size cached sprite for ``name`` (transparent background)."""
|
||||
if name in _NATIVE:
|
||||
return _NATIVE[name]
|
||||
if name == "ancient_dragon":
|
||||
surf = _convert(_make_dragon())
|
||||
_NATIVE[name] = surf
|
||||
return surf
|
||||
grid = SPRITE_DATA.GRIDS.get(name)
|
||||
if grid is None:
|
||||
grid = SPRITE_DATA.GRIDS["player"] # safe fallback
|
||||
tint = SPRITE_DATA.TINTS.get(name)
|
||||
surf = _convert(_rasterize(grid, tint))
|
||||
_NATIVE[name] = surf
|
||||
return surf
|
||||
|
||||
|
||||
def get_tile_sprite(name: str, size: int = TILE) -> pygame.Surface:
|
||||
"""Sprite scaled to ``size`` (cached per name+size)."""
|
||||
key = f"{name}@{size}"
|
||||
if key in _SCALED:
|
||||
return _SCALED[key]
|
||||
native = get_sprite(name)
|
||||
scaled = pygame.transform.scale(native, (size, size))
|
||||
_SCALED[key] = scaled
|
||||
return scaled
|
||||
|
||||
|
||||
def clear_cache() -> None:
|
||||
_NATIVE.clear()
|
||||
_SCALED.clear()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pygame.init()
|
||||
pygame.display.set_mode((16, 16))
|
||||
s = get_sprite("stairs")
|
||||
opaque = yellow = 0
|
||||
for yy in range(s.get_height()):
|
||||
for xx in range(s.get_width()):
|
||||
c = s.get_at((xx, yy))
|
||||
if c.a == 0:
|
||||
continue
|
||||
opaque += 1
|
||||
if c.r > 120 and c.g > 100 and c.b < 110:
|
||||
yellow += 1
|
||||
print(f"stairs {s.get_size()} opaque={opaque} yellow={yellow}")
|
||||
assert opaque > 0 and yellow > 0, "stairs sprite not yellow/opaque"
|
||||
for n in ("player", "rat", "goblin", "skeleton_archer", "orc_warrior",
|
||||
"wraith", "green_slime", "ancient_dragon", "healing_potion", "war_hammer"):
|
||||
g = get_sprite(n)
|
||||
assert g.get_width() >= 4 and g.get_height() >= 4, n
|
||||
print("sprites self-check: OK")
|
||||
pygame.quit()
|
||||
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 44 KiB |