Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(war): show live league state on a terminal /play/war card so a dead pairing still ends at a door

nirholasebc7cfbff1de
diff --git a/pages/play/war.html b/pages/play/war.html
index 5cad6a1d1..43f0067cc 100644
--- a/pages/play/war.html
+++ b/pages/play/war.html
@@ -18,28 +18,42 @@
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Coin+Wars+arena%3A+two+communities%2C+one+battlefield&amp;d=The+live+Coin+Wars+arena.+Enlist+at+your+coin+world%27s+war+portal%2C+fight+the+rival+community+to+the+kill+cap%2C+and+the+result+lands+on+the+Elo+ladder.+You+fight&amp;p=%2Fplay%2Fwar" />
<link rel="canonical" href="https://three.ws/play/war" />
<link rel="icon" href="/favicon.ico" />
- <!-- The arena's two heaviest first-paint assets, preloaded only when this
- link actually carries a pairing. src/play/war.js returns early with "No
- battle to join" when match/ticket/coin are missing (a shared, expired, or
- hand-typed link), and a static preload on that path downloads a manifest
- and a 700 KB avatar the page never reads, which is what the browser
- reports as "preloaded ... but not used". Injecting from the head keeps
- the head start on the real path: this runs before the module graph below
- is even fetched. `crossorigin` stays because both consumers request in CORS mode
- (fetch() defaults to it; three's FileLoader builds a Request, which does
- too), so dropping it would silently orphan the preload instead. -->
+
+ <!-- The Colyseus service that hosts clash_arena, read through the shared
+ chain in src/shared/game-server-url.js. A production build resolves to
+ "" without it (localhost and the Codespace forward are inferred, the
+ public domain is not), which turned every arrival at this page into
+ "The arena server is unreachable". /play carries the same meta. -->
+ <meta name="game-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" />
+
+ <!-- Design tokens. This bespoke 3D page skips the global style.css, and
+ tokens.css is variables-only, so linking it does not touch the arena's
+ own layout. src/play/war.css spends the motion tokens on every hover,
+ focus and cooldown transition; unresolved they made the whole
+ `transition` declaration invalid and the HUD moved in hard cuts. -->
+ <link rel="stylesheet" href="/tokens.css" />
+ <!-- The clip manifest, preloaded only when this link actually carries a
+ pairing. src/play/war.js returns early with "No battle to join" when
+ match/ticket/coin are missing (a shared, expired, or hand-typed link),
+ and a static preload on that path downloads a file the page never reads,
+ which is what the browser reports as "preloaded ... but not used".
+ Injecting from the head keeps the head start on the real path: this runs
+ before the module graph below is even fetched. `crossorigin` stays
+ because the consumer requests in CORS mode (fetch() defaults to it), so
+ dropping it would silently orphan the preload instead. The fighter body
+ is warmed from war.js instead, immediately before the room join, because
+ it is only read once the play gate and the holder gate have both passed
+ and its URL is whichever avatar the player picked in /play. -->
<script>
(function () {
var q = new URLSearchParams(location.search);
if (!q.get('match') || !q.get('ticket') || !q.get('coin')) return;
- ['/animations/manifest.json', '/avatars/default.glb'].forEach(function (href) {
- var l = document.createElement('link');
- l.rel = 'preload';
- l.as = 'fetch';
- l.crossOrigin = 'anonymous';
- l.href = href;
- document.head.appendChild(l);
- });
+ var l = document.createElement('link');
+ l.rel = 'preload';
+ l.as = 'fetch';
+ l.crossOrigin = 'anonymous';
+ l.href = '/animations/manifest.json';
+ document.head.appendChild(l);
})();
</script>
<meta name="robots" content="index, follow, max-image-preview:large" />
@@ -50,6 +64,10 @@
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Coin Wars arena: two communities, one battlefield","description":"The live Coin Wars arena. Enlist at your coin world's war portal, fight the rival community to the kill cap, and the result lands on the Elo ladder. You fight for the coin you hold.","url":"https://three.ws/play/war","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Coin+Wars+arena%3A+two+communities%2C+one+battlefield&d=The+live+Coin+Wars+arena.+Enlist+at+your+coin+world%27s+war+portal%2C+fight+the+rival+community+to+the+kill+cap%2C+and+the+result+lands+on+the+Elo+ladder.+You+fight&p=%2Fplay%2Fwar"},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Play","item":"https://three.ws/play"},{"@type":"ListItem","position":3,"name":"War","item":"https://three.ws/play/war"}]}]}</script>
</head>
<body>
+ <!-- The page heading. A fullscreen arena has no chrome to hang a visible
+ title on, but the document still needs exactly one h1: the two cards
+ below are dialog headings and are mutually exclusive. -->
+ <h1 class="war-page-title">Coin Wars arena</h1>
<canvas id="scene" aria-label="Coin Wars battlefield"></canvas>
<div class="war-vignette" aria-hidden="true"></div>
<div id="labels" aria-hidden="true"></div>
@@ -91,7 +109,7 @@
<!-- Controls. Hidden until joined; the stick is thumb-sized on phones. -->
<div id="controls" class="war-controls" hidden>
- <div id="stick" class="war-stick no-orbit" aria-label="Move">
+ <div id="stick" class="war-stick no-orbit" aria-hidden="true">
<span id="stick-nub" class="war-stick-nub" aria-hidden="true"></span>
</div>
<div class="war-right">
@@ -99,16 +117,17 @@
<div><dt>Kills</dt><dd id="kills">0</dd></div>
<div><dt>Downs</dt><dd id="deaths">0</dd></div>
</dl>
- <button id="attack" class="war-attack no-orbit" type="button">Fire<small>space</small></button>
+ <button id="attack" class="war-attack no-orbit" type="button" aria-keyshortcuts="Space F">Fire<small aria-hidden="true">space</small></button>
<button id="leave" class="war-leave no-orbit" type="button">Leave</button>
</div>
<p id="downed" class="war-downed" role="status" hidden>You are down, respawning shortly.</p>
+ <p class="war-keys">WASD or the arrow keys to move</p>
</div>
<!-- Terminal states. Both are designed cards with the one way out. -->
<div id="result" class="war-modal" role="dialog" aria-modal="true" aria-labelledby="result-title" hidden>
<div class="war-modal-card">
- <h1 id="result-title" class="war-result-title">Battle over</h1>
+ <h2 id="result-title" class="war-result-title">Battle over</h2>
<p id="result-score" class="war-result-score"></p>
<p id="result-reason" class="war-modal-b"></p>
<p id="result-mvp" class="war-modal-b war-modal-faint"></p>
@@ -118,9 +137,14 @@
<div id="fail" class="war-modal" role="dialog" aria-modal="true" aria-labelledby="fail-title" hidden>
<div class="war-modal-card">
- <h1 id="fail-title" class="war-fail-title">No battle to join</h1>
+ <h2 id="fail-title" class="war-fail-title">No battle to join</h2>
<p id="fail-detail" class="war-modal-b"></p>
<button id="fail-back" class="war-modal-btn" type="button">Back to the world</button>
+ <!-- The war room. src/play/war-board.js fills this from /api/wars with
+ the battles running now, the communities queued for an opponent
+ and the top of the ladder, so a card that says "no battle here"
+ always ends in a door into a world that has one. -->
+ <div id="fail-board"></div>
</div>
</div>
diff --git a/src/play/war-board.js b/src/play/war-board.js
new file mode 100644
index 000000000..659b34e3d
--- /dev/null
+++ b/src/play/war-board.js
@@ -0,0 +1,325 @@
+// war-board.js: the war room panel the arena shows on any terminal card.
+//
+// /play/war is a destination, not a place you browse to: the war portal in a
+// coin world hands it a signed pairing. That leaves every terminal state on this
+// page (a hand-typed URL, a shared link, an expired ticket, a holding that came
+// up short) staring at one sentence and a button back to the lobby, which tells
+// a player nothing about where a war actually is.
+//
+// This panel answers that with real league state off /api/wars: the battles
+// running right now, the communities queued for an opponent, and the top of the
+// Elo ladder. Every row is a link into that coin's world, which is where the war
+// portal stands, so "there is no battle here" always ends in a door.
+//
+// The data is the same fold the in-world portal board reads
+// (multiplayer/src/war-standings.js through api/_lib/wars-store.js), so a rating
+// shown here is never a second opinion.
+
+import { createLogger } from '../shared/log.js';
+
+const log = createLogger('war-board');
+
+const ENDPOINT = '/api/wars';
+const TOP_N = 5;
+const LIVE_N = 4;
+const QUEUE_N = 4;
+// A war that kicks off while the player reads the card should appear. The live
+// registry heartbeats every 2s, so this is far cheaper than the data it tracks.
+const REFRESH_MS = 15_000;
+
+/**
+ * Render the war room into `host` and keep it fresh while the tab is visible.
+ * @param {HTMLElement} host container the panel is appended to
+ * @param {{network?: string, coin?: string}} opts the arena's network, and the
+ * coin this player came for (its ladder row is pinned when it has one)
+ * @returns {{dispose: () => void}}
+ */
+export function mountWarBoard(host, { network = 'mainnet', coin = '' } = {}) {
+ const root = el('section', 'war-board');
+ root.setAttribute('aria-live', 'polite');
+ host.appendChild(root);
+
+ let timer = 0;
+ let disposed = false;
+ let inFlight = null;
+
+ const load = async () => {
+ if (disposed) return;
+ if (inFlight) return;
+ const q = new URLSearchParams({ network, limit: '6' });
+ if (coin) q.set('coin', coin);
+ inFlight = fetch(`${ENDPOINT}?${q}`, { headers: { accept: 'application/json' } });
+ try {
+ const res = await inFlight;
+ const body = await res.json().catch(() => null);
+ if (disposed) return;
+ if (!res.ok || !body?.data) throw new Error(body?.error_description || `HTTP ${res.status}`);
+ paint(root, body.data, coin);
+ } catch (err) {
+ if (disposed) return;
+ log.warn('war board read failed', err);
+ paintError(root, load);
+ } finally {
+ inFlight = null;
+ }
+ };
+
+ const tick = () => {
+ if (disposed) return;
+ if (!document.hidden) load();
+ timer = setTimeout(tick, REFRESH_MS);
+ };
+
+ paintLoading(root);
+ load();
+ timer = setTimeout(tick, REFRESH_MS);
+
+ const onVisible = () => { if (!document.hidden) load(); };
+ document.addEventListener('visibilitychange', onVisible);
+
+ return {
+ dispose() {
+ disposed = true;
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisible);
+ root.remove();
+ },
+ };
+}
+
+// ── painting ─────────────────────────────────────────────────────────────────
+
+function paintLoading(root) {
+ root.textContent = '';
+ root.appendChild(heading('Reading the league'));
+ const skel = el('div', 'war-board-skeleton');
+ skel.setAttribute('aria-hidden', 'true');
+ for (let i = 0; i < 3; i++) skel.appendChild(el('span', 'war-board-skeleton-row'));
+ root.appendChild(skel);
+}
+
+function paintError(root, retry) {
+ root.textContent = '';
+ root.appendChild(heading('The league board is unreachable'));
+ root.appendChild(note('The battle ledger did not answer. Your record and rating are unaffected; this panel is only a view of them.'));
+ const btn = el('button', 'war-board-retry');
+ btn.type = 'button';
+ btn.textContent = 'Try the board again';
+ btn.addEventListener('click', () => { paintLoading(root); retry(); });
+ root.appendChild(btn);
+ root.appendChild(links());
+}
+
+function paint(root, data, coin) {
+ const live = (data.live || []).slice(0, LIVE_N);
+ const waiting = (data.queue?.waiting || []).slice(0, QUEUE_N);
+ const table = ladder(data.standings || [], data.standing, coin);
+
+ root.textContent = '';
+
+ if (live.length) {
+ root.appendChild(heading(live.length === 1 ? 'One war is running now' : `${live.length} wars are running now`));
+ const list = el('ul', 'war-board-list');
+ for (const m of live) list.appendChild(liveRow(m));
+ root.appendChild(list);
+ }
+
+ if (waiting.length) {
+ root.appendChild(heading(waiting.length === 1 ? 'One community is waiting for an opponent' : `${waiting.length} communities are waiting for an opponent`));
+ const list = el('ul', 'war-board-list');
+ for (const c of waiting) list.appendChild(queueRow(c));
+ root.appendChild(list);
+ } else if (data.queue && data.queue.available === false) {
+ root.appendChild(note('Matchmaking is offline right now, so no community can queue. Battles already running are unaffected.'));
+ }
+
+ if (table.length) {
+ root.appendChild(heading('Top of the ladder'));
+ const list = el('ul', 'war-board-list');
+ for (const row of table) list.appendChild(ladderRow(row, coin));
+ root.appendChild(list);
+ } else if (data.ledgerAvailable === false) {
+ root.appendChild(note('The battle ledger is unreachable, so the ladder cannot be shown. Wars still run and still report.'));
+ }
+
+ if (!live.length && !waiting.length && !table.length) {
+ root.appendChild(heading('The ladder is empty'));
+ root.appendChild(note('No community has fought a war yet. Walk into a coin world, find the war portal in the plaza, press E, and yours takes the first rung.'));
+ }
+
+ root.appendChild(links());
+}
+
+// ── rows ─────────────────────────────────────────────────────────────────────
+
+function liveRow(m) {
+ const li = el('li', 'war-board-row');
+ const a = link(coinWorldUrl(m.a, m.matchKey), 'war-board-link');
+ a.appendChild(avatar(m.a));
+ const main = el('span', 'war-board-main');
+ main.appendChild(text('span', 'war-board-title', `${label(m.a)} ${m.a?.score ?? 0} - ${m.b?.score ?? 0} ${label(m.b)}`));
+ main.appendChild(text('span', 'war-board-sub', liveSub(m)));
+ a.appendChild(main);
+ a.appendChild(text('span', 'war-board-tag war-board-tag-live', 'live'));
+ li.appendChild(a);
+ return li;
+}
+
+function liveSub(m) {
+ const fighters = (m.a?.fighters || 0) + (m.b?.fighters || 0);
+ const bodies = `${fighters} ${fighters === 1 ? 'fighter' : 'fighters'} on the field`;
+ if (m.phase === 'countdown') return `Starting: ${bodies}`;
+ if (m.phase === 'sudden_death') return `Sudden death: ${bodies}`;
+ if (m.phase === 'lobby') return `Waiting to start: ${bodies}`;
+ const left = Number(m.endsAt) - Date.now();
+ return left > 0 ? `${clock(left)} left, first to ${m.scoreCap || '?'}: ${bodies}` : bodies;
+}
+
+function queueRow(c) {
+ const li = el('li', 'war-board-row');
+ const a = link(coinWorldUrl(c, ''), 'war-board-link');
+ a.appendChild(avatar(c));
+ const main = el('span', 'war-board-main');
+ main.appendChild(text('span', 'war-board-title', label(c)));
+ main.appendChild(text('span', 'war-board-sub', `Queued ${ago(c.since)}: queue your coin and this is who you fight.`));
+ a.appendChild(main);
+ a.appendChild(text('span', 'war-board-tag', 'in queue'));
+ li.appendChild(a);
+ return li;
+}
+
+function ladderRow(row, coin) {
+ const li = el('li', 'war-board-row');
+ const a = link(coinWorldUrl(row, ''), 'war-board-link');
+ if (row.mint === coin) a.classList.add('is-yours');
+ a.appendChild(text('span', 'war-board-rank', `#${row.rank}`));
+ a.appendChild(avatar(row));
+ const main = el('span', 'war-board-main');
+ main.appendChild(text('span', 'war-board-title', label(row)));
+ main.appendChild(text('span', 'war-board-sub', record(row)));
+ a.appendChild(main);
+ a.appendChild(text('span', 'war-board-rating', String(row.rating ?? '')));
+ li.appendChild(a);
+ return li;
+}
+
+function record(row) {
+ const parts = [`${row.wins || 0}W ${row.losses || 0}L`];
+ if (row.draws) parts.push(`${row.draws}D`);
+ if (row.streak > 1) parts.push(`${row.streak} in a row`);
+ if (row.streak < -1) parts.push(`${-row.streak} straight losses`);
+ return parts.join(' · ');
+}
+
+// The top of the table, with this player's community pinned on when it ranks
+// below the cut: a board that never shows you your own row is a board you stop
+// reading.
+function ladder(standings, mine, coin) {
+ const ranked = standings.map((row, i) => ({ ...row, rank: i + 1 }));
+ const top = ranked.slice(0, TOP_N);
+ if (!coin || top.some((r) => r.mint === coin)) return top;
+ const own = ranked.find((r) => r.mint === coin);
+ if (own) return [...top, own];
+ if (mine) return [...top, { ...mine, rank: ranked.length + 1 }];
+ return top;
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+function links() {
+ const nav = el('p', 'war-board-links');
+ const docs = link('/docs/coin-wars', 'war-board-textlink');
+ docs.textContent = 'How Coin Wars works';
+ const play = link('/play', 'war-board-textlink');
+ play.textContent = 'Browse coin worlds';
+ nav.appendChild(docs);
+ nav.appendChild(play);
+ return nav;
+}
+
+// Always a same-origin /play link built from the coin's own identity, so the
+// world loads already dressed as that community and its portal board is one walk
+// away. `war` echoes a specific battle onto that board.
+function coinWorldUrl(c, matchKey) {
+ const q = new URLSearchParams({ coin: c?.mint || '' });
+ if (c?.name) q.set('name', String(c.name).slice(0, 48));
+ if (c?.symbol) q.set('symbol', String(c.symbol).slice(0, 16));
+ if (c?.image) q.set('image', String(c.image).slice(0, 400));
+ if (matchKey) q.set('war', String(matchKey).slice(0, 160));
+ return `/play?${q}`;
+}
+
+// Coin metadata is untrusted on-chain text: every value here lands through
+// textContent or a URLSearchParams-encoded query, never markup.
+function label(c) {
+ if (c?.symbol) return `$${String(c.symbol).slice(0, 16)}`;
+ if (c?.name) return String(c.name).slice(0, 24);
+ const mint = String(c?.mint || '');
+ return mint ? `${mint.slice(0, 4)}…${mint.slice(-4)}` : 'Community';
+}
+
+function avatar(c) {
+ const wrap = el('span', 'war-board-avatar');
+ const url = String(c?.image || '');
+ if (/^https?:\/\//i.test(url)) {
+ const img = document.createElement('img');
+ img.src = url;
+ img.alt = '';
+ img.loading = 'lazy';
+ img.decoding = 'async';
+ img.referrerPolicy = 'no-referrer';
+ // A dead metadata URL must leave the row intact, not a broken-image glyph.
+ img.addEventListener('error', () => { img.remove(); wrap.textContent = initial(c); }, { once: true });
+ wrap.appendChild(img);
+ } else {
+ wrap.textContent = initial(c);
+ }
+ wrap.setAttribute('aria-hidden', 'true');
+ return wrap;
+}
+
+function initial(c) {
+ const s = String(c?.symbol || c?.name || c?.mint || '?');
+ return s.slice(0, 1).toUpperCase();
+}
+
+function ago(since) {
+ const ms = Date.now() - (Number(since) || 0);
+ if (!Number.isFinite(ms) || ms < 0) return 'just now';
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ return `${Math.round(m / 60)}h ago`;
+}
+
+function clock(ms) {
+ const s = Math.max(0, Math.round((Number(ms) || 0) / 1000));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+}
+
+function el(tag, className) {
+ const node = document.createElement(tag);
+ if (className) node.className = className;
+ return node;
+}
+
+function text(tag, className, value) {
+ const node = el(tag, className);
+ node.textContent = value;
+ return node;
+}
+
+function heading(value) {
+ return text('h3', 'war-board-heading', value);
+}
+
+function note(value) {
+ return text('p', 'war-board-note', value);
+}
+
+function link(href, className) {
+ const a = el('a', className);
+ a.href = href;
+ return a;
+}
diff --git a/src/play/war.css b/src/play/war.css
index 5da4feb57..7668ddb96 100644
--- a/src/play/war.css
+++ b/src/play/war.css
@@ -56,6 +56,18 @@ button { font: inherit; color: inherit; cursor: pointer; }
background: radial-gradient(130% 100% at 50% 20%, transparent 55%, rgba(0, 0, 0, 0.6) 100%);
}
+.war-page-title {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ margin: -1px;
+ padding: 0;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ border: 0;
+}
+
#labels { position: fixed; inset: 0; z-index: 4; pointer-events: none; }
.war-tag {
@@ -302,6 +314,24 @@ button { font: inherit; color: inherit; cursor: pointer; }
.war-leave:hover { color: var(--war-ink); border-color: rgba(255, 255, 255, 0.24); }
.war-leave:focus-visible { outline: 2px solid var(--war-us); outline-offset: 2px; }
+.war-keys {
+ position: fixed;
+ left: 50%;
+ bottom: max(8px, calc(env(safe-area-inset-bottom) + 8px));
+ transform: translateX(-50%);
+ margin: 0;
+ color: var(--war-muted);
+ font: 600 11px/1 Inter, system-ui, sans-serif;
+ letter-spacing: 0.02em;
+ pointer-events: none;
+ opacity: 0.75;
+}
+
+/* A phone has the stick and no keyboard, and the hint would sit under the thumb. */
+@media (pointer: coarse), (max-width: 520px) {
+ .war-keys { display: none; }
+}
+
.war-downed {
position: fixed;
left: 50%;
@@ -329,10 +359,16 @@ button { font: inherit; color: inherit; cursor: pointer; }
padding: 20px;
background: rgba(4, 5, 8, 0.72);
backdrop-filter: blur(3px);
+ /* The body is overflow:hidden so the battlefield never scrolls. The card
+ carries the war room, which on a short phone is taller than the viewport,
+ so the scroll lives here. */
+ overflow-y: auto;
+ overscroll-behavior: contain;
}
.war-modal-card {
width: min(420px, 100%);
+ margin: auto;
padding: 26px 24px;
border: 1px solid var(--war-line);
border-radius: 18px;
@@ -371,6 +407,170 @@ button { font: inherit; color: inherit; cursor: pointer; }
.war-modal-btn:active { transform: scale(0.985); }
.war-modal-btn:focus-visible { outline: 2px solid var(--war-us); outline-offset: 3px; }
+/* ── the war room ────────────────────────────────────────────────────────── */
+
+/* Rendered into the fail card by src/play/war-board.js: live wars, the
+ * matchmaking queue, and the top of the Elo ladder, each row a link into that
+ * coin's world where the war portal stands. Left-aligned on purpose: the card
+ * above it centres a single message, a list of records is read down an edge. */
+
+.war-board {
+ margin-top: 18px;
+ padding-top: 16px;
+ border-top: 1px solid var(--war-line);
+ text-align: left;
+}
+
+.war-board-heading {
+ margin: 14px 0 8px;
+ color: var(--war-muted);
+ font: 700 10px/1.4 Inter, system-ui, sans-serif;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+}
+
+.war-board-heading:first-child { margin-top: 0; }
+
+.war-board-note {
+ margin: 0 0 8px;
+ color: var(--war-muted);
+ font-size: 12.5px;
+ line-height: 1.55;
+}
+
+.war-board-list { margin: 0; padding: 0; list-style: none; }
+.war-board-row { margin: 0 0 6px; }
+
+.war-board-link {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 10px;
+ border: 1px solid transparent;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.03);
+ color: var(--war-ink);
+ text-decoration: none;
+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard);
+}
+
+.war-board-link:hover { background: rgba(255, 255, 255, 0.07); border-color: var(--war-line); }
+.war-board-link:active { transform: scale(0.99); }
+.war-board-link:focus-visible { outline: 2px solid var(--war-us); outline-offset: 2px; }
+.war-board-link.is-yours { border-color: color-mix(in srgb, var(--war-us) 45%, var(--war-line)); background: rgba(127, 216, 255, 0.08); }
+
+.war-board-rank {
+ flex: none;
+ min-width: 24px;
+ color: var(--war-muted);
+ font: 700 11px/1 var(--war-mono);
+}
+
+.war-board-avatar {
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ overflow: hidden;
+ border: 1px solid var(--war-line);
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--war-muted);
+ font: 700 11px/1 Inter, system-ui, sans-serif;
+}
+
+.war-board-avatar img { width: 100%; height: 100%; object-fit: cover; }
+
+.war-board-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1 1 auto; }
+
+.war-board-title {
+ overflow: hidden;
+ font: 700 13px/1.3 Inter, system-ui, sans-serif;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.war-board-sub {
+ overflow: hidden;
+ color: var(--war-muted);
+ font-size: 11.5px;
+ line-height: 1.4;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.war-board-tag {
+ flex: none;
+ padding: 3px 8px;
+ border: 1px solid var(--war-line);
+ border-radius: 999px;
+ color: var(--war-muted);
+ font: 700 9.5px/1.3 Inter, system-ui, sans-serif;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.war-board-tag-live {
+ border-color: color-mix(in srgb, var(--war-win) 50%, var(--war-line));
+ color: var(--war-win);
+}
+
+.war-board-rating { flex: none; font: 800 15px/1 var(--war-mono); }
+
+.war-board-skeleton { display: flex; flex-direction: column; gap: 6px; }
+
+.war-board-skeleton-row {
+ height: 42px;
+ border-radius: 10px;
+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.09), rgba(255, 255, 255, 0.04));
+ background-size: 300% 100%;
+ animation: war-shimmer 1.4s linear infinite;
+}
+
+@keyframes war-shimmer {
+ from { background-position: 100% 0; }
+ to { background-position: -100% 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .war-board-skeleton-row { animation: none; }
+}
+
+.war-board-retry {
+ width: 100%;
+ margin: 4px 0 2px;
+ padding: 9px 14px;
+ border: 1px solid var(--war-line);
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--war-ink);
+ font: 700 13px/1 Inter, system-ui, sans-serif;
+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+
+.war-board-retry:hover { background: rgba(255, 255, 255, 0.09); border-color: rgba(255, 255, 255, 0.24); }
+.war-board-retry:focus-visible { outline: 2px solid var(--war-us); outline-offset: 2px; }
+
+.war-board-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px 16px;
+ margin: 16px 0 0;
+}
+
+.war-board-textlink {
+ color: var(--war-us);
+ font: 600 12px/1.4 Inter, system-ui, sans-serif;
+ text-decoration: none;
+ border-bottom: 1px solid transparent;
+ transition: border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
+}
+
+.war-board-textlink:hover { border-bottom-color: currentColor; }
+.war-board-textlink:focus-visible { outline: 2px solid var(--war-us); outline-offset: 3px; border-radius: 3px; }
+
/* ── small screens ───────────────────────────────────────────────────────── */
@media (max-width: 520px) {
@@ -379,4 +579,11 @@ button { font: inherit; color: inherit; cursor: pointer; }
.war-side-name { font-size: 12px; }
.war-stick { width: 100px; height: 100px; }
.war-attack { width: 92px; padding: 12px 0; }
+ .war-modal { padding: 14px 12px; }
+ .war-modal-card { padding: 22px 16px; }
+ .war-result-title, .war-fail-title { font-size: 26px; }
+ .war-board-link { gap: 8px; padding: 8px; }
+ .war-board-avatar { width: 22px; height: 22px; }
+ .war-board-title { font-size: 12.5px; }
+ .war-board-tag { padding: 3px 6px; letter-spacing: 0.05em; }
}
diff --git a/src/play/war.js b/src/play/war.js
index dd97773c6..38c358eb7 100644
--- a/src/play/war.js
+++ b/src/play/war.js
@@ -22,6 +22,7 @@ import { ensurePlayAccess } from '../game/play-gate.js';
import { requestHolderPass } from '../community/town-auth.js';
import { createLogger } from '../shared/log.js';
import { WarWorld } from './war-world.js';
+import { mountWarBoard } from './war-board.js';
import './war.css';
const log = createLogger('war');
@@ -64,6 +65,7 @@ let sendTimer = 0;
let clockTimer = 0;
let lastSent = { x: NaN, z: NaN, yaw: NaN, motion: '' };
let attackCooldownUntil = 0;
+let board = null;
// ── boot ─────────────────────────────────────────────────────────────────────
@@ -123,16 +125,16 @@ let attackCooldownUntil = 0;
}
holderPass = res.holderPass;
} catch (err) {
- const msg = err?.code === 'auth_required'
- ? 'Sign in on the coin world first, then walk back to the war portal.'
- : err?.code === 'wallet_required'
- ? 'Link a Solana wallet on the coin world, then walk back to the war portal.'
- : err?.message || 'Your holding could not be verified right now.';
- return fail('Could not verify your holding', msg, 'Back to the world');
+ return fail('Could not verify your holding', holderErrorText(err), 'Back to the world');
}
}
setStatus('Joining the battle…');
+ // Both gates have passed, so the body WILL be read: start it now and let the
+ // download run under the websocket handshake and the room's join. Doing this
+ // from the head instead orphaned the fetch on every failed join, which is
+ // what the browser reports as "preloaded but not used".
+ warmAvatar(savedAvatar());
try {
const client = new Client(serverUrl);
room = await joinRoomWithTimeout(client, ROOM, {
@@ -366,6 +368,7 @@ function showResult(m) {
$('result').hidden = false;
$('controls').hidden = true;
world?.setLocked(true);
+ focusCard('result-back');
// The league write happens as the room ends, so the world we return to can
// read this battle straight out of the ledger.
$('result-back').textContent = `Back to ${coinLabel()}`;
@@ -390,8 +393,13 @@ function wireChrome() {
addEventListener('keydown', (e) => {
if (e.repeat) return;
const k = e.key.toLowerCase();
- if (k === ' ' || k === 'f') { e.preventDefault(); attack(); }
- if (k === 'escape' && !$('result').hidden) goBack();
+ // Space is the fire key AND the key that presses a focused button. Taking
+ // it unconditionally meant a keyboard player on the result card could not
+ // activate "Back to the world" at all.
+ const onControl = e.target instanceof Element
+ && e.target.closest('button, a, input, select, textarea, [contenteditable]');
+ if (!onControl && (k === ' ' || k === 'f')) { e.preventDefault(); attack(); }
+ if (k === 'escape' && (!$('result').hidden || !$('fail').hidden)) goBack();
});
mountJoystick();
// The coin the player fights for, painted into the page chrome the moment it
@@ -458,6 +466,25 @@ function fail(title, detail, action = 'Back to the world') {
$('fail').hidden = false;
clearInterval(sendTimer);
clearInterval(clockTimer);
+ // A dead end is where a player most needs somewhere to go: the war room
+ // answers "then where IS a battle" with live league state, and every row is a
+ // door into the world whose portal can start one.
+ board?.dispose();
+ board = mountWarBoard($('fail-board'), { network: cfg.network, coin: cfg.coin });
+ focusCard('fail-back');
+}
+
+// A modal that opens without moving focus leaves a keyboard player tabbing
+// through a battlefield they can no longer act on.
+function focusCard(id) {
+ requestAnimationFrame(() => $(id)?.focus());
+}
+
+// Warm a GLB into the HTTP cache. three's FileLoader requests in CORS mode, so
+// this must too or the browser keeps two separate entries and downloads twice.
+function warmAvatar(url) {
+ if (!url) return;
+ fetch(url, { mode: 'cors', credentials: 'omit' }).catch(() => { /* the loader will retry it for real */ });
}
// The room throws named errors; each one has a player-readable cause.
@@ -473,6 +500,30 @@ function joinErrorText(err) {
return msg || 'The arena refused the join.';
}
+// The holder gate answers with a coded error; each one is a different thing the
+// player has to do. The raw upstream string is never shown: "CoinCommunities is
+// not configured" names an internal service and tells a player nothing.
+function holderErrorText(err) {
+ switch (err?.code) {
+ case 'auth_required':
+ return 'Sign in on the coin world first, then walk back to the war portal.';
+ case 'wallet_required':
+ return 'Link a Solana wallet on the coin world, then walk back to the war portal.';
+ case 'cc_unconfigured':
+ return 'Holder verification is offline on this deployment, so the arena cannot seat you. Nothing is wrong with your wallet or your standing in the league.';
+ case 'balance_unavailable':
+ return 'Your on-chain balance could not be read just now, so the arena cannot confirm you hold the coin. Try again in a moment.';
+ case 'upstream_error':
+ return 'The account service did not answer, so your holding could not be checked. Try again in a moment.';
+ case 'rate_limited':
+ return 'Too many checks from this connection. Wait a few seconds and queue again from the portal.';
+ default:
+ break;
+ }
+ if (err?.status >= 500) return 'The holder gate is having trouble right now. Try again in a moment.';
+ return 'Your holding could not be verified right now. Queue again from the war portal and it will be rechecked.';
+}
+
function factionLabel(s, side) {
const symbol = side === 'a' ? s.aSymbol : s.bSymbol;
const name = side === 'a' ? s.aName : s.bName;
diff --git a/tests/war-board.test.js b/tests/war-board.test.js
new file mode 100644
index 000000000..b35ac3eba
--- /dev/null
+++ b/tests/war-board.test.js
@@ -0,0 +1,191 @@
+// @vitest-environment jsdom
+//
+// The war room on the Coin Wars arena's terminal cards (src/play/war-board.js).
+//
+// /play/war is only ever reached with a signed pairing from a coin world's war
+// portal, so every other arrival lands on a dead end. The property under test is
+// that the dead end is never blank: whatever /api/wars answers with (live
+// battles, a queue, a ladder, an empty ledger, or nothing at all), the card ends
+// in a designed state and in a link into a world where a war can be started.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mountWarBoard } from '../src/play/war-board.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const RIVAL_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+let host = null;
+let handle = null;
+
+function respond(data, { ok = true, status = 200 } = {}) {
+ global.fetch = vi.fn(async () => ({
+ ok,
+ status,
+ json: async () => (ok ? { data } : { error: 'server_error', error_description: 'ledger down' }),
+ }));
+}
+
+function mount(opts = {}) {
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ handle = mountWarBoard(host, opts);
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const board = () => host.querySelector('.war-board');
+const rows = () => [...host.querySelectorAll('.war-board-link')];
+const textOf = () => board().textContent;
+
+beforeEach(() => {
+ vi.useRealTimers();
+});
+
+afterEach(() => {
+ handle?.dispose();
+ handle = null;
+ host?.remove();
+ host = null;
+ vi.restoreAllMocks();
+});
+
+describe('the war room', () => {
+ it('paints a loading state before the first answer lands', async () => {
+ let release;
+ global.fetch = vi.fn(() => new Promise((r) => { release = r; }));
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ handle = mountWarBoard(host, {});
+
+ expect(board().querySelectorAll('.war-board-skeleton-row').length).toBe(3);
+ expect(textOf()).toContain('Reading the league');
+ release({ ok: true, status: 200, json: async () => ({ data: {} }) });
+ });
+
+ it('tells a player where to start when the ledger is empty', async () => {
+ respond({ live: [], queue: { available: true, waiting: [] }, standings: [], ledgerAvailable: true });
+ await mount({});
+
+ expect(textOf()).toContain('The ladder is empty');
+ expect(textOf()).toContain('war portal');
+ // An empty state that offers no door is a dead end with extra words.
+ expect(rows().length).toBe(0);
+ const hrefs = [...board().querySelectorAll('a')].map((a) => a.getAttribute('href'));
+ expect(hrefs).toContain('/docs/coin-wars');
+ expect(hrefs).toContain('/play');
+ });
+
+ it('renders a live battle as a link into that coin world, carrying the match key', async () => {
+ respond({
+ live: [{
+ matchKey: 'm-42',
+ phase: 'live',
+ scoreCap: 15,
+ endsAt: Date.now() + 90_000,
+ a: { mint: THREE_MINT, name: 'three', symbol: 'THREE', score: 7, fighters: 3 },
+ b: { mint: RIVAL_MINT, name: 'Synthetic', symbol: 'SYN', score: 4, fighters: 2 },
+ }],
+ queue: { available: true, waiting: [] },
+ standings: [],
+ ledgerAvailable: true,
+ });
+ await mount({});
+
+ expect(textOf()).toContain('One war is running now');
+ expect(textOf()).toContain('$THREE 7 - 4 $SYN');
+ expect(textOf()).toContain('5 fighters on the field');
+
+ const href = rows()[0].getAttribute('href');
+ expect(href.startsWith('/play?')).toBe(true);
+ const q = new URLSearchParams(href.slice('/play?'.length));
+ expect(q.get('coin')).toBe(THREE_MINT);
+ expect(q.get('symbol')).toBe('THREE');
+ expect(q.get('war')).toBe('m-42');
+ });
+
+ it('reads a queued community as an invitation, not a status line', async () => {
+ respond({
+ live: [],
+ queue: { available: true, waiting: [{ mint: RIVAL_MINT, symbol: 'SYN', since: Date.now() - 90_000 }] },
+ standings: [],
+ ledgerAvailable: true,
+ });
+ await mount({});
+
+ expect(textOf()).toContain('One community is waiting for an opponent');
+ expect(textOf()).toContain('2m ago');
+ expect(rows()[0].getAttribute('href')).toContain(`coin=${RIVAL_MINT}`);
+ });
+
+ it('says so when matchmaking is offline rather than reading as "nobody wants to fight"', async () => {
+ respond({ live: [], queue: { available: false, waiting: [] }, standings: [], ledgerAvailable: true });
+ await mount({});
+ expect(textOf()).toContain('Matchmaking is offline');
+ });
+
+ it('ranks the ladder and pins the player\'s own community when it falls below the cut', async () => {
+ const standings = [];
+ for (let i = 0; i < 6; i++) {
+ standings.push({
+ mint: `SYNTHETICmint${i}1111111111111111111111`,
+ symbol: `S${i}`,
+ rating: 1200 - i * 10,
+ wins: 6 - i, losses: i, draws: 0, streak: 0,
+ });
+ }
+ standings.push({ mint: THREE_MINT, symbol: 'THREE', rating: 990, wins: 1, losses: 4, draws: 1, streak: -3 });
+ respond({ live: [], queue: { available: true, waiting: [] }, standings, ledgerAvailable: true });
+ await mount({ coin: THREE_MINT });
+
+ const labels = rows().map((r) => r.textContent);
+ expect(labels.length).toBe(6); // the top five, plus the pinned row
+ expect(labels[0]).toContain('#1');
+ expect(labels[5]).toContain('$THREE');
+ expect(labels[5]).toContain('#7');
+ expect(labels[5]).toContain('3 straight losses');
+ expect(rows()[5].classList.contains('is-yours')).toBe(true);
+ });
+
+ it('offers a retry, not a blank panel, when the board read fails', async () => {
+ respond(null, { ok: false, status: 500 });
+ await mount({});
+
+ expect(textOf()).toContain('The league board is unreachable');
+ const retry = board().querySelector('.war-board-retry');
+ expect(retry).toBeTruthy();
+
+ respond({ live: [], queue: { available: true, waiting: [] }, standings: [], ledgerAvailable: true });
+ retry.click();
+ await new Promise((r) => setTimeout(r, 0));
+ expect(textOf()).toContain('The ladder is empty');
+ });
+
+ it('says the ladder is unreadable rather than showing an empty one', async () => {
+ respond({ live: [], queue: { available: true, waiting: [] }, standings: [], ledgerAvailable: false });
+ await mount({});
+ expect(textOf()).toContain('The battle ledger is unreachable');
+ });
+
+ it('renders a hostile coin name as text, never as markup', async () => {
+ respond({
+ live: [],
+ queue: { available: true, waiting: [{ mint: RIVAL_MINT, name: '<img src=x onerror=alert(1)>', since: Date.now() }] },
+ standings: [],
+ ledgerAvailable: true,
+ });
+ await mount({});
+
+ expect(host.querySelector('img[src="x"]')).toBeNull();
+ // Rendered through textContent, and clipped to the label budget like any
+ // other community name.
+ expect(board().querySelector('.war-board-title').textContent).toBe('<img src=x onerror=alert');
+ });
+
+ it('stops polling and leaves no node behind once disposed', async () => {
+ respond({ live: [], queue: { available: true, waiting: [] }, standings: [], ledgerAvailable: true });
+ await mount({});
+ expect(board()).toBeTruthy();
+ handle.dispose();
+ handle = null;
+ expect(host.querySelector('.war-board')).toBeNull();
+ });
+});