(Underdepths) Prepare for final pass
No files matched your search
@@ -1 +0,0 @@
|
|||||||
4
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
[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] ============================================================
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
|
||||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
|
||||||
All edits landed cleanly. Phase 4c rendering is complete and verified.
|
|
||||||
|
|
||||||
## Summary
|
|
||||||
|
|
||||||
The render layer was already built by a prior dispatch and **passed the phase-4 gate**. I audited it against the full spec (not just the smoke minimum) and closed one genuine gap:
|
|
||||||
|
|
||||||
**Fixed — radial torch-light falloff** (explicitly required, a plan.md judging criterion; `effects.py`'s own docstring claimed it but the renderer did binary bright/dim):
|
|
||||||
- `render/effects.py`: added `torch_factor(dx,dy,radius)` → 1.0 at the bearer's feet, fading to ~0.55 at the sight rim (Chebyshev distance, matches FOV radius).
|
|
||||||
- `render/renderer.py`: visible tiles now dim by distance from the player; `_wall` now honors the factor (it previously ignored it); added normal "hit sparks" particle burst (plan.md lists it but only crit/death/level/pickup/stairs triggered before).
|
|
||||||
|
|
||||||
**Verified already-compliant:**
|
|
||||||
- `data/sprites.py` — distinct 14×15 grids for stairs, player, all 7 enemies, small_slime, items (per-kind tints).
|
|
||||||
- `render/sprites.py` — `get_sprite()` cached; stairs = `(245,215,70)` → R>120,G>100,B<110; self-check confirms 87 opaque/87 yellow pixels.
|
|
||||||
- `render/renderer.py` — blits the stairs sprite on **every** `stairs_down` tile (visible or explored); pure read of state.
|
|
||||||
- `render/camera.py` — smooth easing follow with map-bounds clamp.
|
|
||||||
- explored-dimmed tiles, wall occlusion (via FOV), vignette, pooled particles, screen-shake.
|
|
||||||
|
|
||||||
**Gate result:** `phase 4: PASS` (incl. stairs-rendered pixel assertion + dragon-kill→victory), `phases 1–3: PASS`, `goal: PASS` — no regressions.
|
|
||||||
|
|
||||||
Skipped: torch flicker animation — falloff already sells the torch feel; add only if it reads too static.
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
49976 49976
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
[18:40:07] Underdepths pipeline starting. Last completed phase: 0
|
|
||||||
[18:40:07] ===== PHASE 1: build (attempt 1) =====
|
|
||||||
[18:40:07] dispatch: pi -p (<2064 chars>) TTL=3000s
|
|
||||||
[18:47:15] dispatch returned rc=0
|
|
||||||
[18:47:15] GATE --phase 1: PASS
|
|
||||||
[18:47:15] phase 1 COMPLETE (.build_state -> 1)
|
|
||||||
[18:47:15] ===== PHASE 2: build (attempt 1) =====
|
|
||||||
[18:47:15] dispatch: pi -p (<1021 chars>) TTL=3000s
|
|
||||||
[18:51:56] dispatch returned rc=0
|
|
||||||
orchestrate.sh: line 174: blocked: command not found
|
|
||||||
[18:51:56] dispatch: pi -p (<954 chars>) TTL=3000s
|
|
||||||
[18:54:22] dispatch returned rc=0
|
|
||||||
[18:54:22] dispatch: pi -p (<1196 chars>) TTL=3000s
|
|
||||||
[18:56:18] dispatch returned rc=0
|
|
||||||
orchestrate.sh: line 199: visible: command not found
|
|
||||||
[18:56:18] dispatch: pi -p (<1090 chars>) TTL=3000s
|
|
||||||
[19:08:31] dispatch returned rc=0
|
|
||||||
[19:08:31] GATE --phase 2: PASS
|
|
||||||
[19:08:31] phase 2 COMPLETE (.build_state -> 2)
|
|
||||||
[19:08:31] ===== PHASE 3: build (attempt 1) =====
|
|
||||||
[19:08:31] dispatch: pi -p (<1969 chars>) TTL=3000s
|
|
||||||
[19:13:33] dispatch returned rc=0
|
|
||||||
[19:13:33] GATE --phase 3: PASS
|
|
||||||
[19:13:33] phase 3 COMPLETE (.build_state -> 3)
|
|
||||||
[19:13:33] ===== PHASE 4: build (attempt 1) =====
|
|
||||||
orchestrate.sh: line 242: visible: command not found
|
|
||||||
[19:13:33] dispatch: pi -p (<1210 chars>) TTL=3000s
|
|
||||||
[19:27:37] dispatch returned rc=0
|
|
||||||
[19:27:37] dispatch: pi -p (<1919 chars>) TTL=3000s
|
|
||||||
[20:08:13] dispatch returned rc=0
|
|
||||||
[20:08:13] dispatch: pi -p (<1633 chars>) TTL=3000s
|
|
||||||
[20:12:14] dispatch returned rc=0
|
|
||||||
[20:12:14] GATE --phase 4: PASS
|
|
||||||
[20:12:14] phase 4 COMPLETE (.build_state -> 4)
|
|
||||||
[20:12:14] ===== GOAL BACKSTOP =====
|
|
||||||
[20:12:15] GATE --goal: PASS
|
|
||||||
[20:12:15] ============================================================
|
|
||||||
[20:12:15] BUILD COMPLETE: all 4 phases + goal backstop PASS.
|
|
||||||
[20:12:15] Play it: python main.py
|
|
||||||
[20:12:15] ============================================================
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
37587 37587
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
68252 68252
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
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'
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
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.
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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'
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
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.
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
#!/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 [])
|
|
||||||
|
Before Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 30 KiB |
@@ -1,107 +0,0 @@
|
|||||||
#!/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)))
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
#!/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.")
|
|
||||||
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 46 KiB |
@@ -1,392 +0,0 @@
|
|||||||
"""Enemy AI dispatch.
|
|
||||||
|
|
||||||
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.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))
|
|
||||||
|
|
||||||
# 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
|
|
||||||
|
|
||||||
# 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] = {}
|
|
||||||
|
|
||||||
|
|
||||||
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:
|
|
||||||
_chase(enemy, game_map, player, visible, rng)
|
|
||||||
else:
|
|
||||||
# "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)
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- behaviors
|
|
||||||
|
|
||||||
def _wander(enemy: Any, game_map: Any, rng: random.Random) -> None:
|
|
||||||
if rng.random() < _WANDER_MOVE_CHANCE:
|
|
||||||
return
|
|
||||||
moves = [d for d in _DIRS if game_map.walkable(enemy.x + d[0], enemy.y + d[1])]
|
|
||||||
if not moves:
|
|
||||||
return
|
|
||||||
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
|
|
||||||
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 _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(
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------- 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.
|
|
||||||
"""
|
|
||||||
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 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,
|
|
||||||
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,126 +0,0 @@
|
|||||||
"""Tuning constants, palettes, and progression tables for Underdepths.
|
|
||||||
|
|
||||||
No magic numbers in game logic — everything tunable lives here.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
# --- viewport / grid -------------------------------------------------------
|
|
||||||
TILE: int = 20
|
|
||||||
MAP_W: int = 80
|
|
||||||
MAP_H: int = 50
|
|
||||||
SIGHT_RADIUS: int = 8
|
|
||||||
FLOOR_COUNT: int = 10
|
|
||||||
|
|
||||||
# --- 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),
|
|
||||||
"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),
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- single-char palette keys for procedural pixel-art grids (render layer) -
|
|
||||||
PALETTE: dict = {
|
|
||||||
".": None, # transparent
|
|
||||||
" ": 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 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
|
|
||||||
|
|
||||||
# --- persistence ----------------------------------------------------------------
|
|
||||||
SAVE_FILE: str = "save.json"
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
"""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,
|
|
||||||
)
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
"""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,311 +0,0 @@
|
|||||||
"""Procedural pixel-art grids: 2D arrays of single-char palette keys.
|
|
||||||
|
|
||||||
``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
|
|
||||||
|
|
||||||
# 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,387 +0,0 @@
|
|||||||
"""Intent dispatch: translate a logical key into a session mutation.
|
|
||||||
|
|
||||||
``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
|
|
||||||
|
|
||||||
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),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- 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)
|
|
||||||
elif key in ("?", "m", "escape"):
|
|
||||||
# Overlays / mute live in the presentation layer (main.py); safe no-op.
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- 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)
|
|
||||||
session.turn += 1
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
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
|
|
||||||
if gm.walkable(tx, ty):
|
|
||||||
p.x, p.y = tx, ty
|
|
||||||
_end_turn(session)
|
|
||||||
return
|
|
||||||
# Bumped a wall: no turn spent (standard roguelike convention).
|
|
||||||
|
|
||||||
|
|
||||||
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:
|
|
||||||
_log(session, f"You hit the {name} for {roll.damage} damage.")
|
|
||||||
if enemy.hp <= 0:
|
|
||||||
_defeat_enemy(session, enemy)
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
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 _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 _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
|
|
||||||
_log(session, f"The {e.name} is caught in the blast. ({dmg} damage)")
|
|
||||||
if e.hp <= 0:
|
|
||||||
_defeat_enemy(session, e)
|
|
||||||
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
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 delete_save() -> None:
|
|
||||||
try:
|
|
||||||
os.remove(_save_path())
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
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,98 +0,0 @@
|
|||||||
"""Procedural sound effects via pygame.mixer.
|
|
||||||
|
|
||||||
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
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import pygame
|
|
||||||
|
|
||||||
_FREQ = 22050
|
|
||||||
_SIZE = -16 # 16-bit signed
|
|
||||||
_CHANNELS = 1
|
|
||||||
_BUFFER = 256
|
|
||||||
|
|
||||||
# (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),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
||||||
|
|
||||||
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.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:
|
|
||||||
if not self.available or self.muted:
|
|
||||||
return
|
|
||||||
snd = self._sounds.get(name) or self._sounds.get("hit")
|
|
||||||
if snd is None:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
snd.play()
|
|
||||||
except Exception:
|
|
||||||
pass # audio is best-effort; never propagate a playback error
|
|
||||||
|
|
||||||
def toggle_mute(self) -> bool:
|
|
||||||
self.muted = not self.muted
|
|
||||||
return self.muted
|
|
||||||
|
|
||||||
|
|
||||||
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,27 +0,0 @@
|
|||||||
"""Combat resolution: hit chance, armor reduction, critical hits."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import random
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class AttackRoll:
|
|
||||||
hit: bool
|
|
||||||
crit: bool
|
|
||||||
damage: int
|
|
||||||
|
|
||||||
|
|
||||||
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,94 +0,0 @@
|
|||||||
"""Recursive shadowcasting field of view over 8 octants."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
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),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
cx, cy = origin
|
|
||||||
r2 = radius * radius
|
|
||||||
visible: set[tuple[int, int]] = {(cx, cy)}
|
|
||||||
|
|
||||||
def blocks(x: int, y: int) -> bool:
|
|
||||||
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
|
|
||||||
for j in range(row, radius + 1):
|
|
||||||
dx = -j - 1
|
|
||||||
dy = -j
|
|
||||||
blocked = False
|
|
||||||
new_start = end
|
|
||||||
while dx <= 0:
|
|
||||||
dx += 1
|
|
||||||
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
|
|
||||||
if end > l_slope:
|
|
||||||
break
|
|
||||||
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
|
|
||||||
blocked = False
|
|
||||||
start = new_start
|
|
||||||
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:
|
|
||||||
cast(1, 1.0, 0.0, xx, xy, yx, yy)
|
|
||||||
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,139 +0,0 @@
|
|||||||
"""GameSession: the single source of truth for all mutable state.
|
|
||||||
|
|
||||||
``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 random
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
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: Any = None
|
|
||||||
dungeon: list = field(default_factory=list)
|
|
||||||
current_floor: int = 0
|
|
||||||
log: list = field(default_factory=list)
|
|
||||||
turn: int = 0
|
|
||||||
state: str = "playing"
|
|
||||||
|
|
||||||
|
|
||||||
# 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)
|
|
||||||
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 descend into the Underdepths."],
|
|
||||||
turn=0,
|
|
||||||
state="playing",
|
|
||||||
)
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
"""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.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
|
|
||||||
class Rect:
|
|
||||||
x: int
|
|
||||||
y: int
|
|
||||||
w: int
|
|
||||||
h: int
|
|
||||||
|
|
||||||
@property
|
|
||||||
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]]
|
|
||||||
rooms: list[Rect]
|
|
||||||
explored: list[list[bool]]
|
|
||||||
visible: list[list[bool]]
|
|
||||||
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 walkable(self, x: int, y: int) -> bool:
|
|
||||||
return self.in_bounds(x, y) and self.tiles[y][x] == FLOOR
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- 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 _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 _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
|
|
||||||
|
|
||||||
|
|
||||||
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:
|
|
||||||
_carve_v(tiles, ay, by, ax)
|
|
||||||
_carve_h(tiles, ax, bx, by)
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- 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:
|
|
||||||
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 _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
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 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
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- 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 _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 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 generate_dungeon(seed: int) -> list[GameMap]:
|
|
||||||
rng = random.Random(seed)
|
|
||||||
return [generate_floor(i, rng) for i in range(FLOOR_COUNT)]
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
"""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 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``.
|
|
||||||
|
|
||||||
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.
|
|
||||||
"""
|
|
||||||
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
|
|
||||||
|
|
||||||
def h(x: int, y: int) -> int:
|
|
||||||
return abs(x - gx) + abs(y - gy)
|
|
||||||
|
|
||||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
|
||||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
|
||||||
counter = 0
|
|
||||||
open_heap: list[tuple[int, int, tuple[int, int]]] = [(h(*start), counter, start)]
|
|
||||||
closed: set[tuple[int, int]] = set()
|
|
||||||
|
|
||||||
while open_heap:
|
|
||||||
_, _, current = heapq.heappop(open_heap)
|
|
||||||
if current in closed:
|
|
||||||
continue
|
|
||||||
if current == goal:
|
|
||||||
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
|
|
||||||
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
|
|
||||||
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 + h(*nxt), counter, nxt))
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
from engine.map_gen import generate_dungeon
|
|
||||||
|
|
||||||
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,124 +0,0 @@
|
|||||||
"""JSON-safe serialization of GameSession for save/load.
|
|
||||||
|
|
||||||
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 dataclasses import fields
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from entities.player import Player
|
|
||||||
from entities.enemy import Enemy
|
|
||||||
from entities.item import Item
|
|
||||||
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"],
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def session_to_dict(session: GameSession) -> dict:
|
|
||||||
return {
|
|
||||||
"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),
|
|
||||||
"state": session.state,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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"],
|
|
||||||
turn=d["turn"],
|
|
||||||
log=list(d["log"]),
|
|
||||||
state=d["state"],
|
|
||||||
)
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
"""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 typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
|
||||||
class Enemy:
|
|
||||||
x: int = 0
|
|
||||||
y: int = 0
|
|
||||||
kind: str = ""
|
|
||||||
name: str = ""
|
|
||||||
hp: int = 1
|
|
||||||
max_hp: int = 1
|
|
||||||
power: int = 1
|
|
||||||
armor: 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: Any = None
|
|
||||||
can_split: bool = False
|
|
||||||
sprite_key: str = ""
|
|
||||||
|
|
||||||
@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,13 +0,0 @@
|
|||||||
"""Base entity: position, identity, sprite key."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
|
||||||
class Entity:
|
|
||||||
x: int
|
|
||||||
y: int
|
|
||||||
name: str
|
|
||||||
sprite_key: str
|
|
||||||
blocks: bool = True
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
"""Item entity: identity + effect/equipment payload.
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
|
||||||
class Item:
|
|
||||||
x: int = 0
|
|
||||||
y: int = 0
|
|
||||||
kind: str = ""
|
|
||||||
name: str = ""
|
|
||||||
category: str = ""
|
|
||||||
stats: dict = field(default_factory=dict)
|
|
||||||
sprite_key: str = ""
|
|
||||||
blocks: bool = False
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
"""Player: stats, inventory, equipment, and leveling."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from data.constants import LEVEL_TABLE, LEVEL_CAP, PLAYER_BASE, STRENGTH_POTION_POWER
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
|
||||||
class Player:
|
|
||||||
x: int = 0
|
|
||||||
y: int = 0
|
|
||||||
name: str = "Adventurer"
|
|
||||||
sprite_key: str = "player"
|
|
||||||
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
|
|
||||||
inventory: 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:
|
|
||||||
return self.power + self.weapon_power
|
|
||||||
|
|
||||||
def total_armor(self) -> int:
|
|
||||||
a = self.armor
|
|
||||||
if self.equipped_armor is not None:
|
|
||||||
a += self.equipped_armor.stats.get("armor", 0)
|
|
||||||
return a
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
def gain_xp(self, amount: int) -> int:
|
|
||||||
self.xp += amount
|
|
||||||
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
|
|
||||||
return gained
|
|
||||||
@@ -1,280 +0,0 @@
|
|||||||
"""Entry point, game loop, and state machine for Underdepths.
|
|
||||||
|
|
||||||
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 sys
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import pygame
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
SCREEN_W = 960
|
|
||||||
SCREEN_H = 600
|
|
||||||
FONT_STACK = "monospace,consolas,couriernew,dejavusans"
|
|
||||||
MAXFRAMES_ENV = "UNDERDEPTHS_MAX_FRAMES"
|
|
||||||
|
|
||||||
_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 new_game(seed: int = 0) -> Any:
|
|
||||||
return new_session(seed)
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- helpers
|
|
||||||
def _font(size: int, bold: bool = False) -> pygame.font.Font:
|
|
||||||
try:
|
|
||||||
return pygame.font.SysFont(FONT_STACK, size, bold=bold)
|
|
||||||
except Exception:
|
|
||||||
return pygame.font.Font(None, size)
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
frame = 0
|
|
||||||
|
|
||||||
while running:
|
|
||||||
for event in pygame.event.get():
|
|
||||||
if event.type == pygame.QUIT:
|
|
||||||
running = False
|
|
||||||
elif event.type == pygame.KEYDOWN:
|
|
||||||
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":
|
|
||||||
session = new_game(seed=0)
|
|
||||||
camera.reset((session.player.x, session.player.y))
|
|
||||||
last_log_len = len(session.log)
|
|
||||||
ui = "howto"
|
|
||||||
elif choice == "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":
|
|
||||||
ui = "howto"
|
|
||||||
elif choice == "Quit":
|
|
||||||
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:
|
|
||||||
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()
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main(sys.argv[1:]))
|
|
||||||
@@ -1,383 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Underdepths self-driving build pipeline.
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
#
|
|
||||||
# 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
|
|
||||||
|
|
||||||
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"
|
|
||||||
|
|
||||||
TTL="${UNDERDEPTHS_TTL:-3000}" # per-dispatch ceiling, seconds (50 min)
|
|
||||||
MAX_RETRIES=3
|
|
||||||
|
|
||||||
PY="${PYTHON:-python3}"
|
|
||||||
|
|
||||||
log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" | tee -a "$LOG"; }
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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=$!
|
|
||||||
|
|
||||||
# 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 "$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
|
|
||||||
log " GATE $*: FAIL"
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
FAILED GATE: python tests/smoke.py $kind
|
|
||||||
Full gate output (stdout+stderr):
|
|
||||||
|
|
||||||
$err
|
|
||||||
|
|
||||||
After fixing, run: python tests/smoke.py $kind
|
|
||||||
Repeat until it prints PASS. Then stop. Do not touch unrelated files.
|
|
||||||
EOF
|
|
||||||
)"
|
|
||||||
run_dispatch "$prompt"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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."
|
|
||||||
|
|
||||||
phase1_build() {
|
|
||||||
run_dispatch "$(cat <<EOF
|
|
||||||
$P_COMMON
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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
|
|
||||||
)"
|
|
||||||
}
|
|
||||||
|
|
||||||
phase2_build() {
|
|
||||||
# Four independent systems, built SEQUENTIALLY (never parallel — shared files).
|
|
||||||
run_dispatch "$(cat <<EOF
|
|
||||||
$P_COMMON
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
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 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
|
|
||||||
|
|
||||||
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
|
|
||||||
)"
|
|
||||||
}
|
|
||||||
|
|
||||||
phase3_build() {
|
|
||||||
run_dispatch "$(cat <<EOF
|
|
||||||
$P_COMMON
|
|
||||||
|
|
||||||
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
|
|
||||||
)"
|
|
||||||
}
|
|
||||||
|
|
||||||
phase4_build() {
|
|
||||||
# Large phase — split into sequential sub-builds BEFORE the single phase gate.
|
|
||||||
run_dispatch "$(cat <<EOF
|
|
||||||
$P_COMMON
|
|
||||||
|
|
||||||
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 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
|
|
||||||
|
|
||||||
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
|
|
||||||
)"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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
|
|
||||||
|
|
||||||
local attempt
|
|
||||||
for attempt in $(seq 1 "$MAX_RETRIES"); do
|
|
||||||
if run_gate --phase "$n"; then
|
|
||||||
return 0
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 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 "$@"
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
"""Rendering package: pure read-and-draw of GameSession."""
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
"""Smooth easing camera that follows the player.
|
|
||||||
|
|
||||||
Stateless from the game's perspective: the camera keeps its own smoothed pixel
|
|
||||||
position (view state, not game state). ``main`` owns the instance and passes the
|
|
||||||
resulting offset to ``Renderer.render``; the renderer itself just applies it.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from data.constants import MAP_W, MAP_H, TILE
|
|
||||||
|
|
||||||
|
|
||||||
class Camera:
|
|
||||||
def __init__(self, smoothing: float = 0.18) -> None:
|
|
||||||
self.x: float = 0.0
|
|
||||||
self.y: float = 0.0
|
|
||||||
self.smoothing = max(0.0, min(1.0, smoothing))
|
|
||||||
|
|
||||||
def reset(self, player_xy: tuple[int, int]) -> None:
|
|
||||||
self.x = float(player_xy[0] * TILE)
|
|
||||||
self.y = float(player_xy[1] * TILE)
|
|
||||||
|
|
||||||
def update(self, player_xy: tuple[int, int]) -> tuple[int, int]:
|
|
||||||
tx = player_xy[0] * TILE
|
|
||||||
ty = player_xy[1] * TILE
|
|
||||||
self.x += (tx - self.x) * self.smoothing
|
|
||||||
self.y += (ty - self.y) * self.smoothing
|
|
||||||
return int(self.x), int(self.y)
|
|
||||||
|
|
||||||
def offset_for(self, surface_wh: tuple[int, int], player_xy: tuple[int, int]) -> tuple[int, int]:
|
|
||||||
"""Center the player on screen, clamped to the map bounds (pixel offset)."""
|
|
||||||
sw, sh = surface_wh
|
|
||||||
px = int(self.x)
|
|
||||||
py = int(self.y)
|
|
||||||
ox = px - sw // 2
|
|
||||||
oy = py - sh // 2
|
|
||||||
max_ox = MAP_W * TILE - sw
|
|
||||||
max_oy = MAP_H * TILE - sh
|
|
||||||
if max_ox <= 0:
|
|
||||||
ox = (MAP_W * TILE - sw) // 2
|
|
||||||
else:
|
|
||||||
ox = max(0, min(max_ox, ox))
|
|
||||||
if max_oy <= 0:
|
|
||||||
oy = (MAP_H * TILE - sh) // 2
|
|
||||||
else:
|
|
||||||
oy = max(0, min(max_oy, oy))
|
|
||||||
return ox, oy
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
"""Render-only effects: screen-shake, particles, and a vignette.
|
|
||||||
|
|
||||||
All state here is view state owned by the Renderer instance, never game state.
|
|
||||||
Lighting (visible bright / explored dimmed / unexplored black + radial falloff)
|
|
||||||
is applied per-tile inside ``renderer``; this module supplies the juice and the
|
|
||||||
edge-darkening vignette overlay.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import math
|
|
||||||
import random
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import pygame
|
|
||||||
|
|
||||||
_MAX_PARTICLES = 160
|
|
||||||
|
|
||||||
|
|
||||||
def torch_factor(dx: int, dy: int, radius: int) -> float:
|
|
||||||
"""Radial torch brightness at a tile offset from the bearer.
|
|
||||||
|
|
||||||
Bright warm core (1.0) graduating smoothly to a dim rim (~0.55) at the
|
|
||||||
sight edge — a soft gradient, not a hard disc. Quadratic falloff keeps the
|
|
||||||
core clearly bright. Chebyshev distance matches the FOV radius so the lit
|
|
||||||
disc stays round; walls occlude light via the visible set computed upstream.
|
|
||||||
"""
|
|
||||||
d = max(abs(dx), abs(dy))
|
|
||||||
if d >= radius:
|
|
||||||
return 0.55
|
|
||||||
t = d / radius
|
|
||||||
return 1.0 - 0.45 * (t * t)
|
|
||||||
|
|
||||||
|
|
||||||
class Shake:
|
|
||||||
"""Decaying screen-shake; returns a pixel offset each frame."""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._mag = 0.0
|
|
||||||
|
|
||||||
def trigger(self, magnitude: float = 6.0) -> None:
|
|
||||||
self._mag = min(10.0, max(self._mag, magnitude))
|
|
||||||
|
|
||||||
def offset(self) -> tuple[int, int]:
|
|
||||||
if self._mag <= 0.05:
|
|
||||||
self._mag = 0.0
|
|
||||||
return 0, 0
|
|
||||||
dx = random.uniform(-1, 1) * self._mag
|
|
||||||
dy = random.uniform(-1, 1) * self._mag
|
|
||||||
self._mag *= 0.82
|
|
||||||
return int(dx), int(dy)
|
|
||||||
|
|
||||||
|
|
||||||
class Particles:
|
|
||||||
"""Pooled, capped particle bursts (hit sparks, blood, level-up stars, etc.)."""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._parts: list[dict[str, Any]] = []
|
|
||||||
|
|
||||||
def burst(self, x: float, y: float, color: tuple[int, int, int],
|
|
||||||
count: int = 10, speed: float = 60.0, life: float = 0.4) -> None:
|
|
||||||
for _ in range(count):
|
|
||||||
if len(self._parts) >= _MAX_PARTICLES:
|
|
||||||
break
|
|
||||||
ang = random.uniform(0, math.tau)
|
|
||||||
spd = speed * random.uniform(0.4, 1.0)
|
|
||||||
self._parts.append({
|
|
||||||
"x": x, "y": y,
|
|
||||||
"vx": math.cos(ang) * spd, "vy": math.sin(ang) * spd,
|
|
||||||
"life": life * random.uniform(0.7, 1.2), "age": 0.0,
|
|
||||||
"color": color, "size": random.randint(2, 3),
|
|
||||||
})
|
|
||||||
|
|
||||||
def update(self, dt: float) -> None:
|
|
||||||
alive: list[dict[str, Any]] = []
|
|
||||||
for p in self._parts:
|
|
||||||
p["age"] += dt
|
|
||||||
if p["age"] >= p["life"]:
|
|
||||||
continue
|
|
||||||
p["x"] += p["vx"] * dt
|
|
||||||
p["y"] += p["vy"] * dt
|
|
||||||
p["vy"] += 90.0 * dt # gentle gravity
|
|
||||||
alive.append(p)
|
|
||||||
self._parts = alive
|
|
||||||
|
|
||||||
def draw(self, surface: pygame.Surface, cam_xy: tuple[int, int]) -> None:
|
|
||||||
ox, oy = cam_xy
|
|
||||||
for p in self._parts:
|
|
||||||
t = 1.0 - p["age"] / p["life"]
|
|
||||||
r = max(1, int(p["size"] * t))
|
|
||||||
c = p["color"]
|
|
||||||
col = (int(c[0] * t), int(c[1] * t), int(c[2] * t))
|
|
||||||
pygame.draw.circle(surface, col, (int(p["x"] - ox), int(p["y"] - oy)), r)
|
|
||||||
|
|
||||||
|
|
||||||
def vignette(size: tuple[int, int]) -> pygame.Surface:
|
|
||||||
"""Soft edge-darkening overlay (cached by size via module dict)."""
|
|
||||||
key = size
|
|
||||||
surf = _VIGNETTE_CACHE.get(key)
|
|
||||||
if surf is not None:
|
|
||||||
return surf
|
|
||||||
w, h = size
|
|
||||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
|
||||||
cx, cy = w / 2, h / 2
|
|
||||||
max_d = math.hypot(cx, cy)
|
|
||||||
# Subtle edge-only vignette: concentric non-overlapping annuli (width=step)
|
|
||||||
# so alpha never accumulates. Only the outer ~38% of the screen darkens; the
|
|
||||||
# center stays clear. Max alpha is gentle so edges are never crushed to black.
|
|
||||||
step = 8
|
|
||||||
inner_t = 0.62 # no darkening inside 62% of the corner distance
|
|
||||||
max_alpha = 78
|
|
||||||
r = int(max_d)
|
|
||||||
while r > 0:
|
|
||||||
t = r / max_d
|
|
||||||
if t > inner_t:
|
|
||||||
u = (t - inner_t) / (1.0 - inner_t)
|
|
||||||
alpha = int(max_alpha * u * u)
|
|
||||||
if alpha > 0:
|
|
||||||
pygame.draw.circle(surf, (0, 0, 0, alpha), (int(cx), int(cy)), r, step)
|
|
||||||
r -= step
|
|
||||||
_VIGNETTE_CACHE[key] = surf
|
|
||||||
return surf
|
|
||||||
|
|
||||||
|
|
||||||
_VIGNETTE_CACHE: dict[tuple[int, int], pygame.Surface] = {}
|
|
||||||
@@ -1,506 +0,0 @@
|
|||||||
"""Pure renderer: composes map tiles, entities, lighting, juice, and UI.
|
|
||||||
|
|
||||||
Reads ``GameSession`` and draws — never mutates game state. Visibility for
|
|
||||||
lighting is DERIVED here via FOV (read-only) so a freshly-built session renders
|
|
||||||
correctly even before the action layer has ticked. Stairs are ALWAYS blitted on
|
|
||||||
``stairs_down`` when in view/remembered (invisible stairs make the game
|
|
||||||
unwinnable).
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import math
|
|
||||||
|
|
||||||
import pygame
|
|
||||||
|
|
||||||
from data.constants import (
|
|
||||||
TILE, SIGHT_RADIUS, COLORS, MAP_W, MAP_H,
|
|
||||||
)
|
|
||||||
from engine.fov import compute_fov
|
|
||||||
from render.sprites import get_tile_sprite
|
|
||||||
from render.effects import Particles, Shake, vignette, torch_factor
|
|
||||||
|
|
||||||
_BG = COLORS["bg"]
|
|
||||||
_FONT_STACK = "monospace,consolas,couriernew,dejavusans"
|
|
||||||
# Sprites rendered larger than one tile (centered on their tile).
|
|
||||||
_BIG_SPRITES = frozenset({"ancient_dragon"})
|
|
||||||
|
|
||||||
|
|
||||||
def _dim(color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
|
|
||||||
return (int(color[0] * factor), int(color[1] * factor), int(color[2] * factor))
|
|
||||||
|
|
||||||
|
|
||||||
def _hash2(x: int, y: int) -> int:
|
|
||||||
return (x * 73856093 ^ y * 19349663) & 0xFF
|
|
||||||
|
|
||||||
|
|
||||||
class Renderer:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self.particles = Particles()
|
|
||||||
self.shake = Shake()
|
|
||||||
self._anim = 0.0
|
|
||||||
self._last_hp: int | None = None
|
|
||||||
self._last_log_len = 0
|
|
||||||
self._font_big: pygame.font.Font | None = None
|
|
||||||
self._font_small: pygame.font.Font | None = None
|
|
||||||
self._font: pygame.font.Font | None = None
|
|
||||||
self._fonts_ok = True
|
|
||||||
self._torch: pygame.Surface | None = None
|
|
||||||
self._glow_surf: pygame.Surface | None = None
|
|
||||||
self._shadow_cache: dict[int, pygame.Surface] = {}
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- fonts
|
|
||||||
def _fonts(self) -> None:
|
|
||||||
if not self._fonts_ok or self._font is not None:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
self._font = pygame.font.SysFont(_FONT_STACK, 16, bold=True)
|
|
||||||
self._font_big = pygame.font.SysFont(_FONT_STACK, 22, bold=True)
|
|
||||||
self._font_small = pygame.font.SysFont(_FONT_STACK, 13, bold=True)
|
|
||||||
except Exception:
|
|
||||||
self._fonts_ok = False
|
|
||||||
|
|
||||||
def _text(self, surf: pygame.Surface, msg: str, pos: tuple[int, int],
|
|
||||||
color: tuple[int, int, int], big: bool = False,
|
|
||||||
small: bool = False) -> None:
|
|
||||||
if self._font is None:
|
|
||||||
return
|
|
||||||
f = self._font_big if big else (self._font_small if small else self._font)
|
|
||||||
try:
|
|
||||||
img = f.render(msg, True, color)
|
|
||||||
surf.blit(img, pos)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- entry
|
|
||||||
def render(self, surface: pygame.Surface, session: Any,
|
|
||||||
camera_xy: tuple[int, int] = (0, 0)) -> None:
|
|
||||||
self._fonts()
|
|
||||||
self._anim += 0.016
|
|
||||||
self.particles.update(0.016)
|
|
||||||
|
|
||||||
gm = session.dungeon[session.current_floor]
|
|
||||||
player = session.player
|
|
||||||
vis = compute_fov(gm, (player.x, player.y), SIGHT_RADIUS)
|
|
||||||
|
|
||||||
cam_x, cam_y = camera_xy
|
|
||||||
sh_x, sh_y = self.shake.offset()
|
|
||||||
ox, oy = cam_x - sh_x, cam_y - sh_y
|
|
||||||
sw, sh = surface.get_size()
|
|
||||||
|
|
||||||
surface.fill(_BG)
|
|
||||||
|
|
||||||
x0 = max(0, ox // TILE)
|
|
||||||
y0 = max(0, oy // TILE)
|
|
||||||
x1 = min(gm.width, (ox + sw) // TILE + 1)
|
|
||||||
y1 = min(gm.height, (oy + sh) // TILE + 1)
|
|
||||||
|
|
||||||
# Visible terrain/entities are drawn to a light layer at FULL brightness,
|
|
||||||
# then a smooth radial torch gradient is multiplied in. That gives a soft
|
|
||||||
# circular falloff with no tile-sized banding. Explored-but-unseen tiles
|
|
||||||
# are drawn dim (cool blue-gray) straight onto the surface; unexplored
|
|
||||||
# stays black. Walls occlude because only FOV-visible tiles reach the
|
|
||||||
# light layer.
|
|
||||||
light = pygame.Surface((sw, sh), pygame.SRCALPHA)
|
|
||||||
|
|
||||||
# ---- terrain ----
|
|
||||||
for ty in range(y0, y1):
|
|
||||||
for tx in range(x0, x1):
|
|
||||||
px, py = tx * TILE - ox, ty * TILE - oy
|
|
||||||
visible = (tx, ty) in vis
|
|
||||||
explored = gm.explored[ty][tx]
|
|
||||||
if not (visible or explored):
|
|
||||||
continue
|
|
||||||
is_wall = not gm.walkable(tx, ty)
|
|
||||||
if visible:
|
|
||||||
if is_wall:
|
|
||||||
self._wall(light, px, py, tx, ty, 1.0)
|
|
||||||
else:
|
|
||||||
self._floor(light, px, py, tx, ty, 1.0)
|
|
||||||
else:
|
|
||||||
if is_wall:
|
|
||||||
self._wall_explored(surface, px, py, tx, ty)
|
|
||||||
else:
|
|
||||||
self._floor_explored(surface, px, py, tx, ty)
|
|
||||||
if (tx, ty) == gm.stairs_down:
|
|
||||||
target = light if visible else surface
|
|
||||||
gsh = self._shadow_surf(TILE)
|
|
||||||
target.blit(gsh, (px + (TILE - gsh.get_width()) // 2,
|
|
||||||
py + TILE - gsh.get_height()))
|
|
||||||
target.blit(get_tile_sprite("stairs"), (px, py))
|
|
||||||
|
|
||||||
# ---- entities (items under, enemies over, player on top) ----
|
|
||||||
for e in gm.entities:
|
|
||||||
if self._is_item(e):
|
|
||||||
if (e.x, e.y) in vis:
|
|
||||||
self._draw_entity(light, e, ox, oy, shadow=True)
|
|
||||||
elif gm.explored[e.y][e.x]:
|
|
||||||
self._draw_entity(surface, e, ox, oy, shadow=True)
|
|
||||||
for e in gm.entities:
|
|
||||||
if self._is_enemy(e) and (e.x, e.y) in vis:
|
|
||||||
self._draw_entity(light, e, ox, oy, shadow=True)
|
|
||||||
# player is always on-screen
|
|
||||||
self._draw_entity(light, player, ox, oy, shadow=True, is_player=True)
|
|
||||||
# keep the descent discoverable: when a sprite stands on the stairs, draw
|
|
||||||
# a translucent yellow '>' peek on top so the staircase is never hidden.
|
|
||||||
if gm.stairs_down is not None:
|
|
||||||
ssx, ssy = gm.stairs_down
|
|
||||||
on_stairs = (player.x, player.y) == (ssx, ssy) or any(
|
|
||||||
getattr(e, "x", -9) == ssx and getattr(e, "y", -9) == ssy for e in gm.entities)
|
|
||||||
if on_stairs and (ssx, ssy) in vis:
|
|
||||||
_peek = get_tile_sprite("stairs").copy()
|
|
||||||
_peek.set_alpha(150)
|
|
||||||
light.blit(_peek, (ssx * TILE - ox, ssy * TILE - oy))
|
|
||||||
|
|
||||||
# smooth radial torch: multiply the light layer by a cached gradient mask
|
|
||||||
mask = self._torch_mask()
|
|
||||||
pcx = player.x * TILE - ox + TILE // 2
|
|
||||||
pcy = player.y * TILE - oy + TILE // 2
|
|
||||||
light.blit(mask, (pcx - mask.get_width() // 2, pcy - mask.get_height() // 2),
|
|
||||||
special_flags=pygame.BLEND_RGB_MULT)
|
|
||||||
surface.blit(light, (0, 0))
|
|
||||||
# warm torch glow at the bearer's feet -> clear bright core
|
|
||||||
glow = self._glow()
|
|
||||||
surface.blit(glow, (pcx - glow.get_width() // 2, pcy - glow.get_height() // 2),
|
|
||||||
special_flags=pygame.BLEND_RGB_ADD)
|
|
||||||
|
|
||||||
self.particles.draw(surface, (ox, oy))
|
|
||||||
self._sense_events(session, vis, ox, oy)
|
|
||||||
surface.blit(vignette((sw, sh)), (0, 0))
|
|
||||||
self._ui(surface, session, sw, sh)
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- tiles
|
|
||||||
def _floor(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
|
|
||||||
f: float) -> None:
|
|
||||||
base = _dim(COLORS["floor_visible"], f)
|
|
||||||
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
|
|
||||||
h = _hash2(tx, ty)
|
|
||||||
fleck = _dim(COLORS["floor_explored"], f)
|
|
||||||
# two deterministic flecks per tile for subtle texture
|
|
||||||
fx = px + (h % (TILE - 4)) + 2
|
|
||||||
fy = py + ((h >> 3) % (TILE - 4)) + 2
|
|
||||||
pygame.draw.rect(surf, fleck, (fx, fy, 2, 2))
|
|
||||||
fx2 = px + ((h >> 2) % (TILE - 4)) + 2
|
|
||||||
fy2 = py + ((h >> 5) % (TILE - 4)) + 2
|
|
||||||
pygame.draw.rect(surf, _dim(COLORS["floor_visible"], f * 1.15), (fx2, fy2, 2, 2))
|
|
||||||
|
|
||||||
def _wall(self, surf: pygame.Surface, px: int, py: int, tx: int, ty: int,
|
|
||||||
f: float = 1.0) -> None:
|
|
||||||
pygame.draw.rect(surf, _dim(COLORS["wall_visible"], f), (px, py, TILE, TILE))
|
|
||||||
pygame.draw.rect(surf, _dim(COLORS["wall_top"], f), (px, py, TILE, 4)) # lit top edge
|
|
||||||
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py + TILE - 4, TILE, 4)) # shaded base
|
|
||||||
# brick seams via per-tile hash
|
|
||||||
h = _hash2(tx, ty)
|
|
||||||
seam = COLORS["wall_explored"]
|
|
||||||
if h & 1:
|
|
||||||
pygame.draw.rect(surf, seam, (px + TILE // 2, py + 4, 1, TILE - 8))
|
|
||||||
if h & 2:
|
|
||||||
pygame.draw.rect(surf, seam, (px + 4, py + TILE // 2, TILE - 8, 1))
|
|
||||||
|
|
||||||
def _floor_explored(self, surf: pygame.Surface, px: int, py: int,
|
|
||||||
tx: int, ty: int) -> None:
|
|
||||||
base = COLORS["floor_explored"]
|
|
||||||
pygame.draw.rect(surf, base, (px, py, TILE, TILE))
|
|
||||||
h = _hash2(tx, ty)
|
|
||||||
pygame.draw.rect(surf, _dim(base, 0.7),
|
|
||||||
(px + (h % (TILE - 4)) + 2, py + ((h >> 3) % (TILE - 4)) + 2, 2, 2))
|
|
||||||
pygame.draw.rect(surf, _dim(base, 1.3),
|
|
||||||
(px + ((h >> 2) % (TILE - 4)) + 2, py + ((h >> 5) % (TILE - 4)) + 2, 2, 2))
|
|
||||||
|
|
||||||
def _wall_explored(self, surf: pygame.Surface, px: int, py: int,
|
|
||||||
tx: int, ty: int) -> None:
|
|
||||||
pygame.draw.rect(surf, COLORS["wall_explored"], (px, py, TILE, TILE))
|
|
||||||
pygame.draw.rect(surf, _dim(COLORS["wall_explored"], 1.35), (px, py, TILE, 3)) # faint top edge
|
|
||||||
|
|
||||||
def _torch_mask(self) -> pygame.Surface:
|
|
||||||
"""Cached smooth radial brightness mask (white core -> gray rim).
|
|
||||||
|
|
||||||
Built tiny then smooth-scaled so the falloff is bilinear-smooth with no
|
|
||||||
tile-sized bands. Multiplied (BLEND_RGB_MULT) onto the light layer.
|
|
||||||
"""
|
|
||||||
if self._torch is not None:
|
|
||||||
return self._torch
|
|
||||||
diam = (SIGHT_RADIUS * TILE + TILE) * 2 # covers the whole FOV disc + rim
|
|
||||||
s = 64
|
|
||||||
small = pygame.Surface((s, s), pygame.SRCALPHA)
|
|
||||||
c = (s - 1) / 2
|
|
||||||
for yy in range(s):
|
|
||||||
for xx in range(s):
|
|
||||||
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
|
|
||||||
b = 0.45 + 0.55 * (1.0 - t) ** 1.5 # 1.0 core -> ~0.45 rim
|
|
||||||
g = int(b * 255)
|
|
||||||
small.set_at((xx, yy), (g, g, g, 255))
|
|
||||||
self._torch = pygame.transform.smoothscale(small, (diam, diam))
|
|
||||||
return self._torch
|
|
||||||
|
|
||||||
def _glow(self) -> pygame.Surface:
|
|
||||||
"""Cached warm radial glow added (BLEND_RGB_ADD) at the torch core so the
|
|
||||||
bright center reads clearly against the dimmer rim."""
|
|
||||||
if self._glow_surf is not None:
|
|
||||||
return self._glow_surf
|
|
||||||
diam = SIGHT_RADIUS * TILE * 2
|
|
||||||
s = 48
|
|
||||||
small = pygame.Surface((s, s), pygame.SRCALPHA)
|
|
||||||
c = (s - 1) / 2
|
|
||||||
for yy in range(s):
|
|
||||||
for xx in range(s):
|
|
||||||
t = min(1.0, math.hypot(xx - c, yy - c) / (s / 2))
|
|
||||||
a = int(78 * (1.0 - t) ** 2.2) # warm add, concentrated at center
|
|
||||||
small.set_at((xx, yy), (a, int(a * 0.85), int(a * 0.4), 255))
|
|
||||||
self._glow_surf = pygame.transform.smoothscale(small, (diam, diam))
|
|
||||||
return self._glow_surf
|
|
||||||
|
|
||||||
def _shadow_surf(self, size: int) -> pygame.Surface:
|
|
||||||
"""Cached soft elliptical ground shadow (~90% tile wide) drawn under an
|
|
||||||
entity/stairs so sprites read as grounded. Built from concentric ellipses
|
|
||||||
with rising alpha toward the center for a feathered edge."""
|
|
||||||
s = self._shadow_cache.get(size)
|
|
||||||
if s is not None:
|
|
||||||
return s
|
|
||||||
w = max(10, int(size * 0.92))
|
|
||||||
h = max(5, int(size * 0.32))
|
|
||||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
|
||||||
for frac, alpha in ((1.0, 95), (0.78, 150), (0.52, 215)):
|
|
||||||
rw = max(2, int(w * frac))
|
|
||||||
rh = max(2, int(h * frac))
|
|
||||||
rect = pygame.Rect((w - rw) // 2, (h - rh) // 2, rw, rh)
|
|
||||||
pygame.draw.ellipse(surf, (0, 0, 0, alpha), rect)
|
|
||||||
self._shadow_cache[size] = surf
|
|
||||||
return surf
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- entities
|
|
||||||
def _draw_entity(self, surf: pygame.Surface, e: Any, ox: int, oy: int,
|
|
||||||
shadow: bool, is_player: bool = False) -> None:
|
|
||||||
key = self._sprite_key(e)
|
|
||||||
px = e.x * TILE - ox
|
|
||||||
py = e.y * TILE - oy
|
|
||||||
scale = 2 if key in _BIG_SPRITES else 1
|
|
||||||
size = TILE * scale
|
|
||||||
# big sprites (the dragon boss) center on the entity tile as a 2x2
|
|
||||||
spx = px - TILE // 2 if scale > 1 else px
|
|
||||||
spy = py - TILE // 2 if scale > 1 else py
|
|
||||||
bob = 0 if is_player else int((1 if scale > 1 else 2) *
|
|
||||||
(0.5 + 0.5 * math.sin(self._anim * 3 + e.x)))
|
|
||||||
if shadow:
|
|
||||||
sh = self._shadow_surf(size)
|
|
||||||
surf.blit(sh, (spx + (size - sh.get_width()) // 2,
|
|
||||||
spy + size - sh.get_height() - (0 if scale > 1 else 1)))
|
|
||||||
sprite = get_tile_sprite(key, size)
|
|
||||||
surf.blit(sprite, (spx, spy - bob))
|
|
||||||
if is_player and getattr(e, "effect_timers", {}).get("invisibility", 0) > 0:
|
|
||||||
veil = pygame.Surface((size, size), pygame.SRCALPHA)
|
|
||||||
veil.fill((90, 140, 220, 90))
|
|
||||||
surf.blit(veil, (spx, spy - bob))
|
|
||||||
# HP pip for hurt enemies
|
|
||||||
if self._is_enemy(e) and 0 < e.hp < e.max_hp:
|
|
||||||
frac = max(0.0, e.hp / e.max_hp)
|
|
||||||
bw = size - 4
|
|
||||||
pygame.draw.rect(surf, (40, 20, 20), (spx + 2, spy - 6, bw, 3))
|
|
||||||
pygame.draw.rect(surf, COLORS["hp_full"], (spx + 2, spy - 6, int(bw * frac), 3))
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _sprite_key(e: Any) -> str:
|
|
||||||
key = getattr(e, "sprite_key", "") or ""
|
|
||||||
if key:
|
|
||||||
return key
|
|
||||||
if getattr(e, "behavior", ""): # enemy without sprite_key
|
|
||||||
return getattr(e, "kind", "goblin") or "goblin"
|
|
||||||
return "player"
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _is_enemy(e: Any) -> bool:
|
|
||||||
return bool(getattr(e, "behavior", "")) and getattr(e, "hp", 1) > 0
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _is_item(e: Any) -> bool:
|
|
||||||
return getattr(e, "category", "") != "" and not getattr(e, "behavior", "")
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- juice sense
|
|
||||||
def _sense_events(self, session: Any, vis: set, ox: int, oy: int) -> None:
|
|
||||||
p = session.player
|
|
||||||
cx = p.x * TILE - ox + TILE // 2
|
|
||||||
cy = p.y * TILE - oy + TILE // 2
|
|
||||||
# player took damage since last frame
|
|
||||||
hp = getattr(p, "hp", None)
|
|
||||||
if self._last_hp is not None and hp is not None and hp < self._last_hp:
|
|
||||||
self.shake.trigger(6.0)
|
|
||||||
self.particles.burst(cx, cy, COLORS["hp_empty"], count=10, speed=80)
|
|
||||||
if hp <= 0:
|
|
||||||
self.particles.burst(cx, cy, (220, 220, 220), count=22, speed=120, life=0.7)
|
|
||||||
self._last_hp = hp
|
|
||||||
# new log lines -> spawn flavor at the player
|
|
||||||
new_lines = session.log[self._last_log_len:]
|
|
||||||
self._last_log_len = len(session.log)
|
|
||||||
for line in new_lines:
|
|
||||||
low = line.lower()
|
|
||||||
if "critical" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=110)
|
|
||||||
elif "you hit" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["player"], count=5, speed=70) # hit sparks
|
|
||||||
elif "defeated" in low or "slew" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["hp_empty"], count=16, speed=100, life=0.6)
|
|
||||||
elif "reach level" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["xp_bar"], count=18, speed=90, life=0.8)
|
|
||||||
elif "pick up" in low or "pickup" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["stairs"], count=10, speed=60)
|
|
||||||
elif "descend" in low:
|
|
||||||
self.particles.burst(cx, cy, COLORS["stairs"], count=14, speed=70)
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- UI
|
|
||||||
def _ui(self, surf: pygame.Surface, session: Any, sw: int, sh: int) -> None:
|
|
||||||
p = session.player
|
|
||||||
# ---- top bar ----
|
|
||||||
self._panel(surf, (0, 0, sw, 28))
|
|
||||||
floor_n = session.current_floor + 1
|
|
||||||
self._text(surf, f"Floor {floor_n}/10", (6, 6), COLORS["text"])
|
|
||||||
|
|
||||||
# HP: pixel-art heart icon + red track / green fill
|
|
||||||
hx, hy, hw = 156, 8, 140
|
|
||||||
self._heart(surf, 134, 6)
|
|
||||||
pygame.draw.rect(surf, COLORS["hp_empty"], (hx, hy, hw, 12))
|
|
||||||
frac = max(0.0, p.hp / max(1, p.max_hp))
|
|
||||||
pygame.draw.rect(surf, COLORS["hp_full"], (hx, hy, int(hw * frac), 12))
|
|
||||||
pygame.draw.rect(surf, COLORS["panel_border"], (hx, hy, hw, 12), 1)
|
|
||||||
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + hw + 5, 6), COLORS["text"])
|
|
||||||
|
|
||||||
# Level/XP: star icon + Lv + XP bar (right side)
|
|
||||||
star_x = sw - 252
|
|
||||||
self._star(surf, star_x, 6)
|
|
||||||
self._text(surf, f"Lv {p.level}", (star_x + 16, 6), COLORS["text"])
|
|
||||||
xx, xw = sw - 170, 112
|
|
||||||
pygame.draw.rect(surf, (30, 30, 40), (xx, 10, xw, 8))
|
|
||||||
lvl = min(max(1, p.level), 9)
|
|
||||||
need = [30, 70, 140, 250, 400, 600, 850, 1150, 1500][lvl - 1]
|
|
||||||
prev = [0, 30, 70, 140, 250, 400, 600, 850, 1150][lvl - 1]
|
|
||||||
xpfrac = max(0.0, min(1.0, (p.xp - prev) / max(1, need - prev)))
|
|
||||||
pygame.draw.rect(surf, COLORS["xp_bar"], (xx, 10, int(xw * xpfrac), 8))
|
|
||||||
pygame.draw.rect(surf, COLORS["panel_border"], (xx, 10, xw, 8), 1)
|
|
||||||
|
|
||||||
# ---- right log panel: full-height side panel, color-coded, no clipping ----
|
|
||||||
panel_x, panel_w, line_h = sw - 262, 258, 14
|
|
||||||
panel_top, panel_bottom = 34, sh - 34
|
|
||||||
self._panel(surf, (panel_x, panel_top, panel_w, panel_bottom - panel_top))
|
|
||||||
self._text(surf, "Messages", (panel_x + 6, panel_top + 4), COLORS["text_dim"], small=True)
|
|
||||||
text_x, max_w = panel_x + 6, panel_w - 12
|
|
||||||
# newest at the bottom; word-wrap long lines so nothing is cut off
|
|
||||||
shown = session.log[-8:]
|
|
||||||
wrapped: list[tuple[str, tuple[int, int, int]]] = []
|
|
||||||
for line in shown:
|
|
||||||
wrapped.extend((w, self._log_color(line)) for w in self._wrap(line, max_w))
|
|
||||||
y = panel_bottom - 6 - line_h * len(wrapped)
|
|
||||||
for msg, col in wrapped:
|
|
||||||
if y >= panel_top + 20:
|
|
||||||
self._text(surf, msg, (text_x, y), col, small=True)
|
|
||||||
y += line_h
|
|
||||||
|
|
||||||
# ---- bottom equipment bar: icon slots, not bare text ----
|
|
||||||
self._panel(surf, (0, sh - 30, sw, 30))
|
|
||||||
slot_y = sh - 27
|
|
||||||
nx = self._equip_slot(surf, 6, slot_y, p.equipped_weapon)
|
|
||||||
nx = self._equip_slot(surf, nx + 8, slot_y, p.equipped_armor)
|
|
||||||
self._text(surf, f"Pack: {len(p.inventory)}", (nx + 10, sh - 22), COLORS["text_dim"])
|
|
||||||
eff = ", ".join(f"{k}:{v}" for k, v in p.effect_timers.items())
|
|
||||||
if eff:
|
|
||||||
self._text(surf, f"[{eff}]", (sw // 2 - 40, sh - 22), COLORS["xp_bar"])
|
|
||||||
|
|
||||||
# ---- styled context prompt ----
|
|
||||||
prompt = self._context_prompt(session)
|
|
||||||
if prompt:
|
|
||||||
pw = self._font.size(prompt)[0] if self._font else 130
|
|
||||||
pill = pygame.Surface((pw + 16, 19), pygame.SRCALPHA)
|
|
||||||
pygame.draw.rect(pill, (18, 16, 22, 215), pill.get_rect(), border_radius=4)
|
|
||||||
pygame.draw.rect(pill, (*COLORS["stairs"], 190), pill.get_rect(), 1, border_radius=4)
|
|
||||||
surf.blit(pill, (4, sh - 53))
|
|
||||||
self._text(surf, prompt, (12, sh - 50), COLORS["stairs"])
|
|
||||||
|
|
||||||
# --------------------------------------------------------------- UI helpers
|
|
||||||
@staticmethod
|
|
||||||
def _log_color(line: str) -> tuple[int, int, int]:
|
|
||||||
low = line.lower()
|
|
||||||
if any(w in low for w in ("slain", "died", "wound", "damage to you", "fizzle")):
|
|
||||||
return COLORS["log_bad"] # damage-taken / death -> red
|
|
||||||
if any(w in low for w in ("reach level", "defeated", "slew", "level up")):
|
|
||||||
return COLORS["log_good"] # level-up / kill -> green
|
|
||||||
if any(w in low for w in ("pick up", "pickup", "descend", "quaff",
|
|
||||||
"you read", "equip", "stairs", "reveals")):
|
|
||||||
return COLORS["stairs"] # items / stairs -> yellow
|
|
||||||
return COLORS["text"] # combat / hit / miss / crit -> white
|
|
||||||
|
|
||||||
def _fit_text(self, text: str, max_w: int, small: bool = False) -> str:
|
|
||||||
f = self._font_small if small else self._font
|
|
||||||
if f is None or f.size(text)[0] <= max_w:
|
|
||||||
return text
|
|
||||||
ell = "…"
|
|
||||||
while text and f.size(text + ell)[0] > max_w:
|
|
||||||
text = text[:-1]
|
|
||||||
return (text + ell) if text else ""
|
|
||||||
|
|
||||||
def _wrap(self, text: str, max_w: int) -> list[str]:
|
|
||||||
"""Word-wrap text to <= max_w px per line (greedy). Returns >=1 line."""
|
|
||||||
f = self._font_small
|
|
||||||
if f is None:
|
|
||||||
return [text]
|
|
||||||
words = text.split()
|
|
||||||
lines: list[str] = []
|
|
||||||
cur = ""
|
|
||||||
for w in words:
|
|
||||||
trial = w if not cur else cur + " " + w
|
|
||||||
if f.size(trial)[0] <= max_w or not cur:
|
|
||||||
cur = trial
|
|
||||||
else:
|
|
||||||
lines.append(cur)
|
|
||||||
cur = w
|
|
||||||
if cur:
|
|
||||||
lines.append(cur)
|
|
||||||
return lines or [""]
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _heart(surf: pygame.Surface, x: int, y: int) -> None:
|
|
||||||
c = COLORS["heart"]
|
|
||||||
pygame.draw.circle(surf, c, (x + 4, y + 4), 4)
|
|
||||||
pygame.draw.circle(surf, c, (x + 10, y + 4), 4)
|
|
||||||
pygame.draw.polygon(surf, c, [(x, y + 5), (x + 14, y + 5), (x + 7, y + 13)])
|
|
||||||
surf.set_at((x + 7, y + 2), (90, 16, 20)) # top cleft
|
|
||||||
surf.set_at((x + 3, y + 3), (255, 160, 170)) # highlight
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _star(surf: pygame.Surface, x: int, y: int) -> None:
|
|
||||||
cx, cy = x + 7, y + 7
|
|
||||||
pts = []
|
|
||||||
for i in range(10):
|
|
||||||
ang = -math.pi / 2 + i * math.pi / 5
|
|
||||||
rr = 7 if i % 2 == 0 else 3
|
|
||||||
pts.append((cx + rr * math.cos(ang), cy + rr * math.sin(ang)))
|
|
||||||
pygame.draw.polygon(surf, COLORS["star"], pts)
|
|
||||||
pygame.draw.polygon(surf, (120, 80, 20), pts, 1)
|
|
||||||
|
|
||||||
def _equip_slot(self, surf: pygame.Surface, x: int, y: int,
|
|
||||||
item: Any) -> int:
|
|
||||||
box = 24
|
|
||||||
pygame.draw.rect(surf, COLORS["panel"], (x, y, box, box))
|
|
||||||
pygame.draw.rect(surf, COLORS["panel_border"], (x, y, box, box), 1)
|
|
||||||
if item is not None:
|
|
||||||
kind = getattr(item, "kind", "") or getattr(item, "sprite_key", "")
|
|
||||||
surf.blit(get_tile_sprite(kind, 20), (x + 2, y + 2))
|
|
||||||
name = self._fit_text(item.name, 124)
|
|
||||||
self._text(surf, name, (x + box + 3, y + 6), COLORS["text"])
|
|
||||||
return x + box + 130
|
|
||||||
self._text(surf, "—", (x + 9, y + 5), COLORS["text_dim"])
|
|
||||||
self._text(surf, "empty", (x + box + 3, y + 6), COLORS["text_dim"])
|
|
||||||
return x + box + 52
|
|
||||||
|
|
||||||
def _context_prompt(self, session: Any) -> str:
|
|
||||||
p = session.player
|
|
||||||
gm = session.dungeon[session.current_floor]
|
|
||||||
item = next((e for e in gm.entities
|
|
||||||
if self._is_item(e) and e.x == p.x and e.y == p.y), None)
|
|
||||||
if item is not None:
|
|
||||||
return f"Press G to pick up {item.name}"
|
|
||||||
if gm.stairs_down == (p.x, p.y):
|
|
||||||
return "Press F to descend"
|
|
||||||
return ""
|
|
||||||
|
|
||||||
def _panel(self, surf: pygame.Surface, rect: tuple[int, int, int, int]) -> None:
|
|
||||||
pygame.draw.rect(surf, COLORS["panel"], rect)
|
|
||||||
pygame.draw.rect(surf, COLORS["panel_border"], rect, 1)
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
"""Rasterize palette-key grids to cached pygame Surfaces.
|
|
||||||
|
|
||||||
``get_sprite(name)`` returns the native-size cached Surface; the renderer scales
|
|
||||||
it to ``TILE`` via ``get_tile_sprite``. All art is procedural (pygame.draw /
|
|
||||||
set_at from in-code palettes); no external image files are loaded.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import pygame
|
|
||||||
|
|
||||||
from data import sprites as SPRITE_DATA
|
|
||||||
from data.constants import PALETTE, TILE
|
|
||||||
|
|
||||||
_NATIVE: dict[str, pygame.Surface] = {}
|
|
||||||
_SCALED: dict[str, pygame.Surface] = {}
|
|
||||||
|
|
||||||
|
|
||||||
def _color(ch: str, tint: tuple[int, int, int] | None) -> tuple[int, int, int] | None:
|
|
||||||
if ch == "a":
|
|
||||||
return tint if tint is not None else (200, 200, 200)
|
|
||||||
return PALETTE.get(ch)
|
|
||||||
|
|
||||||
|
|
||||||
def _rasterize(grid: list[str], tint: tuple[int, int, int] | None) -> pygame.Surface:
|
|
||||||
h = len(grid)
|
|
||||||
w = max((len(row) for row in grid), default=1)
|
|
||||||
w = max(1, w)
|
|
||||||
surf = pygame.Surface((w, h), pygame.SRCALPHA)
|
|
||||||
for y, row in enumerate(grid):
|
|
||||||
for x, ch in enumerate(row):
|
|
||||||
c = _color(ch, tint)
|
|
||||||
if c is not None:
|
|
||||||
surf.set_at((x, y), (c[0], c[1], c[2], 255))
|
|
||||||
return surf
|
|
||||||
|
|
||||||
|
|
||||||
def _convert(surf: pygame.Surface) -> pygame.Surface:
|
|
||||||
try:
|
|
||||||
return surf.convert_alpha()
|
|
||||||
except Exception:
|
|
||||||
return surf # no display yet (e.g. constructed before set_mode): use raw
|
|
||||||
|
|
||||||
|
|
||||||
def _make_dragon() -> pygame.Surface:
|
|
||||||
"""Procedural 2x2 boss dragon: ONE connected silhouette (wings+body+head+tail
|
|
||||||
drawn in the same red with no internal outlines, so it reads as a single
|
|
||||||
creature, not separate blobs), then details layered on top."""
|
|
||||||
size = TILE * 2
|
|
||||||
s = pygame.Surface((size, size), pygame.SRCALPHA)
|
|
||||||
K = (16, 14, 20); n = (140, 42, 42); r = (208, 66, 54); H = (172, 54, 54)
|
|
||||||
h = (235, 235, 235); y = (246, 206, 86); amber = (222, 156, 60)
|
|
||||||
|
|
||||||
def poly(col, pts):
|
|
||||||
pygame.draw.polygon(s, col, pts)
|
|
||||||
|
|
||||||
def ell(col, cx, cy, rw, rh):
|
|
||||||
pygame.draw.ellipse(s, col, pygame.Rect(cx - rw, cy - rh, rw * 2, rh * 2))
|
|
||||||
|
|
||||||
# ---- single connected red silhouette: wings sweep up-out, body+head capsule ----
|
|
||||||
poly(r, [(20, 16), (5, 7), (2, 15), (7, 20), (13, 17), (20, 21)]) # left wing
|
|
||||||
poly(r, [(20, 16), (35, 7), (38, 15), (33, 20), (27, 17), (20, 21)]) # right wing
|
|
||||||
ell(r, 20, 22, 7, 13) # body + head capsule
|
|
||||||
poly(r, [(17, 34), (23, 34), (27, 39), (13, 39)]) # tail
|
|
||||||
# wing membrane shading (darker), inside the wings only
|
|
||||||
poly(n, [(16, 15), (6, 9), (4, 14), (9, 18), (13, 16)])
|
|
||||||
poly(n, [(24, 15), (34, 9), (36, 14), (31, 18), (27, 16)])
|
|
||||||
pygame.draw.line(s, H, (20, 17), (6, 9), 1) # finger bones
|
|
||||||
pygame.draw.line(s, H, (20, 17), (13, 16), 1)
|
|
||||||
pygame.draw.line(s, H, (20, 17), (34, 9), 1)
|
|
||||||
pygame.draw.line(s, H, (20, 17), (27, 16), 1)
|
|
||||||
# ---- details ----
|
|
||||||
for sx in (16, 20, 24): # dorsal spines
|
|
||||||
poly(H, [(sx - 1, 10), (sx + 1, 10), (sx, 5)])
|
|
||||||
ell(y, 20, 28, 4, 5) # fiery belly
|
|
||||||
for by in (26, 29, 32):
|
|
||||||
pygame.draw.line(s, amber, (17, by), (23, by), 1)
|
|
||||||
poly(h, [(15, 10), (10, 2), (13, 2), (17, 9)]) # horns
|
|
||||||
poly(h, [(25, 10), (30, 2), (27, 2), (23, 9)])
|
|
||||||
pygame.draw.line(s, H, (14, 14), (17, 14), 1) # brows
|
|
||||||
pygame.draw.line(s, H, (23, 14), (26, 14), 1)
|
|
||||||
pygame.draw.circle(s, y, (17, 16), 2) # eyes
|
|
||||||
pygame.draw.circle(s, y, (23, 16), 2)
|
|
||||||
pygame.draw.line(s, K, (17, 15), (17, 17), 1)
|
|
||||||
pygame.draw.line(s, K, (23, 15), (23, 17), 1)
|
|
||||||
pygame.draw.circle(s, K, (19, 19), 1) # nostrils
|
|
||||||
pygame.draw.circle(s, K, (21, 19), 1)
|
|
||||||
poly(h, [(18, 18), (17, 21), (19, 19)]) # fangs
|
|
||||||
poly(h, [(22, 18), (23, 21), (21, 19)])
|
|
||||||
for fx in (16, 24): # claws
|
|
||||||
pygame.draw.line(s, h, (fx - 2, 35), (fx - 2, 38), 1)
|
|
||||||
pygame.draw.line(s, h, (fx, 35), (fx, 38), 1)
|
|
||||||
pygame.draw.line(s, h, (fx + 2, 35), (fx + 2, 38), 1)
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
def get_sprite(name: str) -> pygame.Surface:
|
|
||||||
"""Native-size cached sprite for ``name`` (transparent background)."""
|
|
||||||
if name in _NATIVE:
|
|
||||||
return _NATIVE[name]
|
|
||||||
if name == "ancient_dragon":
|
|
||||||
surf = _convert(_make_dragon())
|
|
||||||
_NATIVE[name] = surf
|
|
||||||
return surf
|
|
||||||
grid = SPRITE_DATA.GRIDS.get(name)
|
|
||||||
if grid is None:
|
|
||||||
grid = SPRITE_DATA.GRIDS["player"] # safe fallback
|
|
||||||
tint = SPRITE_DATA.TINTS.get(name)
|
|
||||||
surf = _convert(_rasterize(grid, tint))
|
|
||||||
_NATIVE[name] = surf
|
|
||||||
return surf
|
|
||||||
|
|
||||||
|
|
||||||
def get_tile_sprite(name: str, size: int = TILE) -> pygame.Surface:
|
|
||||||
"""Sprite scaled to ``size`` (cached per name+size)."""
|
|
||||||
key = f"{name}@{size}"
|
|
||||||
if key in _SCALED:
|
|
||||||
return _SCALED[key]
|
|
||||||
native = get_sprite(name)
|
|
||||||
scaled = pygame.transform.scale(native, (size, size))
|
|
||||||
_SCALED[key] = scaled
|
|
||||||
return scaled
|
|
||||||
|
|
||||||
|
|
||||||
def clear_cache() -> None:
|
|
||||||
_NATIVE.clear()
|
|
||||||
_SCALED.clear()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
pygame.init()
|
|
||||||
pygame.display.set_mode((16, 16))
|
|
||||||
s = get_sprite("stairs")
|
|
||||||
opaque = yellow = 0
|
|
||||||
for yy in range(s.get_height()):
|
|
||||||
for xx in range(s.get_width()):
|
|
||||||
c = s.get_at((xx, yy))
|
|
||||||
if c.a == 0:
|
|
||||||
continue
|
|
||||||
opaque += 1
|
|
||||||
if c.r > 120 and c.g > 100 and c.b < 110:
|
|
||||||
yellow += 1
|
|
||||||
print(f"stairs {s.get_size()} opaque={opaque} yellow={yellow}")
|
|
||||||
assert opaque > 0 and yellow > 0, "stairs sprite not yellow/opaque"
|
|
||||||
for n in ("player", "rat", "goblin", "skeleton_archer", "orc_warrior",
|
|
||||||
"wraith", "green_slime", "ancient_dragon", "healing_potion", "war_hammer"):
|
|
||||||
g = get_sprite(n)
|
|
||||||
assert g.get_width() >= 4 and g.get_height() >= 4, n
|
|
||||||
print("sprites self-check: OK")
|
|
||||||
pygame.quit()
|
|
||||||
|
Before Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 44 KiB |
@@ -1,855 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Underdepths phase gates + goal backstop.
|
|
||||||
|
|
||||||
This is the build CONTRACT. Each phase gate imports only the modules that phase
|
|
||||||
is expected to produce (imports live inside the function body), so running one
|
|
||||||
phase never fails on another phase's missing code.
|
|
||||||
|
|
||||||
Run:
|
|
||||||
python tests/smoke.py --phase N # single phase gate
|
|
||||||
python tests/smoke.py --goal # full acceptance / headless playthrough
|
|
||||||
python tests/smoke.py # all phases 1..4 then goal
|
|
||||||
|
|
||||||
Headless by default for anything that touches pygame: we set the dummy SDL
|
|
||||||
drivers ONLY here in the harness (never in game code). Exit code 0 == PASS.
|
|
||||||
|
|
||||||
API CONTRACT the game must implement (phase prompts mirror this exactly):
|
|
||||||
data/constants.py:
|
|
||||||
TILE=20, MAP_W=80, MAP_H=50, SIGHT_RADIUS=8, FLOOR_COUNT=10, PALETTE, COLORS
|
|
||||||
|
|
||||||
engine/map_gen.py:
|
|
||||||
@dataclass Rect: x,y,w,h -> .center: tuple[int,int], .intersects(other)->bool
|
|
||||||
@dataclass(slots=True) GameMap: width,height,tiles(list[list[int]] 0=wall/1=floor),
|
|
||||||
rooms(list[Rect]), explored(list[list[bool]]), visible(list[list[bool]]),
|
|
||||||
entities(list), stairs_down(tuple|None), spawn(tuple|None), floor_index(int)
|
|
||||||
.walkable(x,y)->bool, .in_bounds(x,y)->bool
|
|
||||||
generate_dungeon(seed:int)->list[GameMap] # all 10 floors
|
|
||||||
generate_floor(floor_index:int, rng:random.Random)->GameMap
|
|
||||||
|
|
||||||
engine/fov.py:
|
|
||||||
compute_fov(game_map, origin:tuple, radius:int=8)->set[tuple[int,int]]
|
|
||||||
|
|
||||||
engine/pathfinding.py:
|
|
||||||
find_path(game_map, start, goal, blocked=frozenset())->list[tuple]|None
|
|
||||||
# excludes start, includes goal; [] when start==goal; None if unreachable
|
|
||||||
|
|
||||||
engine/combat.py:
|
|
||||||
@dataclass AttackRoll: hit:bool, crit:bool, damage:int
|
|
||||||
roll_attack(attacker, defender, rng=random)->AttackRoll
|
|
||||||
# reads .accuracy .evasion .power .armor .crit_chance (+optional .weapon_power)
|
|
||||||
|
|
||||||
ai/behaviors.py:
|
|
||||||
act_enemy(enemy, game_map, player, visible:set, rng)->None
|
|
||||||
# reads/writes enemy.x/.y/.last_known_pos; adjacent->attack via combat
|
|
||||||
|
|
||||||
entities/entity.py: @dataclass(slots=True) Entity: x,y,name,sprite_key,blocks=True
|
|
||||||
entities/player.py: Player with hp,max_hp,power,armor,accuracy,evasion,crit_chance,
|
|
||||||
level,xp,inventory,equipped_weapon,equipped_armor,effect_timers;
|
|
||||||
.total_power()->int .total_armor()->int .gain_xp(amount)->int
|
|
||||||
entities/enemy.py: Enemy: x,y,kind,name,hp,max_hp,power,armor,accuracy,evasion,
|
|
||||||
crit_chance,speed,behavior,xp_value,last_known_pos,can_split,sprite_key
|
|
||||||
entities/item.py: Item: x,y,kind,name,category,stats(dict)
|
|
||||||
|
|
||||||
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
|
|
||||||
data/items.py: ITEM_DEFS dict; make_item(kind,x,y)->Item
|
|
||||||
|
|
||||||
engine/game_state.py: @dataclass(slots=True) GameSession:
|
|
||||||
player,dungeon(list[GameMap]),current_floor,log(list[str]),turn,state(str)
|
|
||||||
|
|
||||||
engine/serializers.py: session_to_dict(session)->dict ; session_from_dict(d)->GameSession
|
|
||||||
engine/actions.py: apply_input(session, key:str)->None # 'g','f','up',... mutates session
|
|
||||||
engine/audio.py: AudioEngine(enabled=True): .play(name) .toggle_mute() .muted .available
|
|
||||||
|
|
||||||
render/sprites.py: get_sprite(name)->pygame.Surface (cached), incl. 'stairs'
|
|
||||||
render/renderer.py: Renderer with .render(surface, session, camera_xy=(0,0))
|
|
||||||
render/camera.py, render/effects.py: lighting/particles/shake helpers
|
|
||||||
|
|
||||||
main.py: def main(argv=None)->int ; detects SDL_VIDEODRIVER=='dummy' for headless;
|
|
||||||
honors env UNDERDEPTHHS_MAX_FRAMES (sic, see below) to exit after N frames;
|
|
||||||
exposes new_game()->GameSession.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import random
|
|
||||||
import argparse
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
# Harness-only headless setup. Game code must NEVER force these.
|
|
||||||
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
|
|
||||||
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
|
|
||||||
# main.py reads UNDERDEPTHS_MAX_FRAMES to bound a headless run.
|
|
||||||
os.environ.setdefault("UNDERDEPTHS_MAX_FRAMES", "30")
|
|
||||||
|
|
||||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
if ROOT not in sys.path:
|
|
||||||
sys.path.insert(0, ROOT)
|
|
||||||
|
|
||||||
# Max frame budget honored by main.py when launched headless.
|
|
||||||
MAXFRAMES_ENV = "UNDERDEPTHS_MAX_FRAMES"
|
|
||||||
|
|
||||||
PASS = "PASS"
|
|
||||||
FAIL = "FAIL"
|
|
||||||
SKIP = "SKIP"
|
|
||||||
|
|
||||||
|
|
||||||
def _ok(msg): print(msg)
|
|
||||||
def _fail(msg): print(msg)
|
|
||||||
|
|
||||||
|
|
||||||
def flood_reachable(walkable, start, w, h):
|
|
||||||
"""Set of tiles reachable from start over walkable(x,y)->True terrain."""
|
|
||||||
from collections import deque
|
|
||||||
sx, sy = start
|
|
||||||
if not (0 <= sx < w and 0 <= sy < h):
|
|
||||||
return set()
|
|
||||||
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 < w and 0 <= ny < h and walkable(nx, ny):
|
|
||||||
seen.add((nx, ny))
|
|
||||||
dq.append((nx, ny))
|
|
||||||
return seen
|
|
||||||
|
|
||||||
|
|
||||||
class StubMap:
|
|
||||||
"""Minimal map object for FOV/pathfinding/AI gates (decoupled from GameMap)."""
|
|
||||||
def __init__(self, tiles):
|
|
||||||
self.tiles = tiles
|
|
||||||
self.height = len(tiles)
|
|
||||||
self.width = len(tiles[0]) if tiles else 0
|
|
||||||
self.stairs_down = None
|
|
||||||
self.spawn = None
|
|
||||||
self.rooms = []
|
|
||||||
self.floor_index = 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
|
|
||||||
|
|
||||||
|
|
||||||
def open_map(w, h):
|
|
||||||
return StubMap([[1 for _ in range(w)] for _ in range(h)])
|
|
||||||
|
|
||||||
|
|
||||||
def grid_set(tiles, x, y, v):
|
|
||||||
tiles[y][x] = v
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- phase 1
|
|
||||||
def phase1():
|
|
||||||
from engine import map_gen
|
|
||||||
|
|
||||||
def check_floor(gm, seed, fi):
|
|
||||||
errs = []
|
|
||||||
if len(gm.rooms) < 3:
|
|
||||||
errs.append(f"floor {fi}: only {len(gm.rooms)} rooms (need >=3)")
|
|
||||||
# no room overlaps
|
|
||||||
for i in range(len(gm.rooms)):
|
|
||||||
for j in range(i + 1, len(gm.rooms)):
|
|
||||||
if gm.rooms[i].intersects(gm.rooms[j]):
|
|
||||||
errs.append(f"floor {fi}: rooms {i},{j} overlap")
|
|
||||||
if gm.stairs_down is None:
|
|
||||||
errs.append(f"floor {fi}: stairs_down is None")
|
|
||||||
else:
|
|
||||||
sx, sy = gm.stairs_down
|
|
||||||
if not gm.walkable(sx, sy):
|
|
||||||
errs.append(f"floor {fi}: stairs not on a floor tile ({sx},{sy})")
|
|
||||||
if gm.spawn is None:
|
|
||||||
errs.append(f"floor {fi}: spawn is None")
|
|
||||||
else:
|
|
||||||
if not gm.walkable(*gm.spawn):
|
|
||||||
errs.append(f"floor {fi}: spawn not walkable")
|
|
||||||
# reachability: every room reachable + stairs reachable from spawn
|
|
||||||
if gm.spawn is not None:
|
|
||||||
reach = flood_reachable(gm.walkable, gm.spawn, gm.width, gm.height)
|
|
||||||
for ri, r in enumerate(gm.rooms):
|
|
||||||
rx0, ry0 = r.x, r.y
|
|
||||||
rx1, ry1 = r.x + r.w, r.y + r.h
|
|
||||||
if not any((x, y) in reach
|
|
||||||
for y in range(ry0, ry1) for x in range(rx0, rx1)
|
|
||||||
if gm.walkable(x, y)):
|
|
||||||
errs.append(f"floor {fi}: room {ri} unreachable from spawn")
|
|
||||||
if gm.stairs_down is not None and gm.stairs_down not in reach:
|
|
||||||
errs.append(f"floor {fi}: stairs unreachable from spawn")
|
|
||||||
return errs
|
|
||||||
|
|
||||||
all_errs = []
|
|
||||||
for seed in (1, 2, 3, 4, 5):
|
|
||||||
dungeon = map_gen.generate_dungeon(seed=seed)
|
|
||||||
if len(dungeon) != 10:
|
|
||||||
all_errs.append(f"seed {seed}: generate_dungeon returned {len(dungeon)} floors (need 10)")
|
|
||||||
continue
|
|
||||||
for fi in range(9): # floors 0..8 have stairs
|
|
||||||
all_errs.extend(check_floor(dungeon[fi], seed, fi))
|
|
||||||
# floor 9 = boss arena: no descent
|
|
||||||
boss = dungeon[9]
|
|
||||||
if boss.stairs_down is not None:
|
|
||||||
all_errs.append(f"seed {seed}: floor 9 must have NO stairs_down (boss arena)")
|
|
||||||
|
|
||||||
# ASCII render of one floor to visually confirm stairs placement
|
|
||||||
g0 = map_gen.generate_dungeon(seed=7)[0]
|
|
||||||
print("--- ASCII floor 0 (seed 7) ---")
|
|
||||||
for y in range(g0.height):
|
|
||||||
row = []
|
|
||||||
for x in range(g0.width):
|
|
||||||
if g0.stairs_down == (x, y):
|
|
||||||
row.append(">")
|
|
||||||
elif g0.spawn == (x, y):
|
|
||||||
row.append("@")
|
|
||||||
elif g0.walkable(x, y):
|
|
||||||
row.append(".")
|
|
||||||
else:
|
|
||||||
row.append("#")
|
|
||||||
print("".join(row))
|
|
||||||
print("--- end ASCII ---")
|
|
||||||
|
|
||||||
if all_errs:
|
|
||||||
for e in all_errs[:30]:
|
|
||||||
_fail(" " + e)
|
|
||||||
return False
|
|
||||||
_ok("phase 1: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- phase 2
|
|
||||||
def phase2():
|
|
||||||
from engine import fov as fov_mod
|
|
||||||
from engine import pathfinding as pf_mod
|
|
||||||
from engine import combat as cb_mod
|
|
||||||
|
|
||||||
errs = []
|
|
||||||
|
|
||||||
# --- FOV: radius bound + open field sees a lot ---
|
|
||||||
gm = open_map(40, 40)
|
|
||||||
vis = fov_mod.compute_fov(gm, (20, 20), radius=8)
|
|
||||||
if (20, 20) not in vis:
|
|
||||||
errs.append("FOV: origin not visible")
|
|
||||||
if (29, 20) in vis: # distance 9 > radius 8
|
|
||||||
errs.append("FOV: tile beyond radius is visible")
|
|
||||||
if (25, 20) not in vis: # distance 5 within radius, open
|
|
||||||
errs.append("FOV: in-radius open tile not visible")
|
|
||||||
if len(vis) < 100:
|
|
||||||
errs.append(f"FOV: open field visible count suspiciously low ({len(vis)})")
|
|
||||||
|
|
||||||
# --- FOV: wall blocks line of sight ---
|
|
||||||
gm2 = open_map(40, 40)
|
|
||||||
for y in range(40):
|
|
||||||
gm2.tiles[y][15] = 0 # vertical wall column at x=15
|
|
||||||
vis2 = fov_mod.compute_fov(gm2, (10, 20), radius=15)
|
|
||||||
if (20, 20) in vis2:
|
|
||||||
errs.append("FOV: tile behind a solid wall column is visible (LOS leak)")
|
|
||||||
if (15, 20) not in vis2:
|
|
||||||
errs.append("FOV: the blocking wall itself (adjacent to visible floor) should be visible")
|
|
||||||
|
|
||||||
# --- FOV: walled-in player sees only itself + immediate walls ---
|
|
||||||
gm3 = open_map(11, 11)
|
|
||||||
for y in range(11):
|
|
||||||
for x in range(11):
|
|
||||||
gm3.tiles[y][x] = 0 # all walls
|
|
||||||
gm3.tiles[5][5] = 1 # single floor tile the player stands on
|
|
||||||
vis3 = fov_mod.compute_fov(gm3, (5, 5), radius=8)
|
|
||||||
if (5, 5) not in vis3:
|
|
||||||
errs.append("FOV: walled-in player cannot see own tile")
|
|
||||||
leaked = [t for t in vis3 if abs(t[0] - 5) > 1 or abs(t[1] - 5) > 1]
|
|
||||||
if leaked:
|
|
||||||
errs.append(f"FOV: walled-in player sees through walls: {leaked[:5]}")
|
|
||||||
|
|
||||||
# --- A*: identity, open-field optimality, obstacle avoidance, no path ---
|
|
||||||
if pf_mod.find_path(gm, (5, 5), (5, 5)) not in ([], None):
|
|
||||||
errs.append("A*: start==goal should yield [] or None")
|
|
||||||
p = pf_mod.find_path(gm, (5, 5), (10, 7))
|
|
||||||
if p is None:
|
|
||||||
errs.append("A*: no path in open field")
|
|
||||||
else:
|
|
||||||
if not p or p[-1] != (10, 7):
|
|
||||||
errs.append("A*: path does not end at goal")
|
|
||||||
# Manhattan-optimal in open field
|
|
||||||
if len(p) != (abs(10 - 5) + abs(7 - 5)):
|
|
||||||
errs.append(f"A*: open-field path not Manhattan-optimal (len={len(p)})")
|
|
||||||
# around a wall
|
|
||||||
gmw = open_map(10, 10)
|
|
||||||
for y in range(10):
|
|
||||||
gmw.tiles[y][5] = 0 # wall column, except a gap
|
|
||||||
gmw.tiles[4][5] = 1
|
|
||||||
pw = pf_mod.find_path(gmw, (1, 5), (8, 5))
|
|
||||||
if pw is None or pw[-1] != (8, 5):
|
|
||||||
errs.append("A*: failed to route around a wall column via the gap")
|
|
||||||
else:
|
|
||||||
for (x, y) in pw:
|
|
||||||
if not gmw.walkable(x, y):
|
|
||||||
errs.append("A*: path steps onto a wall")
|
|
||||||
break
|
|
||||||
# no path
|
|
||||||
gmn = open_map(10, 3)
|
|
||||||
for y in range(3):
|
|
||||||
gmn.tiles[y][5] = 0 # solid wall column, no gap
|
|
||||||
if pf_mod.find_path(gmn, (1, 1), (8, 1)) is not None:
|
|
||||||
errs.append("A*: should return None when goal is fully walled off")
|
|
||||||
# blocked set respected (treat a tile like an enemy)
|
|
||||||
pb = pf_mod.find_path(open_map(20, 20), (1, 1), (5, 1), blocked={(3, 1)})
|
|
||||||
if pb is None:
|
|
||||||
errs.append("A*: blocked tile should not make path impossible")
|
|
||||||
elif (3, 1) in pb:
|
|
||||||
errs.append("A*: path walks through a blocked tile")
|
|
||||||
|
|
||||||
# --- Combat: 1000 attacks, distribution sane, formula honored ---
|
|
||||||
class C:
|
|
||||||
def __init__(self, **k):
|
|
||||||
self.__dict__.update(k)
|
|
||||||
atk = C(accuracy=5, evasion=0, power=8, armor=0, crit_chance=0.10)
|
|
||||||
dfn = C(accuracy=0, evasion=2, power=4, armor=3, crit_chance=0.0)
|
|
||||||
rng = random.Random(123)
|
|
||||||
hits = crits = 0
|
|
||||||
dmg_max = 0
|
|
||||||
dmg_min = 10 ** 9
|
|
||||||
base = atk.power # no weapon_power attr -> 0 bonus
|
|
||||||
N = 2000
|
|
||||||
for _ in range(N):
|
|
||||||
r = cb_mod.roll_attack(atk, dfn, rng)
|
|
||||||
if not (0 <= r.damage <= 2 * max(0, base - dfn.armor)):
|
|
||||||
errs.append(f"combat: damage {r.damage} out of [0,{2 * max(0, base - dfn.armor)}]")
|
|
||||||
break
|
|
||||||
dmg_max = max(dmg_max, r.damage)
|
|
||||||
if r.hit:
|
|
||||||
dmg_min = min(dmg_min, r.damage)
|
|
||||||
hits += 1
|
|
||||||
if r.crit:
|
|
||||||
crits += 1
|
|
||||||
if hits == 0:
|
|
||||||
errs.append("combat: never hit in 2000 attacks")
|
|
||||||
if crits == 0:
|
|
||||||
errs.append("combat: never crit in 2000 attacks (crit_chance 0.10)")
|
|
||||||
# hit_chance = clamp(0.7 + (5-2)*0.05, .1, .95) = 0.85 -> expect ~0.85
|
|
||||||
hr = hits / N
|
|
||||||
if not (0.78 <= hr <= 0.92):
|
|
||||||
errs.append(f"combat: hit rate {hr:.3f} far from expected ~0.85")
|
|
||||||
# nonzero damage floor: base 8 - armor 3 = 5
|
|
||||||
if dmg_min > 5:
|
|
||||||
errs.append(f"combat: min hit damage {dmg_min} > expected {5}")
|
|
||||||
|
|
||||||
if errs:
|
|
||||||
for e in errs:
|
|
||||||
_fail(" " + e)
|
|
||||||
return False
|
|
||||||
_ok("phase 2: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def phase2_ai():
|
|
||||||
"""AI chase gate (behaviors depend on pathfinding+fov, built after those)."""
|
|
||||||
from ai import behaviors
|
|
||||||
|
|
||||||
class E:
|
|
||||||
def __init__(self, x, y):
|
|
||||||
self.x, self.y = x, y
|
|
||||||
self.behavior = "chase"
|
|
||||||
self.hp = 99; self.max_hp = 99
|
|
||||||
self.power = 4; self.speed = 1; self.kind = "goblin"
|
|
||||||
self.last_known_pos = None
|
|
||||||
self.accuracy = 4; self.evasion = 1; self.armor = 1; self.crit_chance = 0.0
|
|
||||||
|
|
||||||
class P:
|
|
||||||
x = 18; y = 2; hp = 50; max_hp = 50; power = 5
|
|
||||||
accuracy = 5; evasion = 2; armor = 0; crit_chance = 0.1
|
|
||||||
|
|
||||||
# straight corridor of floor
|
|
||||||
gm = StubMap([[1 if y == 2 else 0 for y in range(5)] for _ in range(20)])
|
|
||||||
gm.width, gm.height = 20, 5
|
|
||||||
e = E(2, 2)
|
|
||||||
p = P()
|
|
||||||
rng = random.Random(5)
|
|
||||||
vis = {(x, 2) for x in range(20)}
|
|
||||||
start_d = abs(e.x - p.x) + abs(e.y - p.y)
|
|
||||||
last_d = start_d
|
|
||||||
for _ in range(40):
|
|
||||||
behaviors.act_enemy(e, gm, p, vis, rng)
|
|
||||||
d = abs(e.x - p.x) + abs(e.y - p.y)
|
|
||||||
last_d = d
|
|
||||||
if d <= 1:
|
|
||||||
break
|
|
||||||
if last_d > 1:
|
|
||||||
_fail(f" AI: chase enemy did not reach player (ended distance {last_d})")
|
|
||||||
return False
|
|
||||||
_ok("phase 2 AI: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- phase 3
|
|
||||||
def phase3():
|
|
||||||
from data import enemies as E
|
|
||||||
from data import items as I
|
|
||||||
from entities import player as P_mod
|
|
||||||
|
|
||||||
errs = []
|
|
||||||
|
|
||||||
# --- roster correctness vs plan.md ---
|
|
||||||
expected = {
|
|
||||||
"rat": dict(hp=8, power=3, armor=0, behavior="wander", xp=5),
|
|
||||||
"goblin": dict(hp=15, power=5, armor=1, behavior="chase", xp=12),
|
|
||||||
"skeleton_archer": dict(hp=12, power=4, armor=1, behavior="ranged", xp=15),
|
|
||||||
"orc_warrior": dict(hp=30, power=8, armor=3, behavior="flee", xp=25),
|
|
||||||
"wraith": dict(hp=20, power=10, armor=0, behavior="phase", xp=30),
|
|
||||||
"green_slime": dict(hp=18, power=5, armor=1, behavior="split", xp=18),
|
|
||||||
"ancient_dragon": dict(hp=120, power=15, armor=8, behavior="chase", xp=200),
|
|
||||||
}
|
|
||||||
for kind, want in expected.items():
|
|
||||||
e = E.make_enemy(kind, 0, 0)
|
|
||||||
for field, val in want.items():
|
|
||||||
got = getattr(e, field)
|
|
||||||
if field == "power" and kind == "skeleton_archer":
|
|
||||||
continue # ranged power tracked separately; base power may differ
|
|
||||||
if got != val:
|
|
||||||
errs.append(f"roster {kind}.{field} = {got!r}, expected {val!r}")
|
|
||||||
# split capability + small slime exists
|
|
||||||
gs = E.make_enemy("green_slime", 0, 0)
|
|
||||||
if not getattr(gs, "can_split", False):
|
|
||||||
errs.append("green_slime.can_split must be True")
|
|
||||||
try:
|
|
||||||
ss = E.make_enemy("small_slime", 0, 0)
|
|
||||||
if ss.hp > gs.hp:
|
|
||||||
errs.append("small_slime should be weaker than green_slime")
|
|
||||||
except Exception as ex: # noqa
|
|
||||||
errs.append(f"small_slime not constructible: {ex!r}")
|
|
||||||
# dragon must be killable: floor-9 gear total_power > dragon armor 8
|
|
||||||
wh = I.make_item("war_hammer", 0, 0)
|
|
||||||
if wh.stats.get("power", 0) <= 8:
|
|
||||||
errs.append(f"war_hammer power {wh.stats.get('power')} must exceed dragon armor 8")
|
|
||||||
|
|
||||||
# --- player equip changes totals ---
|
|
||||||
Player = P_mod.Player
|
|
||||||
pl = Player(x=0, y=0) if "x" in Player.__dataclass_fields__ else Player()
|
|
||||||
base_power = pl.total_power()
|
|
||||||
pl.equip(I.make_item("battle_axe", 0, 0))
|
|
||||||
if pl.total_power() != base_power + 7:
|
|
||||||
errs.append(f"equip battle_axe: total_power {pl.total_power()} != {base_power + 7}")
|
|
||||||
pl.equip(I.make_item("chain_mail", 0, 0))
|
|
||||||
if pl.total_armor() < 4:
|
|
||||||
errs.append(f"equip chain_mail: total_armor {pl.total_armor()} < 4")
|
|
||||||
|
|
||||||
# --- XP / leveling ---
|
|
||||||
pl2 = Player(x=0, y=0) if "x" in Player.__dataclass_fields__ else Player()
|
|
||||||
start_lvl = pl2.level
|
|
||||||
pl2.hp = 1 # deliberately hurt
|
|
||||||
levels = pl2.gain_xp(30) # 30 xp -> level 2
|
|
||||||
if pl2.level != start_lvl + 1:
|
|
||||||
errs.append(f"gain_xp(30): level {pl2.level} != {start_lvl + 1}")
|
|
||||||
if pl2.hp != pl2.max_hp:
|
|
||||||
errs.append("level-up must fully heal")
|
|
||||||
# push to level 10 to confirm full table works
|
|
||||||
pl2.gain_xp(100000)
|
|
||||||
if pl2.level != 10:
|
|
||||||
errs.append(f"level cap should be 10, got {pl2.level}")
|
|
||||||
|
|
||||||
if errs:
|
|
||||||
for e in errs:
|
|
||||||
_fail(" " + e)
|
|
||||||
return False
|
|
||||||
_ok("phase 3: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- phase 4
|
|
||||||
def phase4():
|
|
||||||
import json
|
|
||||||
from engine import map_gen
|
|
||||||
from engine import game_state as gs_mod
|
|
||||||
from engine import serializers as ser
|
|
||||||
from engine import actions as act
|
|
||||||
from data import items as I
|
|
||||||
|
|
||||||
errs = []
|
|
||||||
|
|
||||||
def fresh_session(seed=99):
|
|
||||||
dungeon = map_gen.generate_dungeon(seed=seed)
|
|
||||||
Player = gs_mod.GameSession # placeholder, replaced below
|
|
||||||
return dungeon
|
|
||||||
|
|
||||||
# build a real session through the game's own constructor if available
|
|
||||||
try:
|
|
||||||
sess = gs_mod.new_session(seed=42) if hasattr(gs_mod, "new_session") else None
|
|
||||||
except Exception:
|
|
||||||
sess = None
|
|
||||||
if sess is None:
|
|
||||||
try:
|
|
||||||
from main import new_game
|
|
||||||
sess = new_game(seed=42)
|
|
||||||
except Exception as ex:
|
|
||||||
return _phase4_fail(f"cannot build a session: {ex!r}")
|
|
||||||
|
|
||||||
# ---- save / load round-trip stability (compare dicts, skip volatile) ----
|
|
||||||
d1 = ser.session_to_dict(sess)
|
|
||||||
sess2 = ser.session_from_dict(d1)
|
|
||||||
d2 = ser.session_to_dict(sess2)
|
|
||||||
if d1 != d2:
|
|
||||||
# locate first diff for a useful message
|
|
||||||
errs.append("save/load: session_to_dict not stable across load (d1 != d2)")
|
|
||||||
# volatile 'visible' grid must NOT be persisted (recomputed from FOV)
|
|
||||||
if "visible" in json.dumps(d1):
|
|
||||||
errs.append("save/load: 'visible' grid must not be serialized")
|
|
||||||
|
|
||||||
# ---- 'g' pickup ----
|
|
||||||
sessp = gs_mod.new_session(seed=42) if hasattr(gs_mod, "new_session") else None
|
|
||||||
if sessp is None:
|
|
||||||
from main import new_game
|
|
||||||
sessp = new_game(seed=42)
|
|
||||||
cur = sessp.dungeon[sessp.current_floor]
|
|
||||||
px, py = sessp.player.x, sessp.player.y
|
|
||||||
# drop an item directly under the player
|
|
||||||
item = I.make_item("healing_potion", px, py)
|
|
||||||
cur.entities.append(item)
|
|
||||||
before = len(sessp.player.inventory)
|
|
||||||
try:
|
|
||||||
act.apply_input(sessp, "g")
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"apply_input('g') raised: {ex!r}")
|
|
||||||
if len(sessp.player.inventory) != before + 1:
|
|
||||||
errs.append(f"pickup: inventory grew {before}->{len(sessp.player.inventory)} (expected +1)")
|
|
||||||
|
|
||||||
# ---- 'f' descent ----
|
|
||||||
sessf = gs_mod.new_session(seed=42) if hasattr(gs_mod, "new_session") else None
|
|
||||||
if sessf is None:
|
|
||||||
from main import new_game
|
|
||||||
sessf = new_game(seed=42)
|
|
||||||
floor_before = sessf.current_floor
|
|
||||||
cur = sessf.dungeon[sessf.current_floor]
|
|
||||||
# move player onto stairs
|
|
||||||
if cur.stairs_down is None:
|
|
||||||
errs.append("descent: floor has no stairs_down")
|
|
||||||
else:
|
|
||||||
sessf.player.x, sessf.player.y = cur.stairs_down
|
|
||||||
try:
|
|
||||||
act.apply_input(sessf, "f")
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"apply_input('f') raised: {ex!r}")
|
|
||||||
if sessf.current_floor != floor_before + 1:
|
|
||||||
errs.append(f"descent: floor {floor_before}->{sessf.current_floor} (expected +1)")
|
|
||||||
|
|
||||||
# ---- audio resilience: forced mixer failure must not crash ----
|
|
||||||
try:
|
|
||||||
import pygame
|
|
||||||
pygame.init()
|
|
||||||
orig = pygame.mixer.init
|
|
||||||
pygame.mixer.init = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no device"))
|
|
||||||
from engine import audio as au_mod
|
|
||||||
eng = au_mod.AudioEngine(enabled=True)
|
|
||||||
eng.play("hit") # must be a silent no-op
|
|
||||||
eng.toggle_mute()
|
|
||||||
pygame.mixer.init = orig
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"audio: forced mixer failure crashed: {ex!r}")
|
|
||||||
|
|
||||||
# ---- stairs visibly rendered: sprite is yellow + renderer draws it ----
|
|
||||||
stairs_errs = _check_stairs_rendered()
|
|
||||||
errs.extend(stairs_errs)
|
|
||||||
|
|
||||||
# ---- winnability: buffed player kills dragon on floor 9 -> victory ----
|
|
||||||
win_errs = _check_dragon_kill(gs_mod, act)
|
|
||||||
errs.extend(win_errs)
|
|
||||||
|
|
||||||
if errs:
|
|
||||||
for e in errs:
|
|
||||||
_fail(" " + e)
|
|
||||||
return False
|
|
||||||
_ok("phase 4: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _phase4_fail(msg):
|
|
||||||
_fail(" " + msg)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _check_stairs_rendered():
|
|
||||||
"""The renderer must blit a distinct yellow stairs sprite on stairs_down."""
|
|
||||||
import pygame
|
|
||||||
errs = []
|
|
||||||
try:
|
|
||||||
from render import sprites as spr
|
|
||||||
except Exception as ex:
|
|
||||||
return [f"stairs render: cannot import render.sprites: {ex!r}"]
|
|
||||||
|
|
||||||
# 1) a 'stairs' sprite exists and is visibly yellow + non-empty
|
|
||||||
try:
|
|
||||||
s = spr.get_sprite("stairs")
|
|
||||||
except Exception as ex:
|
|
||||||
return [f"stairs render: get_sprite('stairs') raised: {ex!r}"]
|
|
||||||
if s is None:
|
|
||||||
return ["stairs render: get_sprite('stairs') returned None"]
|
|
||||||
w, h = s.get_size()
|
|
||||||
if w < 4 or h < 4:
|
|
||||||
errs.append(f"stairs sprite suspiciously small ({w}x{h})")
|
|
||||||
yellow_pixels = opaque = 0
|
|
||||||
for yy in range(h):
|
|
||||||
for xx in range(w):
|
|
||||||
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_pixels += 1
|
|
||||||
if opaque == 0:
|
|
||||||
errs.append("stairs sprite is fully transparent (nothing drawn)")
|
|
||||||
elif yellow_pixels == 0:
|
|
||||||
errs.append("stairs sprite has no yellow pixels (not a glowing yellow staircase)")
|
|
||||||
|
|
||||||
# 2) the renderer actually draws it on the stairs_down tile
|
|
||||||
try:
|
|
||||||
from render import renderer as R
|
|
||||||
from engine import map_gen
|
|
||||||
from main import new_game
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"stairs render: import renderer/map/new_game failed: {ex!r}")
|
|
||||||
return errs
|
|
||||||
sess = new_game(seed=3)
|
|
||||||
# ensure we are not on the boss floor; pick floor 0, stand adjacent to stairs
|
|
||||||
sess.current_floor = 0
|
|
||||||
gm = sess.dungeon[0]
|
|
||||||
if gm.stairs_down is None:
|
|
||||||
errs.append("stairs render: floor 0 has no stairs")
|
|
||||||
return errs
|
|
||||||
sx, sy = gm.stairs_down
|
|
||||||
# place player on a walkable neighbor so stairs stays visible & lit
|
|
||||||
placed = False
|
|
||||||
for (nx, ny) in ((sx + 1, sy), (sx - 1, sy), (sx, sy + 1), (sx, sy - 1)):
|
|
||||||
if gm.walkable(nx, ny):
|
|
||||||
sess.player.x, sess.player.y = nx, ny
|
|
||||||
placed = True
|
|
||||||
break
|
|
||||||
if not placed:
|
|
||||||
errs.append("stairs render: no walkable neighbor of stairs to stand on")
|
|
||||||
return errs
|
|
||||||
try:
|
|
||||||
renderer = R.Renderer()
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"stairs render: Renderer() raised: {ex!r}")
|
|
||||||
return errs
|
|
||||||
TILE = 20
|
|
||||||
try:
|
|
||||||
from data import constants as C
|
|
||||||
TILE = getattr(C, "TILE", 20)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
surf = pygame.Surface((gm.width * TILE, gm.height * TILE), pygame.SRCALPHA)
|
|
||||||
try:
|
|
||||||
renderer.render(surf, sess, camera_xy=(0, 0))
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"stairs render: renderer.render raised: {ex!r}")
|
|
||||||
return errs
|
|
||||||
cx = sx * TILE + TILE // 2
|
|
||||||
cy = sy * TILE + TILE // 2
|
|
||||||
pc = surf.get_at((cx, cy))
|
|
||||||
# compare against a known plain floor tile center (a floor tile not on stairs)
|
|
||||||
floor_ref = None
|
|
||||||
for yy in range(gm.height):
|
|
||||||
for xx in range(gm.width):
|
|
||||||
if gm.walkable(xx, yy) and (xx, yy) != gm.stairs_down and abs(xx - sx) <= 5 and abs(yy - sy) <= 5:
|
|
||||||
floor_ref = surf.get_at((xx * TILE + TILE // 2, yy * TILE + TILE // 2))
|
|
||||||
break
|
|
||||||
if floor_ref:
|
|
||||||
break
|
|
||||||
if floor_ref is not None:
|
|
||||||
diff = abs(pc.r - floor_ref.r) + abs(pc.g - floor_ref.g) + abs(pc.b - floor_ref.b)
|
|
||||||
is_yellowish = pc.r > 110 and pc.g > 90 and pc.b < 130
|
|
||||||
if diff < 40 and not is_yellowish:
|
|
||||||
errs.append(
|
|
||||||
f"stairs render: stairs tile pixel {pc} too similar to floor {floor_ref} "
|
|
||||||
"(stairs sprite not drawn on stairs_down)")
|
|
||||||
return errs
|
|
||||||
|
|
||||||
|
|
||||||
def _check_dragon_kill(gs_mod, act):
|
|
||||||
"""Floor 9: a player geared with floor-9 weapons can kill the dragon -> victory."""
|
|
||||||
errs = []
|
|
||||||
try:
|
|
||||||
from main import new_game
|
|
||||||
from data import items as I
|
|
||||||
from data import enemies as E
|
|
||||||
except Exception as ex:
|
|
||||||
return [f"dragon kill: import failed: {ex!r}"]
|
|
||||||
|
|
||||||
sess = new_game(seed=11)
|
|
||||||
# jump straight to the boss floor with a leveled, well-geared player
|
|
||||||
sess.current_floor = 9
|
|
||||||
gm = sess.dungeon[9]
|
|
||||||
# find the dragon on floor 9
|
|
||||||
dragon = next((e for e in gm.entities if getattr(e, "kind", "") == "ancient_dragon"), None)
|
|
||||||
if dragon is None:
|
|
||||||
# some builds spawn the dragon lazily; force one in
|
|
||||||
try:
|
|
||||||
dragon = E.make_enemy("ancient_dragon", 0, 0)
|
|
||||||
gm.entities.append(dragon)
|
|
||||||
except Exception as ex:
|
|
||||||
return [f"dragon kill: no ancient_dragon on floor 9 and cannot make one: {ex!r}"]
|
|
||||||
# gear up: best weapon + armor, level 10, full hp
|
|
||||||
try:
|
|
||||||
sess.player.equip(I.make_item("war_hammer", 0, 0))
|
|
||||||
sess.player.equip(I.make_item("plate_armor", 0, 0))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
sess.player.gain_xp(100000)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
sess.player.hp = sess.player.max_hp
|
|
||||||
if sess.player.total_power() <= dragon.armor:
|
|
||||||
errs.append(
|
|
||||||
f"dragon kill: geared player total_power {sess.player.total_power()} "
|
|
||||||
f"<= dragon armor {dragon.armor} (unwinnable)")
|
|
||||||
return errs
|
|
||||||
# stand adjacent and beat on it via the action layer (move-into-enemy = attack)
|
|
||||||
sess.player.x = max(0, dragon.x - 1)
|
|
||||||
sess.player.y = dragon.y
|
|
||||||
safety = 500
|
|
||||||
while dragon.hp > 0 and safety > 0:
|
|
||||||
safety -= 1
|
|
||||||
try:
|
|
||||||
act.apply_input(sess, "right")
|
|
||||||
except Exception:
|
|
||||||
# some action layers use absolute intents; fall back to direct combat
|
|
||||||
from engine import combat as cb
|
|
||||||
r = cb.roll_attack(sess.player, dragon)
|
|
||||||
if r.hit:
|
|
||||||
dragon.hp -= r.damage
|
|
||||||
if getattr(dragon, "hp", 1) <= 0:
|
|
||||||
# trigger death/victory handling if present
|
|
||||||
try:
|
|
||||||
act.apply_input(sess, "wait")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
break
|
|
||||||
if dragon.hp > 0:
|
|
||||||
errs.append(f"dragon kill: dragon still alive ({dragon.hp} hp) after many attacks")
|
|
||||||
# dragon death on floor 9 must yield victory
|
|
||||||
if getattr(sess, "state", None) != "victory":
|
|
||||||
errs.append(f"dragon kill: session.state = {sess.state!r}, expected 'victory'")
|
|
||||||
return errs
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- goal
|
|
||||||
def goal():
|
|
||||||
"""Full acceptance: headless launch of main.py + a scripted play sequence."""
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
errs = []
|
|
||||||
|
|
||||||
# 1) main.py launches headless and exits cleanly within a frame budget
|
|
||||||
env = dict(os.environ)
|
|
||||||
env["SDL_VIDEODRIVER"] = "dummy"
|
|
||||||
env["SDL_AUDIODRIVER"] = "dummy"
|
|
||||||
env[MAXFRAMES_ENV] = "20"
|
|
||||||
try:
|
|
||||||
proc = subprocess.run(
|
|
||||||
[sys.executable, os.path.join(ROOT, "main.py")],
|
|
||||||
cwd=ROOT, env=env, capture_output=True, text=True, timeout=90,
|
|
||||||
)
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
errs.append("goal: main.py headless launch timed out (did not honor frame budget)")
|
|
||||||
else:
|
|
||||||
if proc.returncode != 0:
|
|
||||||
errs.append(f"goal: main.py exited {proc.returncode}")
|
|
||||||
combined = (proc.stdout or "") + (proc.stderr or "")
|
|
||||||
if "Traceback" in combined:
|
|
||||||
# show a trimmed traceback
|
|
||||||
tail = "\n".join(combined.splitlines()[-12:])
|
|
||||||
errs.append("goal: main.py printed a Traceback:\n" + tail)
|
|
||||||
|
|
||||||
# 2) programmatic scripted play: new game -> move -> descend a floor -> no crash
|
|
||||||
try:
|
|
||||||
from main import new_game
|
|
||||||
from engine import actions as act
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"goal: cannot import new_game/actions: {ex!r}")
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
s = new_game(seed=2024)
|
|
||||||
gm = s.dungeon[s.current_floor]
|
|
||||||
if gm.stairs_down is not None:
|
|
||||||
s.player.x, s.player.y = gm.stairs_down
|
|
||||||
floor0 = s.current_floor
|
|
||||||
act.apply_input(s, "f")
|
|
||||||
if s.current_floor != floor0 + 1:
|
|
||||||
errs.append("goal: scripted descend did not advance the floor")
|
|
||||||
# a few moves should never crash on any floor
|
|
||||||
for k in ("up", "down", "left", "right", "g", "?", "m"):
|
|
||||||
act.apply_input(s, k)
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"goal: scripted play raised: {ex!r}\n{traceback.format_exc()[-400:]}")
|
|
||||||
|
|
||||||
# 3) all systems importable
|
|
||||||
for mod in ("engine.map_gen", "engine.fov", "engine.pathfinding",
|
|
||||||
"engine.combat", "engine.serializers", "engine.actions",
|
|
||||||
"engine.audio", "ai.behaviors", "data.enemies", "data.items",
|
|
||||||
"render.sprites", "render.renderer"):
|
|
||||||
try:
|
|
||||||
__import__(mod)
|
|
||||||
except Exception as ex:
|
|
||||||
errs.append(f"goal: cannot import {mod}: {ex!r}")
|
|
||||||
|
|
||||||
if errs:
|
|
||||||
for e in errs:
|
|
||||||
_fail(" " + e)
|
|
||||||
_fail("goal: FAIL")
|
|
||||||
return False
|
|
||||||
_ok("goal: PASS")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- dispatch
|
|
||||||
PHASES = {
|
|
||||||
1: [phase1],
|
|
||||||
2: [phase2, phase2_ai],
|
|
||||||
3: [phase3],
|
|
||||||
4: [phase4],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def run_phase(n):
|
|
||||||
fns = PHASES.get(n)
|
|
||||||
if not fns:
|
|
||||||
_fail(f"phase {n}: unknown phase")
|
|
||||||
return False
|
|
||||||
for fn in fns:
|
|
||||||
try:
|
|
||||||
ok = fn()
|
|
||||||
except Exception:
|
|
||||||
_fail(f" {fn.__name__} raised:")
|
|
||||||
traceback.print_exc()
|
|
||||||
ok = False
|
|
||||||
if not ok:
|
|
||||||
_fail(f"phase {n}: FAIL")
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--phase", type=int)
|
|
||||||
ap.add_argument("--goal", action="store_true")
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
if args.goal:
|
|
||||||
sys.exit(0 if goal() else 1)
|
|
||||||
if args.phase is not None:
|
|
||||||
sys.exit(0 if run_phase(args.phase) else 1)
|
|
||||||
# default: run all phases then goal
|
|
||||||
ok = True
|
|
||||||
for n in (1, 2, 3, 4):
|
|
||||||
if not run_phase(n):
|
|
||||||
ok = False
|
|
||||||
break
|
|
||||||
if ok and not goal():
|
|
||||||
ok = False
|
|
||||||
sys.exit(0 if ok else 1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||