xonecas.ioDon't click! Sean Caetano Martin Sign in

tiny-adventure / commits / 63daab4

Landing, end and shared-run screens, a feedback form, a living board, clear fight formations, and a harness that replays every fight

The party marches and fights in a spaced formation, things on its tile and the flora toward the camera step aside, and camp gathers round a fire in the tile while the night passes on a banner. Wind, banners, smoke, fireflies and birds bring the board to life. The client reads each event's kind from the server, which fixes gear-granted Mend and Rally playing as attacks on teammates. Verify now replays 92 bot fights through the client's playback code and fails a fight whose shown hp differs from the server's.

Co-Authored-By: Claude Opus 5.5

sacenox1 day ago63daab433e679581fbda2bb2bca0f4378dd409bdparent fc58fcc26 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

CLAUDE.md+10-4
@@ -10,9 +10,10 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
1010 - `internal/world`: hex math, noise, terrain bytes, pathfinding.
1111 - `internal/gen`: builds a `World` from a seed: terrain, factions, POIs, spawns, bands, loot, landmarks, missions, party, encounters.
1212 - `internal/sim`: game rules that are pure functions: classes and growth, abilities, items (`BuildItem`, `RollItem`), traits and `EdgeOf`, combat, `Forecast` odds, XP.
13-- `internal/server`: HTTP and the stateful game: move, bands, hazards, landmarks, clock and camping, shops, threat view, fights.
14-- `web/js`: one concern per file. `main.js` wires the flow. `kit.js` is the canvas-texture UI layer, `frames.js` its widgets, `text.js` fonts and text, `theme.js` colour roles, `layout.js` widget rects. Board and art: `board.js`, `flora.js`, `props.js`, `figures.js`, `minis.js`, `beasts.js`, `sky.js`. Feedback: `combat.js` plays the server log one turn at a time, `levelup.js` celebrates level gains above the hero cards, `route.js` draws the `/api/path` preview, `medallions.js` renders each hero' …
15-- `scripts`: the harness. `serve.sh` starts a server, `driver.mjs` drives the browser, `bot.mjs` is the careful player policy shared by verify and playthrough, `layout.mjs` checks rects.
13+- `internal/server`: HTTP and the stateful game: move, bands, hazards, landmarks, clock and camping, shops, threat view, fights. `actions.go` is the one switch every POST goes through, `store.go` the per-game action logs and replay, `server.go` players, seats and routes, `limit.go` rate limits, `feedback.go` its gate, `run.go` and `card.go` the share page and PNG card (fonts in `internal/server/fonts`, lining numerals frozen in).
14+- `web/js`: one concern per file. `main.js` wires the flow. `kit.js` is the canvas-texture UI layer, `frames.js` its widgets, `text.js` fonts and text, `theme.js` colour roles, `layout.js` widget rects. Board and art: `board.js`, `flora.js`, `props.js`, `figures.js`, `minis.js`, `beasts.js`, `sky.js`. Feedback: `combat.js` plays the server log one turn at a time, `levelup.js` celebrates level gains above the hero cards, `route.js` draws the `/api/path` preview, `playback.js` applies one combat e …
15+- `deploy`: the systemd unit and Caddy block for tiny-adventure.xonecas.io. Steps in `docs/deploy.md`.
16+- `scripts`: the harness. `serve.sh` starts a server, `driver.mjs` drives the browser, `bot.mjs` is the careful player policy shared by verify and playthrough, `fights.mjs` replays fight logs through `web/js/playback.js` and checks them against the server, `layout.mjs` checks rects.
1617
1718 ## Commands
1819
@@ -29,6 +30,8 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
2930 - All game UI is drawn on canvas textures through `kit.js` and `frames.js`: HUD, panels, buttons, menus, title and end screens, floating numbers. The only DOM elements are the canvas and the `#fatal` fallback.
3031 - Text goes through `drawText` with a box height `h`: it centres the cap height in the box. Never place text with magic offsets. MedievalSharp (`display: true`) is for titles, headings, place labels and odds words only; Alegreya with lining numerals is the body. Fonts are vendored in `web/fonts` and load before the first draw.
3132 - Colours come from roles in `theme.js`: a grey ramp, one amber accent for state and the primary action, red only for danger. Radius at most 4. No gradients.
33+- The one exception to canvas-only UI is the hidden `textarea` in `feedback.js`. It takes the typing, including paste, IME and mobile keyboards, and the form is drawn on canvas. Add no other DOM.
34+- A game is its seed plus its action log. Every rule must give the same result when the log is replayed: no wall clock, no `math/rand` outside `rng`, no map iteration order in rules. The action's own time is `g.now`.
3235 - `window.__game` (`web/js/debug.js`) must keep working: `mode`, `busy`, `state()`, `rects()` via `setRects`, `tileScreen`, `focusTile`, `pickAt`, `perf()`. The harness reads layout only from `rects()`.
3336 - Scripts import `web/js/stats.js` and `web/js/hex.js`; keep those free of browser APIs.
3437 - Generated art: the `openrouter` skill can make images when a texture or icon is needed.
@@ -39,8 +42,11 @@ A seeded tabletop campaign: a Go server owns every rule, a Three.js client in `w
3942 - Defeat ends the campaign. Any harness setup that fights through the API can end the run; pin the seed and check `phase`.
4043 - Never kill processes with `pkill -f`; it matches the agent's own shell. Find a server by port: `ss -ltnpH 'sport = :PORT'`.
4144 - Seeds above 2^53 lose precision in JS. `rng.NewSeed` stays below a million.
42-- Balance is measured with the careful bot over seeds 1 to 20 through the API. Expect about 19 wins in about 9 days. `TestCarefulPlayWinsMostCampaigns` is the fast Go guard.
45+- Balance is measured with the careful bot over seeds 1 to 20 through the API. Expect about 19 wins in about 10 to 11 days. `TestCarefulPlayWinsMostCampaigns` is the fast Go guard.
4346 - The client walks one hex per `/api/move {steps: 1}` so the player can change course. Keep `track.busy` true for the whole walk; the harness waits on it.
47+- Every request without a player id gets a new board. The harness sends one id per process as `X-Player` from node and plants it as the `ta` cookie in the browser (`driver.mjs`). A script that calls the API without it plays alone.
48+- The client reads each combat event's `kind` from the server. Never classify an event from the unit's own ability list: gear grants abilities too, and a heal played as damage shows a hero hit by a teammate.
49+- Rate limits skip loopback requests without `X-Forwarded-For`. Caddy always sets that header, so public traffic is limited and the harness is not.
4450
4551 ## Definition of done
4652
README.md+6-3
@@ -10,11 +10,12 @@ go run ./cmd/server
1010
1111 Open http://localhost:8080. Flags:
1212
13-- `--seed N` fixes the campaign seed. Without it, a random seed is picked at boot.
13+- `--seed N` gives every new player campaign seed N. Without it, each player gets a random seed.
1414 - `--addr :8080` sets the listen address.
1515 - `--web web` sets the static files directory.
16+- `--data DIR` keeps every game as an action log in DIR, so games survive a restart. Without it, games live in memory.
1617
17-The New Game button on the end screen asks the server for a fresh random seed.
18+Each browser gets its own board through a cookie. The title screen continues it, and New campaign starts another. `docs/deploy.md` covers the public server at tiny-adventure.xonecas.io.
1819
1920 ## Art
2021
@@ -32,7 +33,7 @@ The seed decides every system and its details:
3233 - Party: classes, stats, abilities and starting gear are rolled per seed.
3334 - Progression: enemy level grows with distance from the spawn. Gear comes from loot found on the map and from fights. XP comes from fights. The boss fight unlocks after every other main step is done.
3435
35-Beating the boss ends the campaign with a victory screen. If the whole party falls, it ends with a defeat screen.
36+Beating the boss ends the campaign with a victory screen. If the whole party falls, it ends with a defeat screen. Both show the run's numbers and put its share link in the address bar. Copy link copies it. The link opens that result card for anyone, with a preview image for chat apps, and Play this seed starts the same campaign.
3637
3738 ## Playing
3839
@@ -45,6 +46,8 @@ Beating the boss ends the campaign with a victory screen. If the whole party fal
4546 - The main quest asks you to recover keys from the places it names. The top bar counts them, and the boss stays sealed until you hold them all.
4647 - Walking over loot picks it up. Each base item has its own stats: daggers trade attack for speed and crit, plate trades speed for defense. The inventory and the trader compare every item with the selected hero's gear. Items may carry a trait, such as fire, lifesteal or taunt, paid for with a lower stat. Enemies show their traits, weaknesses and resistances on the threat card. Prepare (G) opens the inventory with live odds, so you can gear for the fight in front of you.
4748 - Fights play out one turn at a time. Space or a click speeds them up. Heroes who level up hop on the board, and their gains rise above their cards. A lost fight ends the campaign.
49+- A hero who drops to 0 hp falls and lies on the board, greyed out. They sit out fights and earn no XP until a potion (P) gets them up at half health, or a night at camp brings everyone back.
50+- After a fight and a gear change, Give feedback? opens a short form. The note goes in with the game's anonymous log.
4851 - M toggles sound.
4952
5053 ## Check
docs/verification.md+8-1
@@ -38,6 +38,12 @@ Plays one full campaign on `<seed>` through input only, with the careful bot fro
3838 - Layout, read from `window.__game.rects()` only: every `essential` rect is fully inside the viewport, and no two rects partly overlap (full containment is allowed). Checked on title, explore, inventory, journal, threat card, combat, trader, night HUD, victory and defeat screens.
3939 - The page must log no console errors or uncaught exceptions.
4040
41+Before the resolutions, verify plays seeds 1 to 5 to the end through the API with the careful bot, which equips the gear it finds. `scripts/fights.mjs` replays each fight's log through `web/js/playback.js`, the same code the client uses to show hp. Each replay must end at the server's hp. No fallen unit may act or be targeted, and heals and buffs must stay on the caster's side. The step fails if no heal or buff came up. Run it alone with `node scripts/fights.mjs <base> [seeds]`.
42+
43+Every fight the harness clicks also checks the playback. When the fight ends, the client's shown hp for each hero who did not level up must equal the server's, and every foe must show 0 after a win. `window.__game.drift()` lists any difference, and `driver.mjs` fails the step on it. This catches a client that plays an event as the wrong kind, such as a heal played as an attack.
44+
45+`TestCombatLogFollowsTheRules` in `internal/sim` replays the log of about 600 seeded fights, with fallen heroes and gear that grants Rally, Mend and lifesteal. Nobody fallen acts or is targeted, heals and buffs stay on the caster's side, damage only crosses sides, and the replayed hp equals the fight's result. It fails if any of those cases never came up.
46+
4147 ## Reviewing the output
4248
4349 The harness cannot judge looks. After a run, read every PNG for at least 1280x720, 800x600 and 390x844, and the recording frames, and write down what is wrong: clipped text, unreadable sizes, empty panels, UI covering the board, an unplayable end state. Assertions passing does not mean the UI is good.
@@ -50,7 +56,8 @@ Defined in `web/js/debug.js`, installed after boot.
5056 | --- | --- |
5157 | `mode` | `loading`, `title`, `explore`, `threat`, `prepare`, `combat`, `camp`, `end` |
5258 | `busy` | true while a move, walk or fight animation runs |
53-| `state()` | phase, seed, party x/y/gold/potions/inventory/unit levels and hp, threat, shop, clock, summary, winner |
59+| `drift()` | hp the last fight showed that differs from the server, empty when the playback is right |
60+| `state()` | phase, seed, party x/y/gold/potions/inventory/unit levels and hp, threat, shop, clock, summary, game, feedback |
5461 | `perf()` | frame time over the last 240 frames (`fps`, `p50`, `p95`, `max` in ms), draw calls, triangles and the GPU name |
5562 | `rects()` | `[{name, x, y, w, h, essential}]` in CSS pixels |
5663 | `setRects(fn)` | replace the rect provider (use when the UI is drawn in Three.js) |
scripts/driver.mjs+11-3
@@ -1,8 +1,11 @@
11 import { execFileSync } from 'node:child_process';
2+import { randomBytes } from 'node:crypto';
23
34 export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
45
5-export function createDriver({ session, baseUrl, w, h }) {
6+const PLAYER = randomBytes(16).toString('hex');
7+
8+export function createDriver({ session, baseUrl, w, h, player = PLAYER }) {
69 const ab = (...args) => execFileSync('agent-browser', ['--session', session, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 });
710 const ev = (expr) => {
811 const out = JSON.parse(ab('--json', 'eval', expr));
@@ -10,7 +13,8 @@ export function createDriver({ session, baseUrl, w, h }) {
1013 return out.data.result;
1114 };
1215 const api = async (path, body) => {
13- const res = await fetch(baseUrl + path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
16+ const headers = { 'Content-Type': 'application/json', 'X-Player': player };
17+ const res = await fetch(baseUrl + path, body === undefined ? { headers } : { method: 'POST', headers, body: JSON.stringify(body) });
1418 return res.json();
1519 };
1620 const gameState = async () => JSON.parse(ev('JSON.stringify(window.__game.state())'));
@@ -66,7 +70,10 @@ export function createDriver({ session, baseUrl, w, h }) {
6670 const fight = async (observe) => {
6771 await clickRect('threat-fight');
6872 await sleep(300);
69- return waitIdle(observe);
73+ const seen = await waitIdle(observe);
74+ const drift = JSON.parse(ev('JSON.stringify(window.__game.drift())'));
75+ if (drift.length) throw new Error(`fight playback disagrees with the server: ${drift.join('; ')}`);
76+ return seen;
7077 };
7178 const settle = async (ms = 400) => {
7279 await sleep(ms);
@@ -121,6 +128,7 @@ export function createDriver({ session, baseUrl, w, h }) {
121128 },
122129 });
123130 const openPage = async (want) => {
131+ ab('cookies', 'set', 'ta', player, '--url', baseUrl, '--http-only');
124132 ab('open', baseUrl);
125133 const t0 = Date.now();
126134 while (Date.now() - t0 < 30000) {
scripts/fights.mjs+57-0
@@ -0,0 +1,57 @@
1+import { apiIO, playOut } from './bot.mjs';
2+import { maxHp } from '../web/js/stats.js';
3+import { applyEvent } from '../web/js/playback.js';
4+
5+export function replayFight(before, after) {
6+ const hp = new Map();
7+ const cap = new Map();
8+ for (const u of before.party.units) {
9+ hp.set(u.id, Math.min(u.stats.hp, maxHp(u)));
10+ cap.set(u.id, maxHp(u));
11+ }
12+ for (const e of after.encounter?.enemies || []) {
13+ hp.set(e.id, e.stats.hp);
14+ cap.set(e.id, e.stats.maxHp);
15+ }
16+ const out = [];
17+ const heroes = new Set(before.party.units.map((u) => u.id));
18+ for (const ev of after.log || []) {
19+ const same = heroes.has(ev.actor) === heroes.has(ev.target);
20+ if (!(hp.get(ev.actor) > 0) && ev.ability !== 'thorns') out.push(`a fallen unit acts: ${ev.text}`);
21+ if (!(hp.get(ev.target) > 0)) out.push(`a fallen unit is targeted: ${ev.text}`);
22+ if ((ev.kind === 'heal' || ev.kind === 'buff') !== same) out.push(`${ev.kind} crosses sides the wrong way: ${ev.text}`);
23+ applyEvent(hp, ev, cap.get(ev.target));
24+ }
25+ const was = Object.fromEntries(before.party.units.map((u) => [u.id, u.level]));
26+ for (const u of after.party.units) if (was[u.id] === u.level && hp.get(u.id) !== u.stats.hp) out.push(`${u.name} replays to ${hp.get(u.id)} hp, server ${u.stats.hp}`);
27+ if (after.rewards) for (const e of after.encounter.enemies) if (hp.get(e.id) !== 0) out.push(`${e.name} replays to ${hp.get(e.id)} hp after a won fight`);
28+ return out;
29+}
30+
31+export async function checkFights(api, seeds) {
32+ const io = apiIO(api);
33+ const fight = io.fight;
34+ const report = { fights: 0, kinds: {}, abilities: {}, problems: [] };
35+ io.fight = async (s) => {
36+ const after = await fight(s);
37+ if (!after.encounter) return after;
38+ report.fights++;
39+ for (const ev of after.log) {
40+ report.kinds[ev.kind] = (report.kinds[ev.kind] || 0) + 1;
41+ report.abilities[ev.ability] = (report.abilities[ev.ability] || 0) + 1;
42+ }
43+ for (const p of replayFight(s, after)) report.problems.push(`seed ${after.seed} fight ${after.summary.battles}: ${p}`);
44+ return after;
45+ };
46+ for (const seed of seeds) await playOut(io, await api('/api/new', { seed }), {});
47+ return report;
48+}
49+
50+if (import.meta.url === `file://${process.argv[1]}`) {
51+ const [base, ...seeds] = process.argv.slice(2);
52+ const api = async (path, body) => (await fetch(base + path, body === undefined ? { headers: { 'X-Player': 'f'.repeat(32) } } : { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Player': 'f'.repeat(32) }, body: JSON.stringify(body) })).json();
53+ const r = await checkFights(api, seeds.length ? seeds.map(Number) : [1, 2, 3, 4, 5]);
54+ console.log(`${r.fights} fights, kinds ${JSON.stringify(r.kinds)}, mend ${r.abilities.mend || 0}, rally ${r.abilities.rally || 0}, lifesteal ${r.abilities.lifesteal || 0}`);
55+ for (const p of r.problems.slice(0, 10)) console.log(`FAIL ${p}`);
56+ process.exit(r.problems.length ? 1 : 0);
57+}
scripts/serve.sh+2-1
@@ -4,10 +4,11 @@ export AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--use-angle=swif
44
55 serve() {
66 local seed=$1 log=$2 port bin
7+ data=$(mktemp -d)
78 port=$(python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])')
89 bin=$(mktemp -d)/server
910 (cd "$root" && go build -o "$bin" ./cmd/server)
10- "$bin" --seed "$seed" --addr "127.0.0.1:$port" --web "$root/web" >"$log" 2>&1 &
11+ "$bin" --seed "$seed" --addr "127.0.0.1:$port" --web "$root/web" --data "$data" >"$log" 2>&1 &
1112 server_pid=$!
1213 trap 'kill $server_pid 2>/dev/null || true' EXIT
1314 base="http://127.0.0.1:$port"
scripts/verify.mjs+11-1
@@ -4,6 +4,7 @@ import { createDriver, sleep } from './driver.mjs';
44 import { maxHp } from '../web/js/stats.js';
55 import { createBot, playOut, apiIO, finished, night } from './bot.mjs';
66 import { layoutIssues } from './layout.mjs';
7+import { checkFights } from './fights.mjs';
78
89 const [outDir, baseUrl, seedArg] = process.argv.slice(2);
910 const SEED = Number(seedArg || 7);
@@ -16,7 +17,7 @@ const SHORT_STEPS = 2;
1617 const driver = createDriver({ session: SESSION, baseUrl, w: 0, h: 0 });
1718 const { ab, api } = driver;
1819
19-const sum = (s) => ({ phase: s.phase, day: s.clock.day, time: s.clock.time, x: s.party.x, y: s.party.y, battles: s.summary.battles, kills: s.summary.kills, loot: s.summary.loot, steps: s.summary.steps, gold: s.party.gold, inv: s.party.inventory?.length ?? 0, levels: s.party.units.map((u) => u.level).join('/'), winner: s.winner || null });
20+const sum = (s) => ({ phase: s.phase, day: s.clock.day, time: s.clock.time, x: s.party.x, y: s.party.y, battles: s.summary.battles, kills: s.summary.kills, loot: s.summary.loot, steps: s.summary.steps, gold: s.party.gold, inv: s.party.inventory?.length ?? 0, levels: s.party.units.map((u) => u.level).join('/'), hp: s.party.units.map((u) => u.stats.hp).join('/') });
2021 const fmt = (o) => Object.entries(o).map(([k, v]) => `${k}=${v}`).join(' ');
2122
2223 const report = { seed: SEED, baseUrl, startedAt: new Date().toISOString(), resolutions: [] };
@@ -266,6 +267,13 @@ async function runResolution([w, h], record) {
266267 }
267268
268269 mkdirSync(outDir, { recursive: true });
270+const FIGHT_SEEDS = [1, 2, 3, 4, 5];
271+console.log(`== fights through the API, seeds ${FIGHT_SEEDS.join(', ')}`);
272+report.fights = await checkFights(api, FIGHT_SEEDS);
273+for (const want of ['heal', 'buff']) if (!report.fights.kinds[want]) report.fights.problems.push(`no ${want} event in ${report.fights.fights} fights, so it went unchecked`);
274+failures += report.fights.problems.length;
275+console.log(` ${report.fights.problems.length ? 'FAIL' : 'ok '} ${report.fights.fights} fights replayed, mend ${report.fights.abilities.mend || 0}, rally ${report.fights.abilities.rally || 0}, lifesteal ${report.fights.abilities.lifesteal || 0}`);
276+for (const p of report.fights.problems.slice(0, 10)) console.log(` FAIL ${p}`);
269277 for (const r of RESOLUTIONS) {
270278 const tag = `${r[0]}x${r[1]}`;
271279 if (ONLY && !ONLY.includes(tag)) continue;
@@ -284,6 +292,8 @@ try { ab('close'); } catch {}
284292 report.failures = failures;
285293 writeFileSync(join(outDir, 'report.json'), JSON.stringify(report, null, 2));
286294 const md = [`# Verification report`, ``, `Seed ${SEED}, ${report.startedAt}. Total failures: **${failures}**.`, ``];
295+const fr = report.fights;
296+md.push(`## Fights through the API`, ``, `${fr.fights} fights on seeds ${FIGHT_SEEDS.join(', ')}, each log replayed through \`web/js/playback.js\` and checked against the server's hp. Event kinds: ${JSON.stringify(fr.kinds)}.`, ``, ...(fr.problems.length ? fr.problems.map((p) => `- FAIL ${p}`) : ['No problems.']), ``);
287297 for (const r of report.resolutions) {
288298 md.push(`## ${r.resolution}`, ``);
289299 if (r.aborted) md.push(`Harness aborted: ${r.aborted}`, ``);
web/index.html+1-1
@@ -2,7 +2,7 @@
22 <html lang="en">
33 <head>
44 <meta charset="utf-8">
5-<title>Tiny Adventure</title>
5+<title>Tiny Adventure</title><meta name="description" content="A seeded tabletop campaign in your browser. Free to play, no sign-up."><meta property="og:title" content="Tiny Adventure"><meta property="og:description" content="A seeded tabletop campaign in your browser. Free to play, no sign-up.">
66 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
77 <link rel="icon" href="data:,">
88 <style>html,body{margin:0;height:100%;overflow:hidden;background:#150e08}canvas{display:block;touch-action:none}pre{color:#f4e6c0;font:16px Georgia,serif;padding:24px}</style>
web/js/api.js+3-1
@@ -1,7 +1,7 @@
11 async function call(method, url, body) {
22 const res = await fetch(url, {
33 method,
4- headers: { 'Content-Type': 'application/json', 'X-Player': 'local' },
4+ headers: { 'Content-Type': 'application/json' },
55 body: body ? JSON.stringify(body) : undefined,
66 });
77 const data = await res.json();
@@ -35,3 +35,5 @@ export const rest = () => call('POST', '/api/rest', {});
3535 export const buy = (item) => call('POST', '/api/buy', { item });
3636 export const sell = (item) => call('POST', '/api/sell', { item });
3737 export const drink = (unit) => call('POST', '/api/drink', { unit });
38+export const run = (id) => call('GET', `/api/run/${id}`);
39+export const feedback = (text) => call('POST', '/api/feedback', { text });
web/js/board.js+18-12
@@ -1,6 +1,7 @@
11 import * as THREE from '../vendor/three.module.js';
22 import { HEX, hexToWorld, hexDistance } from './hex.js';
33 import { BIOMES, DEEP, ROAD, SNOW, TRUNK_PAINT, BURNT, PRIMER } from './paint.js';
4+import { sway } from './life.js';
45 import { CANOPY, SNOW_TIPS, TRUNK, TREE_TRUNK, MOUNTAIN, MOUNTAIN_CAP, ROCKS, TUFT } from './flora.js';
56
67 const SHAPE = { DEEP: 0, SHALLOW: 1, PLAIN: 2, HILL: 3, MOUNTAIN: 4, PEAK: 5 };
@@ -67,9 +68,9 @@ export function createBoard(map) {
6768 const mount = layer(MOUNTAIN, { cast: true });
6869 const snow = layer(MOUNTAIN_CAP, { cast: true });
6970 const trunks = layer(TRUNK, { cast: true });
70- const tips = layer(SNOW_TIPS, { cast: true });
71- const tufts = layer(TUFT);
72- const canopies = Object.fromEntries(Object.entries(CANOPY).map(([k, g]) => [k, layer(g, { cast: true })]));
71+ const tips = layer(SNOW_TIPS, { cast: true, sway: 0.05 });
72+ const tufts = layer(TUFT, { sway: 0.12 });
73+ const canopies = Object.fromEntries(Object.entries(CANOPY).map(([k, g]) => [k, layer(g, { cast: true, sway: 0.05 })]));
7374 const rocks = Object.fromEntries(Object.entries(ROCKS).map(([k, g]) => [k, layer(g, { cast: true })]));
7475 const put = (l, hex, x, y, z, angle, sx, sy, color, shade) => {
7576 m4.compose(v.set(x, y, z), q.setFromAxisAngle(UP, angle), s.set(sx, sy, sx));
@@ -145,7 +146,9 @@ export function createBoard(map) {
145146 const group = new THREE.Group();
146147 const byHex = Array.from({ length: W * H }, () => []);
147148 for (const l of layers) {
148- const mesh = new THREE.InstancedMesh(l.geometry, new THREE.MeshStandardMaterial({ color: '#ffffff', roughness: 0.9, flatShading: true, vertexColors: !!l.vertexColors }), Math.max(1, l.items.length));
149+ const material = new THREE.MeshStandardMaterial({ color: '#ffffff', roughness: 0.9, flatShading: true, vertexColors: !!l.vertexColors });
150+ if (l.sway) sway(material, l.sway);
151+ const mesh = new THREE.InstancedMesh(l.geometry, material, Math.max(1, l.items.length));
149152 mesh.count = l.items.length;
150153 mesh.castShadow = !!l.cast;
151154 mesh.frustumCulled = false;
@@ -170,7 +173,7 @@ export function createBoard(map) {
170173 const explored = new Uint8Array(W * H);
171174 const primer = new THREE.Color(PRIMER);
172175 const tint = new THREE.Color();
173- let standing = -1;
176+ let kept = [];
174177 const up = new Uint8Array(W * H);
175178 const stand = (i, on) => {
176179 for (const [l, k] of byHex[i] || []) {
@@ -201,9 +204,12 @@ export function createBoard(map) {
201204 l.mesh.instanceMatrix.needsUpdate = true;
202205 l.mesh.instanceColor.needsUpdate = true;
203206 }
204- if (standing >= 0) stand(standing, true);
205- standing = py * W + px;
206- stand(standing, false);
207+ }
208+
209+ function shelter(list) {
210+ for (const i of kept) if (!list.includes(i)) stand(i, !cleared.includes(i));
211+ kept = list;
212+ for (const i of kept) stand(i, false);
207213 }
208214
209215 function update(now) {
@@ -217,15 +223,15 @@ export function createBoard(map) {
217223 if (k < 1) continue;
218224 rising.splice(n, 1);
219225 up[r.i] = 1;
220- stand(r.i, r.i !== standing && !cleared.includes(r.i));
226+ stand(r.i, !kept.includes(r.i) && !cleared.includes(r.i));
221227 }
222228 }
223229
224230 let cleared = [];
225231 function arena(px, py, radius) {
226- for (const i of cleared) stand(i, true);
232+ for (const i of cleared) stand(i, !kept.includes(i));
227233 cleared = [];
228- if (px == null) return stand(standing, false);
234+ if (px == null) return;
229235 for (let r = 0; r < H; r++) for (let c = 0; c < W; c++) if (hexDistance(c, r, px, py) <= radius) cleared.push(r * W + c);
230236 for (const i of cleared) stand(i, false);
231237 }
@@ -235,5 +241,5 @@ export function createBoard(map) {
235241 return { x: i % W, y: Math.floor(i / W) };
236242 };
237243 const seen = (c, r) => explored[r * W + c] === 1;
238- return { group, pick: tiles.mesh, hexOf, pos, walkable, reveal, arena, seen, center, look, update };
244+ return { group, pick: tiles.mesh, hexOf, pos, walkable, reveal, shelter, arena, seen, center, look, update };
239245 }
web/js/combat.js+50-21
@@ -3,8 +3,12 @@ import { part } from './props.js';
33 import { createMini, flash } from './minis.js';
44 import { maxHp } from './stats.js';
55 import { T } from './theme.js';
6+import { track } from './debug.js';
7+import { applyEvent } from './playback.js';
68
79 const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
10+const RANGE = 2.4;
11+const SPREAD = 1.7;
812
913 export function createCombat(scene, party, cam, ui, sound) {
1014 const anims = [];
@@ -31,16 +35,18 @@ export function createCombat(scene, party, cam, ui, sound) {
3135 bar.fill.position.x = -0.38 * (1 - r);
3236 }
3337
34- function spawnEnemies(encounter) {
38+ function spawnEnemies(encounter, dir) {
3539 const base = party.pos;
40+ const across = new THREE.Vector3(-dir.z, 0, dir.x);
3641 const n = encounter.enemies.length;
3742 return encounter.enemies.map((e, i) => {
3843 const big = encounter.boss && i === 0;
3944 const fig = createMini(e, { enemy: true, boss: big });
4045 const size = fig.userData.size;
41- const side = encounter.boss ? (i % 2 ? 1 : -1) * (0.9 + Math.floor((i - 1) / 2) * 0.8) : (i - (n - 1) / 2) * 0.75;
42- fig.position.set(base.x + (big ? 2.7 : 2.1 + (i % 2) * 0.6), base.y, base.z + (big ? 0 : side));
43- fig.rotation.y = -Math.PI / 2;
46+ const side = encounter.boss ? (i % 2 ? 1 : -1) * (0.95 + Math.floor((i - 1) / 2) * 0.7) : (i - (n - 1) / 2) * 0.7;
47+ const depth = big ? RANGE + 0.5 : RANGE + (encounter.boss ? 0 : (i % 2) * 0.35);
48+ fig.position.copy(base).addScaledVector(dir, depth).addScaledVector(across, big ? 0 : side);
49+ fig.rotation.y = Math.atan2(-dir.x, -dir.z);
4450 fig.scale.setScalar(0.01);
4551 tween(0.35, (p) => fig.scale.setScalar(size * Math.max(0.01, p)));
4652 scene.add(fig);
@@ -61,9 +67,7 @@ export function createCombat(scene, party, cam, ui, sound) {
6167 }
6268
6369 function strike(ev, t, ab, heal) {
64- const cur = hp.get(ev.target) ?? 0;
65- const next = heal ? Math.min(t.max, cur + ev.amount) : Math.max(0, cur - ev.amount);
66- hp.set(ev.target, next);
70+ const next = applyEvent(hp, ev, t.max);
6771 if (!t.ally) setBar(t.bar, next / t.max);
6872 if (!heal && ev.amount > 0) {
6973 flash(t.fig);
@@ -80,17 +84,34 @@ export function createCombat(scene, party, cam, ui, sound) {
8084 sound.play('fall');
8185 cam.shake(0.35);
8286 const f = t.fig;
83- if (t.ally) tween(0.4, (p) => (f.rotation.z = (p * Math.PI) / 2));
87+ if (t.ally) {
88+ const body = f.userData.body;
89+ party.topple(f, true);
90+ const end = body.rotation.z;
91+ tween(0.4, (p) => (body.rotation.z = end * p));
92+ }
8493 else tween(0.5, (p) => (f.scale.setScalar(Math.max(0.01, (1 - p) * f.userData.size)), (f.position.y = t.home.y - p * 0.3)));
8594 }
8695 }
8796
88- async function play(state, before) {
97+ function boost(ev, t) {
98+ flash(t.fig, T.accent);
99+ sound.play('heal');
100+ const [sx, sy] = cam.screenOf(t.fig);
101+ ui.floater(sx, sy, `+${ev.amount}% power`, 'gain');
102+ }
103+
104+ async function play(state, before, at) {
89105 const enc = state.encounter;
90106 const log = state.log || [];
91107 const poi = state.map.pois.find((q) => q.id === enc.poi);
92108 ui.setCombat(true, enc.boss ? `Boss fight at ${poi.name}` : poi ? `Fight at ${poi.name}` : `Fight: ${enc.enemies[0].name}`);
93- const foes = spawnEnemies(enc);
109+ const dir = at.clone().sub(party.pos).setY(0);
110+ if (dir.lengthSq() < 1e-4) dir.set(1, 0, 0);
111+ dir.normalize();
112+ party.face(Math.atan2(dir.x, dir.z), true);
113+ party.widen(SPREAD);
114+ const foes = spawnEnemies(enc, dir);
94115 enemies = foes;
95116 const ids = new Map();
96117 hp.clear();
@@ -108,12 +129,8 @@ export function createCombat(scene, party, cam, ui, sound) {
108129 hp.set(u.id, p.stats.hp);
109130 u.abilities.forEach((a) => abilities.set(a.id, a));
110131 });
111- for (const f of party.figures.values()) {
112- f.rotation.y = Math.PI / 2;
113- f.userData.mode = 'idle';
114- }
115- const mid = party.pos.clone();
116- mid.x += 1.6;
132+ for (const f of party.figures.values()) f.userData.mode = 'idle';
133+ const mid = party.pos.clone().addScaledVector(dir, RANGE / 2);
117134 cam.setFocus(mid, 10);
118135 ui.render(before, hp);
119136 ui.logLine(`${enc.boss ? 'Boss fight' : 'Fight'}: ${foes.map((f) => f.unit.name).join(', ')}`, 'head');
@@ -127,22 +144,26 @@ export function createCombat(scene, party, cam, ui, sound) {
127144 const a = ids.get(ev.actor);
128145 const t = ids.get(ev.target);
129146 const ab = abilities.get(ev.ability);
130- const heal = ab && ab.kind === 'heal';
147+ const heal = ev.kind === 'heal';
148+ const buff = ev.kind === 'buff';
131149 if (a) {
132- a.fig.userData.mode = heal ? 'cast' : 'fight';
150+ a.fig.userData.mode = heal || buff ? 'cast' : 'fight';
133151 a.fig.userData.swing?.();
134- if (t && a !== t && !heal) lunge(a.fig, t.fig.position, (turn / 1000) * 0.9);
152+ if (t && a !== t && !heal && !buff) lunge(a.fig, t.fig.position, (turn / 1000) * 0.9);
135153 }
136154 await sleep(turn * 0.45);
137- if (t) strike(ev, t, ab, heal);
155+ if (t && buff) boost(ev, t);
156+ else if (t) strike(ev, t, ab, heal);
138157 ui.logLine(ev.text, ev.killed ? 'kill' : ev.crit ? 'crit' : '');
139158 ui.render(before, hp);
140159 await sleep(turn * 0.55);
141160 if (a) a.fig.userData.mode = 'idle';
142161 }
143162 await sleep(500);
144- for (const u of state.party.units) party.figures.get(u.id).rotation.z = 0;
163+ track.drift = drift(state, before, foes);
145164 for (const f of party.figures.values()) f.userData.mode = null;
165+ party.sync(state.party.units);
166+ party.widen(1);
146167 for (const f of foes) scene.remove(f.fig);
147168 bars.length = 0;
148169 enemies = [];
@@ -150,6 +171,14 @@ export function createCombat(scene, party, cam, ui, sound) {
150171 ui.setCombat(false);
151172 }
152173
174+ function drift(state, before, foes) {
175+ const out = [];
176+ const was = Object.fromEntries(before.party.units.map((u) => [u.id, u.level]));
177+ for (const u of state.party.units) if (was[u.id] === u.level && hp.get(u.id) !== u.stats.hp) out.push(`${u.name} shown ${hp.get(u.id)} hp, server ${u.stats.hp}`);
178+ if (state.rewards) for (const f of foes) if (hp.get(f.unit.id) !== 0) out.push(`${f.unit.name} shown ${hp.get(f.unit.id)} hp after a won fight`);
179+ return out;
180+ }
181+
153182 function update(dt) {
154183 for (const e of enemies) e.fig.userData.animate(e.fig.userData.mode || 'idle', dt);
155184 for (let i = anims.length - 1; i >= 0; i--) {
web/js/debug.js+2-1
@@ -28,7 +28,7 @@ export function installDebug(ctx) {
2828 viewport: () => ({ w: innerWidth, h: innerHeight, dpr: devicePixelRatio }),
2929 state: () => {
3030 const s = getState();
31- return s && { phase: s.phase, seed: s.seed, party: { x: s.party.x, y: s.party.y, gold: s.party.gold, potions: s.party.potions, inventory: s.party.inventory.length, units: s.party.units.map((u) => ({ id: u.id, level: u.level, hp: u.stats.hp })) }, threat: s.threat ? { poi: s.threat.poi, odds: s.threat.odds, barred: !!s.threat.barred } : null, shop: s.shop?.id || null, clock: s.clock, summary: s.summary, winner: s.winner || null };
31+ return s && { phase: s.phase, seed: s.seed, party: { x: s.party.x, y: s.party.y, gold: s.party.gold, potions: s.party.potions, inventory: s.party.inventory.length, units: s.party.units.map((u) => ({ id: u.id, level: u.level, hp: u.stats.hp })) }, threat: s.threat ? { poi: s.threat.poi, odds: s.threat.odds, barred: !!s.threat.barred } : null, shop: s.shop?.id || null, clock: s.clock, summary: s.summary, game: s.game, feedback: !!s.feedback };
3232 },
3333 partyWorld: () => ({ x: party.pos.x, y: party.pos.z }),
3434 rects: () => track.rects(),
@@ -43,5 +43,6 @@ export function installDebug(ctx) {
4343 pickAt: (sx, sy) => getWorld().pick(new THREE.Vector2((sx / innerWidth) * 2 - 1, -(sy / innerHeight) * 2 + 1), cam.camera),
4444 setRects: (fn) => { track.rects = fn; },
4545 perf: () => perf(renderer),
46+ drift: () => track.drift || [],
4647 };
4748 }
web/js/feedback.js+84-0
@@ -0,0 +1,84 @@
1+import { drawText, wrap, lineHeight } from './text.js';
2+import { T } from './theme.js';
3+
4+const MAX = 2000;
5+const MIN = 3;
6+const SIZE = 14;
7+
8+export function createFeedback(layer, m, f) {
9+ const area = document.createElement('textarea');
10+ area.maxLength = MAX;
11+ area.setAttribute('aria-label', 'Feedback');
12+ Object.assign(area.style, { position: 'fixed', left: '0', top: '0', width: '1px', height: '1px', opacity: '0', border: '0', padding: '0', resize: 'none' });
13+ document.body.append(area);
14+ const focused = () => document.activeElement === area;
15+
16+ const cta = layer.add('feedback-cta', {
17+ z: 2,
18+ draw(ctx, w, h, wd) {
19+ f.button(ctx, 0, 0, w, h, 'Give feedback?', { hover: wd.hovered('feedback-open'), size: 13 });
20+ wd.hit(0, 0, w, h, { name: 'feedback-open', key: 'feedback-open', onClick: m.openFeedback });
21+ },
22+ });
23+
24+ const panel = layer.add('panel-feedback', {
25+ z: 3,
26+ draw(ctx, w, h, wd) {
27+ const pad = 16;
28+ f.panel(ctx, 0, 0, w, h, 'surface');
29+ drawText(ctx, 'Feedback', pad, 12, { h: 30, size: 22, display: true });
30+ let y = 46;
31+ for (const line of wrap(ctx, 'What worked, what did not? Your note goes in with this game\'s log and nothing else about you.', 13, 'normal', w - pad * 2)) {
32+ drawText(ctx, line, pad, y, { h: lineHeight(13), size: 13, color: T.muted });
33+ y += lineHeight(13);
34+ }
35+ y += 8;
36+ const bottom = h - pad - 40 - 26;
37+ const on = focused();
38+ f.panel(ctx, pad, y, w - pad * 2, bottom - y, 'bg', on ? T.accent : T.line);
39+ wd.hit(pad, y, w - pad * 2, bottom - y, { name: 'feedback-text', key: 'feedback-text', onClick: () => area.focus() });
40+ const text = area.value;
41+ const rows = Math.max(1, Math.floor((bottom - y - 16) / lineHeight(SIZE)));
42+ if (!text && !on) drawText(ctx, 'Click here and type', pad + 10, y + 8, { h: lineHeight(SIZE), size: SIZE, color: T.faint });
43+ else {
44+ const lines = wrap(ctx, text + (on ? '|' : ''), SIZE, 'normal', w - pad * 2 - 20);
45+ lines.slice(-rows).forEach((l, i) => drawText(ctx, l, pad + 10, y + 8 + i * lineHeight(SIZE), { h: lineHeight(SIZE), size: SIZE, maxW: w - pad * 2 - 20, fit: true }));
46+ }
47+ const status = m.feedbackError || (on ? 'Ctrl+Enter sends, Esc closes' : '');
48+ drawText(ctx, status, pad, bottom + 4, { h: 18, size: 12, color: m.feedbackError ? T.danger : T.faint, maxW: w - pad * 2 - 90, fit: true });
49+ drawText(ctx, `${text.length}/${MAX}`, w - pad, bottom + 4, { h: 18, size: 12, color: T.faint, align: 'right' });
50+ const bw = (w - pad * 2 - 10) / 2;
51+ const ready = text.trim().length >= MIN && !m.feedbackBusy;
52+ f.button(ctx, pad, h - pad - 40, bw, 40, m.feedbackBusy ? 'Sending' : 'Send', { primary: ready, disabled: !ready, hover: wd.hovered('feedback-send'), size: 15 });
53+ wd.hit(pad, h - pad - 40, bw, 40, { name: 'feedback-send', key: 'feedback-send', onClick: () => ready && m.sendFeedback(text.trim()) });
54+ f.button(ctx, pad + bw + 10, h - pad - 40, bw, 40, 'Cancel', { hover: wd.hovered('feedback-cancel'), size: 15 });
55+ wd.hit(pad + bw + 10, h - pad - 40, bw, 40, { name: 'feedback-cancel', key: 'feedback-cancel', onClick: () => m.closePanel() });
56+ },
57+ });
58+
59+ area.addEventListener('input', () => {
60+ m.feedbackError = '';
61+ panel.invalidate();
62+ });
63+ area.addEventListener('focus', () => panel.invalidate());
64+ area.addEventListener('blur', () => panel.invalidate());
65+ area.addEventListener('keydown', (e) => {
66+ e.stopPropagation();
67+ if (e.key === 'Escape') {
68+ e.preventDefault();
69+ m.closePanel();
70+ } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && area.value.trim().length >= MIN) {
71+ e.preventDefault();
72+ m.sendFeedback(area.value.trim());
73+ }
74+ });
75+
76+ const sync = () => {
77+ if (m.panel !== 'feedback' && focused()) area.blur();
78+ };
79+ const clear = () => {
80+ area.value = '';
81+ area.blur();
82+ };
83+ return { widgets: { 'feedback-cta': cta, 'panel-feedback': panel }, sync, clear, focus: () => area.focus() };
84+}
web/js/hud.js+32-3
@@ -153,7 +153,7 @@ export function createHud(layer, m, f) {
153153 ctx.beginPath();
154154 ctx.rect(cx, by, cw2, bh);
155155 ctx.clip();
156- drawText(ctx, `${cur}/${max}`, x + cw / 2, by, { h: bh, size: small ? 10 : 11, align: 'center', weight: 'bold', color });
156+ drawText(ctx, cur ? `${cur}/${max}` : 'Fallen', x + cw / 2, by, { h: bh, size: small ? 10 : 11, align: 'center', weight: 'bold', color });
157157 ctx.restore();
158158 });
159159 f.bar(ctx, x + 8, h - 7, bw, 2, Math.min(1, u.xp / (40 * u.level)), T.faint);
@@ -168,7 +168,7 @@ export function createHud(layer, m, f) {
168168 const s = m.state;
169169 const items = [['btn-inv', 'Inventory', 'I', 'inv'], ['btn-journal', 'Journal', 'J', 'journal']];
170170 if (s.shop) items.push(['btn-shop', 'Trader', 'T', 'shop']);
171- if (s.clock.time >= s.clock.dayLength && !m.combat && !m.threat) items.push(['btn-camp', 'Make camp', 'C', null]);
171+ if (s.clock.time >= s.clock.dayLength && !m.combat && !m.threat && !m.camp) items.push(['btn-camp', 'Make camp', 'C', null]);
172172 const grid = h > 60;
173173 const gap = 6;
174174 const cols = grid ? 2 : items.length;
@@ -193,5 +193,34 @@ export function createHud(layer, m, f) {
193193 },
194194 });
195195
196- return { topbar, log, bottom, portraits, menu, 'combat-banner': banner };
196+ const camp = layer.add('camp-banner', {
197+ z: 2,
198+ passive: true,
199+ draw(ctx, w, h) {
200+ const { day, k } = m.camp;
201+ const dawn = k > 0.85;
202+ f.panel(ctx, 0, 0, w, h, 'surface', dawn ? T.accent : T.line);
203+ drawText(ctx, dawn ? `Dawn of day ${day + 1}` : `Night ${day} passes by the fire`, w / 2, 6, { h: 24, size: 16, display: true, align: 'center', color: dawn ? T.accent : T.fg, maxW: w - 16, fit: true });
204+ const x = 18;
205+ const bw = w - 36;
206+ const y = h - 16;
207+ ctx.fillStyle = T.bg;
208+ ctx.fillRect(x, y - 2, bw, 4);
209+ ctx.fillStyle = T.faint;
210+ ctx.fillRect(x, y - 2, bw * k, 4);
211+ const px = x + bw * k;
212+ ctx.fillStyle = dawn ? T.accent : T.fg;
213+ ctx.beginPath();
214+ ctx.arc(px, y, 5, 0, Math.PI * 2);
215+ ctx.fill();
216+ if (!dawn) {
217+ ctx.fillStyle = T.surface;
218+ ctx.beginPath();
219+ ctx.arc(px + 2.2, y - 1.5, 4, 0, Math.PI * 2);
220+ ctx.fill();
221+ }
222+ },
223+ });
224+
225+ return { topbar, log, bottom, portraits, menu, 'combat-banner': banner, 'camp-banner': camp };
197226 }
web/js/layout.js+6-1
@@ -16,7 +16,7 @@ export function layoutFor(lw, lh, m) {
1616 const wide = 10 + PORTRAITS_W + 16 + MENU_W + 10 <= lw;
1717 out.scrim = m.screen ? { x: 0, y: 0, w: lw, h: lh } : null;
1818 const cw = Math.min(lw - 2 * pad, 500);
19- const ch = Math.min(lh - 2 * pad, m.screen === 'end' ? 430 : cw < 460 ? 470 : 400);
19+ const ch = Math.min(lh - 2 * pad, m.screen === 'end' ? (cw < 460 ? 430 : 410) : cw < 460 ? 490 : 420);
2020 out.card = m.screen ? { x: (lw - cw) / 2, y: (lh - ch) / 2, w: cw, h: ch } : null;
2121 if (!m.hud) return out;
2222
@@ -38,6 +38,10 @@ export function layoutFor(lw, lh, m) {
3838 out['panel-inv'] = m.panel === 'inv' ? panel : null;
3939 out['panel-journal'] = m.panel === 'journal' ? panel : null;
4040 out['panel-shop'] = m.panel === 'shop' ? panel : null;
41+ const fw = Math.min(lw - 2 * pad, 520);
42+ const fh = Math.min(avail, 340);
43+ out['panel-feedback'] = m.panel === 'feedback' ? { x: (lw - fw) / 2, y: TOP + (avail - fh) / 2, w: fw, h: fh } : null;
44+ out['feedback-cta'] = m.state.feedback && !m.panel && !m.threat && !m.combat && !m.camp ? { x: out.topbar.x + tw - 136, y: TOP, w: 136, h: 30 } : null;
4145 if (m.threat) {
4246 const w = Math.min(lw - 2 * pad, 400);
4347 const h = Math.min(avail, threatHeight(m.threat.threat));
@@ -48,5 +52,6 @@ export function layoutFor(lw, lh, m) {
4852 const logH = lines * 17 + 12;
4953 out.log = m.panel || m.threat || m.hush || !lines ? null : { x: pad, y: lh - bh - pad - logH, w: logW, h: logH };
5054 out['combat-banner'] = m.combat ? { x: (lw - 300) / 2, y: TOP, w: 300, h: 34 } : null;
55+ out['camp-banner'] = m.camp ? { x: (lw - 300) / 2, y: TOP, w: 300, h: 58 } : null;
5156 return out;
5257 }
web/js/life.js+127-0
@@ -0,0 +1,127 @@
1+import * as THREE from '../vendor/three.module.js';
2+
3+const PUFFS = 5;
4+const PUFF_LIFE = 3.4;
5+const MAX_SOURCES = 24;
6+const FLIES = 48;
7+const FLY_RANGE = 4.5;
8+const FLOCKS = 2;
9+const BIRDS = 3;
10+
11+export const wind = { value: 0 };
12+
13+export function sway(material, amount) {
14+ material.onBeforeCompile = (sh) => {
15+ sh.uniforms.uWind = wind;
16+ sh.vertexShader = `uniform float uWind;\n${sh.vertexShader}`.replace('#include <begin_vertex>', `#include <begin_vertex>
17+ float phase = instanceMatrix[3].x * 0.7 + instanceMatrix[3].z * 0.5;
18+ float bend = max(position.y, 0.0) * ${amount.toFixed(3)};
19+ transformed.x += sin(uWind * 1.7 + phase) * bend;
20+ transformed.z += cos(uWind * 1.3 + phase * 1.3) * bend * 0.6;`);
21+ };
22+ return material;
23+}
24+
25+const m4 = new THREE.Matrix4();
26+const q = new THREE.Quaternion();
27+const v = new THREE.Vector3();
28+const s = new THREE.Vector3();
29+const qz = new THREE.Quaternion();
30+const UP = new THREE.Vector3(0, 1, 0);
31+const FWD = new THREE.Vector3(0, 0, 1);
32+const FLIP = new THREE.Quaternion().setFromAxisAngle(UP, Math.PI);
33+
34+function wing() {
35+ const g = new THREE.BufferGeometry();
36+ g.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0.06, 0, 0, -0.06, 0.22, 0, 0], 3));
37+ g.computeVertexNormals();
38+ return g;
39+}
40+
41+export function createLife(group) {
42+ const center = new THREE.Vector3();
43+ let homed = false;
44+ const smoke = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(0.09, 0), new THREE.MeshStandardMaterial({ color: '#a8a29a', roughness: 1, flatShading: true, transparent: true, opacity: 0.55, depthWrite: false }), MAX_SOURCES * PUFFS);
45+ smoke.frustumCulled = false;
46+ smoke.count = 0;
47+ smoke.raycast = () => {};
48+ group.add(smoke);
49+ let sources = [];
50+
51+ const flyPos = new Float32Array(FLIES * 3);
52+ const flySeed = Array.from({ length: FLIES }, () => [Math.random() * 100, Math.random() * 2 - 1, Math.random() * 2 - 1, 0.2 + Math.random() * 0.8]);
53+ const flyGeo = new THREE.BufferGeometry();
54+ flyGeo.setAttribute('position', new THREE.BufferAttribute(flyPos, 3));
55+ const flies = new THREE.Points(flyGeo, new THREE.PointsMaterial({ color: '#e6ff9c', size: 0.09, transparent: true, opacity: 0, blending: THREE.AdditiveBlending, depthWrite: false }));
56+ flies.frustumCulled = false;
57+ flies.raycast = () => {};
58+ group.add(flies);
59+
60+ const birds = new THREE.InstancedMesh(wing(), new THREE.MeshStandardMaterial({ color: '#2b2621', side: THREE.DoubleSide, roughness: 1 }), FLOCKS * BIRDS * 2);
61+ birds.frustumCulled = false;
62+ birds.castShadow = true;
63+ birds.raycast = () => {};
64+ group.add(birds);
65+ const flocks = Array.from({ length: FLOCKS }, (_, i) => ({ r: 3.5 + i * 2.2, h: 2.8 + i * 0.6, speed: (i ? -1 : 1) * (0.22 + i * 0.05), phase: i * 2.4, cx: (i ? -1 : 1) * 2.5, cz: (i ? 2 : -1.5) }));
66+ const flags = [];
67+
68+ function setSources(list) {
69+ sources = list.slice(0, MAX_SOURCES);
70+ smoke.count = sources.length * PUFFS;
71+ }
72+
73+ function track(obj) {
74+ obj.traverse((o) => o.userData.wave && flags.push({ o, phase: Math.random() * 6 }));
75+ }
76+
77+ function update(t, dark, focus) {
78+ wind.value = t;
79+ sources.forEach((src, i) => {
80+ for (let k = 0; k < PUFFS; k++) {
81+ const life = ((t + k * (PUFF_LIFE / PUFFS) + i * 0.37) % PUFF_LIFE) / PUFF_LIFE;
82+ const size = (src.size || 1) * (life < 0.7 ? 0.6 + life * 1.4 : 1.58 * (1 - (life - 0.7) / 0.3));
83+ v.set(src.p.x + life * 0.35 + Math.sin(t + k) * 0.05, src.p.y + life * 1.3, src.p.z + Math.cos(t * 0.7 + k) * 0.05);
84+ smoke.setMatrixAt(i * PUFFS + k, m4.compose(v, q.identity(), s.setScalar(Math.max(0.01, size))));
85+ }
86+ });
87+ smoke.instanceMatrix.needsUpdate = true;
88+
89+ flies.visible = dark > 0.05;
90+ flies.material.opacity = dark;
91+ if (flies.visible) {
92+ flySeed.forEach(([seed, ox, oz, hy], i) => {
93+ flyPos[i * 3] = focus.x + ox * FLY_RANGE + Math.sin(t * 0.4 + seed) * 0.6;
94+ flyPos[i * 3 + 1] = focus.y + hy + Math.sin(t * 1.3 + seed * 2) * 0.15;
95+ flyPos[i * 3 + 2] = focus.z + oz * FLY_RANGE + Math.cos(t * 0.33 + seed) * 0.6;
96+ });
97+ flyGeo.attributes.position.needsUpdate = true;
98+ }
99+
100+ if (!homed) center.copy(focus);
101+ homed = true;
102+ center.lerp(focus, 0.004);
103+ birds.visible = dark < 0.6;
104+ if (birds.visible) {
105+ let n = 0;
106+ for (const f of flocks) {
107+ const a0 = f.phase + t * f.speed;
108+ for (let b = 0; b < BIRDS; b++) {
109+ const a = a0 - b * 0.12 * Math.sign(f.speed);
110+ const r = f.r + (b % 2 ? 0.35 : -0.35) * Math.min(b, 1);
111+ v.set(center.x + f.cx + Math.cos(a) * r, center.y + f.h + Math.sin(t * 0.8 + b) * 0.1, center.z + f.cz + Math.sin(a) * r);
112+ const flap = Math.sin(t * 9 + b * 1.7) * 0.6;
113+ for (const side of [1, -1]) {
114+ q.setFromAxisAngle(UP, -a).multiply(qz.setFromAxisAngle(FWD, side * flap));
115+ if (side < 0) q.multiply(FLIP);
116+ birds.setMatrixAt(n++, m4.compose(v, q, s.setScalar(1)));
117+ }
118+ }
119+ }
120+ birds.instanceMatrix.needsUpdate = true;
121+ }
122+
123+ for (const f of flags) f.o.rotation.y = Math.sin(t * 2.3 + f.phase) * 0.3;
124+ }
125+
126+ return { setSources, track, update };
127+}
web/js/main.js+48-10
@@ -68,6 +68,11 @@ const ui = createUI(renderer, canvas, {
6868 onMute: () => ui.toast(sound.toggle() ? 'Sound off' : 'Sound on'),
6969 onHurry: () => combat.hurry(),
7070 onHalt: () => halt(),
71+ onFeedback: async (text) => {
72+ state = await api.feedback(text);
73+ ui.render(state);
74+ ui.toast('Thanks. Your note is in, with this game\'s log.');
75+ },
7176 });
7277 const combat = createCombat(scene, party, cam, ui, sound);
7378 const levelUp = createLevelUp(party, cam, ui, sound);
@@ -179,11 +184,12 @@ async function act(fn) {
179184
180185 function settle(next) {
181186 levelUp.play(state, next);
187+ party.sync(next.party.units);
182188 state = next;
183189 world.refresh(next);
184190 ui.render(next);
185191 for (const n of next.notes || []) {
186- ui.logLine(n, n.includes('hp') || n.includes('trap') ? 'kill' : 'hint');
192+ ui.logLine(n, /hp|trap|fallen/.test(n) ? 'kill' : 'hint');
187193 ui.toast(n);
188194 }
189195 for (const it of next.found || []) {
@@ -268,12 +274,12 @@ function fight() {
268274 const next = await api.interact(poiId);
269275 sky.setClock(next.clock);
270276 const poi = target(next, { poi: next.map.pois.some((p) => p.id === poiId) && poiId, band: poiId });
271- await party.walk([world.worldPos(poi.x, poi.y)]);
272277 world.stage(true);
273278 track.mode = 'combat';
274- await combat.play(next, before);
275- track.mode = 'explore';
279+ await combat.play(next, before, world.worldPos(poi.x, poi.y));
276280 world.stage(false);
281+ if (next.phase !== 'defeat') await party.walk([world.worldPos(next.party.x, next.party.y)]);
282+ track.mode = 'explore';
277283 const r = next.rewards;
278284 if (r) {
279285 ui.logLine(`Victory: +${r.xp} XP, +${r.gold} gold${r.items?.length ? ', ' + r.items.map((i) => i.name).join(', ') : ''}`, 'reward');
@@ -285,23 +291,40 @@ function fight() {
285291 });
286292 }
287293
288-async function restart() {
289- const s = await api.newGame();
294+async function restart(seed) {
295+ history.replaceState(null, '', '/');
296+ const s = await api.newGame(seed);
290297 load(s);
291298 ui.show(false);
292299 title(s);
293300 }
294301
302+async function share(run) {
303+ const url = `${location.origin}/r/${run.game}`;
304+ try {
305+ await navigator.clipboard.writeText(url);
306+ return true;
307+ } catch {
308+ return false;
309+ }
310+}
311+
312+function showRun(run, own) {
313+ track.mode = 'end';
314+ cam.orbit(0.06);
315+ ui.showEnd(run, { own, onShare: () => share(run), onSeed: () => restart(run.seed), onNew: () => restart() });
316+}
317+
295318 function title(s) {
296319 track.mode = 'title';
297320 cam.orbit(0.06);
298321 ui.showTitle(s, { onStart: begin, onNew: restart });
299322 }
300323
301-function endGame(s) {
324+async function endGame(s) {
302325 track.mode = 'end';
303- cam.orbit(0.06);
304- ui.showEnd(s, restart);
326+ history.replaceState(null, '', `/r/${s.game}`);
327+ showRun(await api.run(s.game), true);
305328 }
306329
307330 function begin() {
@@ -320,7 +343,11 @@ function makeCamp() {
320343 track.mode = 'camp';
321344 world.showLabels(false);
322345 sound.play('rest');
346+ party.gather(true);
347+ ui.camp(state.clock.day);
323348 await sky.camp(party.pos.clone());
349+ ui.camp(null);
350+ party.gather(false);
324351 world.showLabels(true);
325352 track.mode = 'explore';
326353 settle(next);
@@ -336,7 +363,7 @@ function frame() {
336363 if (world) {
337364 party.update(dt);
338365 levelUp.update(dt);
339- world.update(clock.elapsedTime);
366+ world.update(clock.elapsedTime, sky.dark(), party.pos);
340367 const key = tileOf(party.pos);
341368 if (key !== lastTile) {
342369 if (lastTile && party.moving()) sound.play('step');
@@ -344,10 +371,12 @@ function frame() {
344371 const [x, y] = key.split(',').map(Number);
345372 world.reveal(x, y);
346373 }
374+ world.shelter(party.pos, cam.camera.position);
347375 cam.follow(party.pos);
348376 sky.update(dt, party.pos);
349377 }
350378 combat.update(dt);
379+ ui.night(sky.night());
351380 cam.update(dt);
352381 renderer.info.reset();
353382 renderer.clear();
@@ -363,7 +392,16 @@ async function boot() {
363392 frame();
364393 installDebug({ getState: () => state, getWorld: () => world, cam, party, renderer });
365394 window.__game.setRects(ui.rects);
395+ const link = location.pathname.match(/^\/r\/([0-9a-f]{16})$/);
396+ if (link && link[1] !== state.game) {
397+ try {
398+ return showRun(await api.run(link[1]), false);
399+ } catch {
400+ history.replaceState(null, '', '/');
401+ }
402+ }
366403 if (state.phase === 'victory' || state.phase === 'defeat') return endGame(state);
404+ history.replaceState(null, '', '/');
367405 title(state);
368406 }
369407
web/js/minis.js+15-0
@@ -31,6 +31,21 @@ export function createMini(unit, { enemy = false, boss = false } = {}) {
3131 return g;
3232 }
3333
34+const ASH = new THREE.Color('#5a5650');
35+
36+export function dim(fig, on) {
37+ fig.traverse((o) => {
38+ if (!o.isMesh || !o.material.color) return;
39+ o.userData.base ||= o.material;
40+ if (on && !o.userData.ash) {
41+ o.userData.ash = o.userData.base.clone();
42+ o.userData.ash.color.lerp(ASH, 0.75);
43+ }
44+ o.userData.paint = on ? o.userData.ash : o.userData.base;
45+ o.material = o.userData.paint;
46+ });
47+}
48+
3449 export function flash(fig, color = '#ff3020', ms = 160) {
3550 const meshes = [];
3651 fig.traverse((o) => o.isMesh && o.material.emissive && meshes.push(o));
web/js/party.js+58-10
@@ -1,9 +1,12 @@
11 import * as THREE from '../vendor/three.module.js';
2-import { createMini } from './minis.js';
2+import { createMini, dim } from './minis.js';
33
4-const OFFSETS = [[-0.24, -0.2], [0.24, -0.2], [-0.24, 0.24], [0.24, 0.24], [0, 0]];
4+const MARCH = [[-0.27, 0.27], [0.27, 0.27], [-0.27, -0.27], [0.27, -0.27]];
5+const RING = [[-0.32, 0.32], [0.32, 0.32], [-0.32, -0.32], [0.32, -0.32]];
56 const SPEED = 4;
67 const PACE = 3.6;
8+const TURN = 8;
9+const TOPPLE = 1.35;
710
811 export function createParty(scene) {
912 const root = new THREE.Group();
@@ -12,21 +15,50 @@ export function createParty(scene) {
1215 const pos = new THREE.Vector3();
1316 let route = [];
1417 let resolve = null;
18+ let heading = 0;
19+ let goal = 0;
20+ let ring = false;
21+ let spread = 1;
1522
1623 function setUnits(units) {
1724 for (const f of figures.values()) root.remove(f);
1825 figures.clear();
1926 units.forEach((u, i) => {
2027 const f = createMini(u);

Cut short: this commit's diff is over 1000 lines.

web/js/playback.js+7-0

Cut short: this commit's diff is over 1000 lines.

web/js/props.js+5-1

Cut short: this commit's diff is over 1000 lines.

web/js/screens.js+52-24

Cut short: this commit's diff is over 1000 lines.

web/js/sky.js+4-3

Cut short: this commit's diff is over 1000 lines.

web/js/text.js+1-1

Cut short: this commit's diff is over 1000 lines.

web/js/ui.js+46-6

Cut short: this commit's diff is over 1000 lines.

web/js/world.js+50-7

Cut short: this commit's diff is over 1000 lines.