diff --git a/package.json b/package.json index cca62f3..ce51105 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "build": "node scripts/build.mjs", "test": "node --test test/*.test.js", "dev": "node scripts/dev.mjs", - "test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs", + "test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs && node test/effects-browser.mjs", "check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser", "test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs", "test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs && node test/tutorial-errors-browser.mjs" diff --git a/scripts/publish-beta.mjs b/scripts/publish-beta.mjs index 8c00f0e..cac025b 100644 --- a/scripts/publish-beta.mjs +++ b/scripts/publish-beta.mjs @@ -68,6 +68,12 @@ const defaults = { default: false, }, { name: "sound", label: "Game sounds", type: "checkbox", default: true }, + { + name: "animations", + label: "Animations", + type: "checkbox", + default: true, + }, { name: "language", label: "Language", @@ -117,6 +123,17 @@ const files = await uploadViewerFiles( const viewer = { url: files.url }, style = { url: files.stylesheets[0] }; const patch = { + preferences: [ + ...(existing?.preferences ?? defaults.preferences).filter( + (preference) => preference.name !== "animations", + ), + existing?.preferences?.find( + (preference) => preference.name === "animations", + ) ?? + defaults.preferences.find( + (preference) => preference.name === "animations", + ), + ], settings: [ ...(existing?.settings ?? []).filter( (setting) => setting.name !== "autoRetrieve", @@ -149,7 +166,7 @@ const patch = { }, }; if (existing) { - for (const field of ["settings", "tutorial"]) + for (const field of ["settings", "tutorial", "preferences"]) if (JSON.stringify(patch[field]) === JSON.stringify(existing[field])) delete patch[field]; } @@ -173,7 +190,14 @@ assert.equal(published.public, live); if (existing) { for (const [field, value] of Object.entries(existing)) if ( - !["engine", "viewer", "settings", "tutorial", "updatedAt"].includes(field) + ![ + "engine", + "viewer", + "settings", + "tutorial", + "preferences", + "updatedAt", + ].includes(field) ) assert.deepEqual( published[field], diff --git a/test/effects-browser.mjs b/test/effects-browser.mjs new file mode 100644 index 0000000..0526b28 --- /dev/null +++ b/test/effects-browser.mjs @@ -0,0 +1,359 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { createServer } from "node:http"; +import { readFile, mkdir } from "node:fs/promises"; +import { resolve, extname } from "node:path"; +import * as E from "../engine/index.js"; + +const dist = resolve("dist"); +const server = createServer(async (req, res) => { + try { + const pathname = new URL(req.url, "http://localhost").pathname; + if (pathname === "/sound-test.js") { + res.setHeader("Content-Type", "text/javascript; charset=utf-8"); + res.end(await readFile("viewer/sound.js")); + return; + } + if (pathname === "/") { + res.setHeader("Content-Type", "text/html"); + res.end( + '
', + ); + return; + } + const path = resolve(dist, "." + pathname); + if (!path.startsWith(dist + "/")) throw Error("Invalid path"); + res.setHeader( + "Content-Type", + { + ".js": "text/javascript", + ".css": "text/css", + ".json": "application/json", + ".webp": "image/webp", + }[extname(path)] ?? "application/octet-stream", + ); + res.end(await readFile(path)); + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +const browser = await chromium.launch(); +await mkdir(".local/qa", { recursive: true }); +function fixture() { + const s = E.init(3, [], {}, "action-feedback"); + s.phase = "actions"; + s.actor = s.first = 0; + s.players[0].boat = "1,0"; + s.players[0].money = 7; + s.players[0].fish = [1]; + s.players[0].character = null; + for (const a of E.ACTIONS) s.players[0].markers[a] = 1; + s.players[1].markers.rest = 1; + s.players[2].markers.rest = 1; + s.board["0,0"].huts = [0]; + s.demands[0] = { + id: 10, + goods: ["kava", "copra", "beef"], + filled: [true, true, false], + }; + return s; +} +try { + for (const width of [390, 1440]) { + const p = await browser.newPage({ + viewport: { width, height: 1000 }, + isMobile: width < 700, + hasTouch: width < 700, + }); + const errors = []; + p.on("pageerror", (e) => { + errors.push(e.message); + console.error(e.message); + }); + await p.addInitScript(() => { + window.played = 0; + const Native = window.AudioContext; + window.AudioContext = class extends Native { + constructor() { + super(); + for (const name of ["createOscillator", "createBufferSource"]) { + const create = this[name].bind(this); + this[name] = () => { + const source = create(); + const start = source.start.bind(source); + source.start = (...args) => { + window.played++; + return start(...args); + }; + return source; + }; + } + } + }; + }); + await p.goto(`http://127.0.0.1:${server.address().port}/`); + if (width === 1440) { + const samples = await p.evaluate(async () => { + const { createMoveSound } = await import("/sound-test.js"); + const result = {}; + for (const kind of [ + "marker", + "sail", + "fish", + "draw", + "build", + "sell", + "buy", + "complete", + "explore", + "rest", + "tourist", + "discard", + ]) { + const offline = new OfflineAudioContext(1, 24000, 24000); + const proxy = new Proxy(offline, { + get(target, name) { + if (name === "state") return "running"; + const value = target[name]; + return typeof value === "function" ? value.bind(target) : value; + }, + }); + const audio = createMoveSound(() => proxy); + audio.setEnabled(true); + audio.unlock(); + await audio.play(kind); + const buffer = await offline.startRendering(); + const data = buffer.getChannelData(0); + result[kind] = { + peak: Math.max(...data.map(Math.abs)), + energy: data.reduce((sum, n) => sum + n * n, 0), + }; + } + return result; + }); + for (const [kind, { peak, energy }] of Object.entries(samples)) { + assert.ok(peak < 0.1, `${kind}: soft volume without clipping`); + assert.ok(energy > 0.001, `${kind}: audio actually renders`); + } + } + await p.evaluate(() => { + window.host = vanuatu.launch("#game"); + host.emit("player", { index: 0 }); + host.emit("preferences", { locale: "fr", sound: true }); + window.settle = () => + new Promise((r) => + requestAnimationFrame(() => requestAnimationFrame(r)), + ); + }); + const emit = async (state) => { + await p.evaluate( + async (state) => { + host.emit("state", state); + await settle(); + }, + E.stripSecret(state, 0), + ); + }; + let s = fixture(); + await emit(s); + assert.equal( + await p.locator(".action-effect").count(), + 0, + "Initial load is still", + ); + await p.locator(".brand").click(); + await p.waitForTimeout(100); + const sail = E.availableMoves(s, 0).find( + (m) => + m.action === "sail" && + m.path.length === 2 && + m.path.at(-1) !== s.players[0].boat, + ); + assert.ok(sail); + const sailed = E.move(s, sail, 0); + await emit(sailed); + await p.locator(".effect-piece").waitFor(); + const progress = await p.evaluate(() => { + const piece = document.querySelector(".effect-piece"); + const animation = piece.getAnimations()[0]; + animation.pause(); + animation.currentTime = animation.effect.getTiming().duration / 2; + const frames = animation.effect.getKeyframes(); + return { + frames: frames.length, + first: frames[0].transform, + last: frames.at(-1).transform, + pointerEvents: getComputedStyle(piece).pointerEvents, + }; + }); + assert.equal(progress.frames, 3, "Boat follows the intermediate space"); + assert.notEqual(progress.first, progress.last); + assert.equal(progress.pointerEvents, "none"); + assert.equal( + await p + .locator('[data-boat="0"]') + .evaluate((el) => getComputedStyle(el).opacity), + "0", + ); + await p.screenshot({ path: `.local/qa/feedback-sail-${width}.png` }); + assert.ok(await p.evaluate(() => window.played >= 2)); + // Scrolling cancels the overlay immediately and restores the real boat. + await p.evaluate(() => document.dispatchEvent(new Event("scroll"))); + assert.equal(await p.locator(".action-effect").count(), 0); + assert.equal( + await p + .locator('[data-boat="0"]') + .evaluate((el) => getComputedStyle(el).opacity), + "1", + ); + + await emit(s); + const sold = E.move( + s, + E.availableMoves(s, 0).find((m) => m.action === "sell"), + 0, + ); + await emit(sold); + await p.locator(".effect-reward").first().waitFor(); + const amounts = await p.locator(".effect-reward").allTextContents(); + assert.ok( + amounts.some((t) => t.includes("+3")), + "Show gross income, not the net money drop", + ); + assert.ok( + amounts.some((t) => t.includes("10") && t.includes("+5")), + "Show automatic prosperity conversion", + ); + await p.waitForTimeout(650); + await p.screenshot({ path: `.local/qa/feedback-sale-${width}.png` }); + await p.waitForTimeout(1700); + assert.equal( + await p.locator(".action-effect").count(), + 0, + "Effects clean themselves up", + ); + const audioCount = await p.evaluate(() => window.played); + await emit(sold); + assert.equal(await p.locator(".action-effect").count(), 0); + assert.equal( + await p.evaluate(() => window.played), + audioCount, + "Duplicate states are silent", + ); + + for (const action of ["build", "draw", "buy"]) { + await emit(s); + const move = E.availableMoves(s, 0).find( + (m) => m.action === action && (action !== "buy" || m.good === "beef"), + ); + assert.ok(move, action); + await emit(E.move(s, move, 0)); + assert.ok( + await p + .locator(action === "buy" ? ".effect-piece" : ".effect-stamp") + .count(), + `${action}: feedback is attached to the action`, + ); + if (action === "buy") { + assert.ok( + (await p.locator(".effect-reward").allTextContents()).some((text) => + text.includes("+7"), + ), + ); + } + } + const planning = fixture(); + planning.phase = "plan"; + for (const player of planning.players) + for (const action of E.ACTIONS) player.markers[action] = 0; + await emit(planning); + await emit( + E.move( + planning, + E.availableMoves(planning, 0).find((m) => m.type === "plan"), + 0, + ), + ); + assert.ok( + await p + .locator("[data-marker-player='0']") + .evaluateAll((nodes) => + nodes.some((node) => node.getAnimations().length), + ), + "Placed markers have a short landing animation", + ); + + await p.emulateMedia({ reducedMotion: "reduce" }); + await emit(s); + await emit(sailed); + assert.equal( + await p.locator(".action-effect").count(), + 0, + "Reduced motion suppresses overlays", + ); + await p.emulateMedia({ reducedMotion: "no-preference" }); + await p.evaluate(() => + host.emit("preferences", { + locale: "fr", + sound: false, + animations: false, + }), + ); + await emit(s); + const mutedAt = await p.evaluate(() => window.played); + await emit(sailed); + assert.equal(await p.locator(".action-effect").count(), 0); + assert.equal( + await p.evaluate(() => window.played), + mutedAt, + "Muted incoming moves are silent", + ); + await p.locator("[data-help]").first().click(); + assert.equal( + await p.locator('[data-pref="animations"]').isChecked(), + false, + ); + await p.locator('[data-pref="animations"]').check(); + await p.locator("dialog [data-close]").click(); + await emit(s); + await emit(sailed); + assert.ok(await p.locator(".action-effect").count()); + await p.evaluate(() => host.emit("replay:start")); + assert.equal(await p.locator(".action-effect").count(), 0); + await p.evaluate( + async (states) => { + for (let i = 0; i < states.length; i++) { + host.emit("replay:to", i + 1); + host.emit("gamelog", { start: i, data: { frames: [states[i]] } }); + await settle(); + } + }, + [E.stripSecret(s, 0), E.stripSecret(sailed, 0)], + ); + assert.equal( + await p.locator(".action-effect").count(), + 0, + "Forward replay does not animate", + ); + await p.evaluate(async () => { + host.emit("replay:end"); + await settle(); + }); + assert.equal(await p.locator(".action-effect").count(), 0); + assert.ok( + await p.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ); + assert.deepEqual(errors, []); + await p.close(); + console.log( + `${width}: route animation, accurate rewards, sound gating, cleanup, reduced motion and replay passed`, + ); + } +} finally { + await browser.close(); + server.close(); +} diff --git a/test/effects.test.js b/test/effects.test.js new file mode 100644 index 0000000..1a3ce44 --- /dev/null +++ b/test/effects.test.js @@ -0,0 +1,73 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { liveEvents, rewards, soundFor } from "../viewer/effects.js"; + +test("live feedback ignores initial load, duplicates, undo, catch-up and replaced histories", () => { + const start = { type: "start", p: 0 }; + const event = { type: "action", action: "sail", p: 0 }; + const before = { historyLength: 1, events: [start] }; + const after = { historyLength: 2, events: [start, event] }; + assert.deepEqual(liveEvents(before, after), [event]); + for (const [a, b] of [ + [null, after], + [after, after], + [after, before], + [before, { ...after, historyLength: 4 }], + [before, { ...after, events: [{ type: "start", p: 1 }, event] }], + ]) + assert.deepEqual(liveEvents(a, b), []); +}); + +test("rewards show gross sale income separately from automatic conversion", () => { + const sale = { + type: "action", + action: "sell", + details: { income: 6, price: 3 }, + }; + assert.deepEqual(rewards(sale), [{ icon: "coin", value: 6 }]); + assert.deepEqual(rewards({ type: "conversion", points: 5 }), []); + assert.deepEqual( + rewards({ type: "action", action: "buy", details: { cost: 3, points: 7 } }), + [ + { icon: "coin", value: -3 }, + { icon: "point", value: 7 }, + ], + ); + assert.deepEqual(rewards({ type: "beg", amount: 3 }), [ + { icon: "point", value: -3 }, + { icon: "coin", value: 3 }, + ]); + assert.deepEqual( + rewards({ type: "action", action: "fish", details: { fish: 2 } }), + [{ icon: "fish", value: 2 }], + ); + assert.deepEqual(rewards({ type: "action", action: "sell" }), []); +}); + +test("sound follows the actual action and distinguishes a completed ship", () => { + assert.equal( + soundFor([ + { + type: "action", + action: "buy", + details: { shipments: [{ complete: true }] }, + }, + ]), + "complete", + ); + assert.equal( + soundFor([ + { + type: "action", + action: "buy", + details: { shipments: [{ complete: false }] }, + }, + ]), + "buy", + ); + assert.equal( + soundFor([{ type: "action", action: "sail" }, { type: "discard" }]), + "sail", + ); + assert.equal(soundFor([{ type: "round" }]), null); +}); diff --git a/test/sound.test.js b/test/sound.test.js index a6ff8a3..773c5bf 100644 --- a/test/sound.test.js +++ b/test/sound.test.js @@ -3,10 +3,11 @@ import assert from "node:assert/strict"; import { createMoveSound } from "../viewer/sound.js"; function audioFixture() { - const counts = { created: 0, played: 0, stopped: 0, closed: 0 }; + const counts = { created: 0, played: 0, stopped: 0, closed: 0, buffers: 0 }; const context = { state: "suspended", currentTime: 0, + sampleRate: 8000, destination: {}, async resume() { this.state = "running"; @@ -24,7 +25,7 @@ function audioFixture() { }, createOscillator() { return { - frequency: {}, + frequency: { setValueAtTime() {}, exponentialRampToValueAtTime() {} }, connect(gain) { return gain; }, @@ -40,6 +41,16 @@ function audioFixture() { }, }; }, + createBuffer(channels, length) { + counts.buffers++; + return { getChannelData: () => new Float32Array(length) }; + }, + createBufferSource() { + return this.createOscillator(); + }, + createBiquadFilter() { + return { frequency: {}, connect: (node) => node, disconnect() {} }; + }, }; const audio = createMoveSound(() => { counts.created++; @@ -117,3 +128,39 @@ test("unavailable browser audio does not interrupt play", async () => { await audio.play(); audio.destroy(); }); + +test("material cues reuse noise and replace fast overlapping sounds", async () => { + const { audio, counts } = audioFixture(); + audio.setEnabled(true); + audio.unlock(); + await audio.play("sail"); + assert.equal(counts.played, 2); + await audio.play("draw"); + assert.equal(counts.buffers, 1); + assert.equal(counts.stopped, 2); + await audio.play("complete"); + assert.equal(counts.played, 7); + audio.setEnabled(false); + assert.equal(counts.stopped, 7); + audio.destroy(); +}); + +test("cancelling effects also cancels a sound still waiting for audio unlock", async () => { + const { audio, counts, context } = audioFixture(); + let resume; + context.resume = () => + new Promise((resolve) => { + resume = () => { + context.state = "running"; + resolve(); + }; + }); + audio.setEnabled(true); + audio.unlock(); + const pending = audio.play("sail"); + audio.stop(); + resume(); + await pending; + assert.equal(counts.played, 0); + audio.destroy(); +}); diff --git a/viewer/board.js b/viewer/board.js index f547526..81716d5 100644 --- a/viewer/board.js +++ b/viewer/board.js @@ -212,7 +212,7 @@ export function boardSvg( const x = c.x + ((i % 3) - (rowSize - 1) / 2) * 39, y = c.y + (boats.length > 3 ? row * 32 : 11); const help = `${"Boat"} · ${p.name}`; - svg += `${esc(help)}${svgIcon("sail", 0, 0, 48, p.color, help)}${colorBlind ? `${symbols[pi]}` : ""}`; + svg += `${esc(help)}${svgIcon("sail", 0, 0, 48, p.color, help)}${colorBlind ? `${symbols[pi]}` : ""}`; } svg += ""; } diff --git a/viewer/effects.js b/viewer/effects.js new file mode 100644 index 0000000..efb5baf --- /dev/null +++ b/viewer/effects.js @@ -0,0 +1,396 @@ +// Only adjacent live states qualify. Loading, undoing, replaying and catching up +// must never celebrate old moves, or invent gains from a net balance change. +export function liveEvents(before, after) { + if (!before || after.historyLength !== before.historyLength + 1) return []; + const previous = before.events ?? []; + const events = after.events ?? []; + if (events.length <= previous.length) return []; + if ( + previous.length && + JSON.stringify(previous.at(-1)) !== + JSON.stringify(events[previous.length - 1]) + ) + return []; + return events.slice(previous.length); +} + +export function rewards(event) { + const d = event.details ?? {}; + const result = []; + const add = (icon, value) => { + if (Number.isFinite(value) && value !== 0) result.push({ icon, value }); + }; + if (event.type === "action") { + add("coin", -d.cost); + add("coin", d.income); + add("point", d.points); + add("fish", d.fish); + add("explore", d.treasure); + } else if (event.type === "treasure") { + add( + "coin", + event.values?.reduce((a, b) => a + b, 0), + ); + } else if (event.type === "beg") { + add("point", -event.amount); + add("coin", event.amount); + } + return result; +} + +export function soundFor(events) { + const event = events.find((e) => + [ + "action", + "plan", + "neutral", + "place", + "treasure", + "beg", + "discard", + "character", + "rest", + "governor", + ].includes(e.type), + ); + if (!event) return null; + if (event.details?.shipments?.some((s) => s.complete)) return "complete"; + if (event.type === "action") return event.action; + return ( + { + plan: "marker", + neutral: "marker", + place: "build", + treasure: "sell", + beg: "sell", + governor: "marker", + character: "marker", + }[event.type] ?? event.type + ); +} + +export function createEffects(root, { icon, sound, center }) { + const doc = root.ownerDocument; + const view = doc.defaultView; + const motion = view.matchMedia("(prefers-reduced-motion: reduce)"); + const layer = doc.createElement("div"); + layer.className = "action-effects"; + layer.setAttribute("aria-hidden", "true"); + layer.setAttribute("translate", "no"); + root.append(layer); + const animations = new Set(); + let frame = 0, + enabled = true; + const allowed = () => enabled && !motion.matches && !doc.hidden; + const query = (selector) => root.querySelector(selector); + const point = (element) => { + if (!element) return null; + const r = element.getBoundingClientRect(); + if ( + !r.width || + !r.height || + r.bottom <= 0 || + r.top >= view.innerHeight || + r.right <= 0 || + r.left >= view.innerWidth + ) + return null; + const map = element.closest(".map-scroll"); + if (map) { + const clip = map.getBoundingClientRect(); + if ( + r.right < clip.left || + r.left > clip.right || + r.bottom < clip.top || + r.top > clip.bottom + ) + return null; + } + return { + x: r.left + r.width / 2, + y: r.top + r.height / 2, + width: r.width, + height: r.height, + }; + }; + const boat = (p) => query(`[data-boat="${p}"]`); + const card = (p) => query(`[data-player-card="${p}"] .player-name`); + const cell = (id) => query(`[data-cell="${id}"] .cell-surface`); + function cancel() { + view.cancelAnimationFrame(frame); + for (const animation of animations) animation.cancel(); + animations.clear(); + layer.replaceChildren(); + } + function animate( + node, + frames, + duration, + { delay = 0, remove = false, fill = "none" } = {}, + ) { + if (!node?.animate) { + if (remove) node?.remove(); + return; + } + const animation = node.animate(frames, { + duration, + delay, + fill, + easing: "ease-out", + }); + animations.add(animation); + const finish = () => { + animations.delete(animation); + if (remove) node.remove(); + }; + animation.onfinish = () => { + animation.cancel(); + finish(); + }; + animation.oncancel = finish; + } + function overlay(at, html, kind = "reward") { + if (!at) return null; + const node = doc.createElement("div"); + node.className = `action-effect effect-${kind}`; + node.innerHTML = html; + node.style.left = `${Math.max(72, Math.min(view.innerWidth - 72, at.x))}px`; + node.style.top = `${Math.max(24, at.y)}px`; + layer.append(node); + return node; + } + function gain(at, html, delay = 0) { + const node = overlay(at, html); + if (node) + animate( + node, + [ + { + opacity: 0, + transform: "translate(-50%, -40%) scale(.94)", + offset: 0, + }, + { + opacity: 1, + transform: "translate(-50%, -80%) scale(1)", + offset: 0.15, + }, + { opacity: 1, transform: "translate(-50%, -100%)", offset: 0.8 }, + { opacity: 0, transform: "translate(-50%, -115%)", offset: 1 }, + ], + 1100, + { delay, remove: true, fill: "backwards" }, + ); + } + function pulse(element) { + if (!point(element)) return; + animate( + element, + [ + { boxShadow: "inset 0 0 0 2px #c59543, 0 0 0 3px #c5954344" }, + { boxShadow: "inset 0 0 0 2px transparent, 0 0 0 6px transparent" }, + ], + 750, + ); + } + function drop(element) { + if (!allowed() || !point(element)) return; + animate( + element, + [ + { transform: "translateY(-7px) scale(1.14)" }, + { transform: "translateY(1px) scale(.98)", offset: 0.7 }, + { transform: "none" }, + ], + 230, + ); + } + function fly(html, from, to, duration = 420, waypoints = []) { + if (!from || !to) return false; + const node = overlay(from, html, "piece"); + node.style.left = `${from.x}px`; + node.style.top = `${from.y}px`; + const positions = [from, ...waypoints, to]; + animate( + node, + positions.map((p) => ({ + transform: `translate(calc(-50% + ${p.x - from.x}px), calc(-50% + ${p.y - from.y}px))`, + })), + duration, + { remove: true }, + ); + return node; + } + function capture() { + if (!allowed()) return null; + return { + boats: new Map( + [...root.querySelectorAll("[data-boat]")].map((b) => [ + Number(b.dataset.boat), + point(b), + ]), + ), + first: point(query(".player-name [data-first-help]")), + }; + } + function show(events, before, after, captured, player) { + cancel(); + if (doc.hidden) return; + const cue = soundFor(events); + if (cue) void sound.play(cue); + if (!allowed()) return; + // Pending controls and dialog closure can render again in the same turn. + // Position effects once, after that work, without a per-frame layout loop. + frame = view.requestAnimationFrame(() => { + frame = 0; + if (!allowed()) return; + for (const event of events) { + const p = event.p; + const d = event.details ?? {}; + if (["plan", "neutral"].includes(event.type)) { + for (const action of new Set(event.actions)) + drop( + query( + `[data-action="${action}"] ${event.type === "neutral" ? ".neutral" : `[data-marker-player="${p}"]`}`, + ), + ); + } + if (event.type === "action" && event.action === "sail") { + const node = boat(p), + end = point(node), + start = captured?.boats.get(p); + const matrix = query(".archipelago")?.getScreenCTM(); + const path = matrix + ? (event.path ?? []).slice(0, -1).map((id) => { + const c = center(id); + return new view.DOMPoint(c.x, c.y + 11).matrixTransform(matrix); + }) + : []; + const duration = Math.min(650, 280 + (event.path?.length ?? 1) * 110); + const box = node?.getBBox(); + const piece = fly( + `${node?.innerHTML ?? ""}`, + start, + end, + duration, + path, + ); + if (piece) { + piece.style.color = after.players[p].color; + piece.style.width = `${end.width}px`; + piece.style.height = `${end.height}px`; + animate(node, [{ opacity: 0 }, { opacity: 0 }], duration); + } + } + const source = + point(cell(event.cell ?? d.cell ?? after.players[p]?.boat)) ?? + point(card(p)); + if ( + event.type === "action" && + ["build", "draw", "tourist"].includes(event.action) + ) { + const piece = overlay(source, icon(event.action), "stamp"); + if (piece) { + piece.style.color = after.players[p].color; + animate( + piece, + [ + { opacity: 0, transform: "translate(-50%, -90%) scale(1.2)" }, + { + opacity: 1, + transform: "translate(-50%, -60%) scale(1)", + offset: 0.3, + }, + { + opacity: 0, + transform: "translate(-50%, -60%) scale(1)", + offset: 1, + }, + ], + 650, + { remove: true }, + ); + } + } + if (event.action === "buy") + for (const shipment of d.shipments ?? []) { + const ship = query(`[data-ship="${shipment.ship}"]`); + fly(icon(event.good), source, point(ship)); + if (shipment.complete) pulse(ship); + } + const changes = rewards(event); + if (changes.length) + gain( + source, + changes + .map( + ({ icon: name, value }) => + `${value > 0 ? "+" : "−"}${Math.abs(value)}${icon(name)}`, + ) + .join(""), + event.action === "sail" ? 500 : 130, + ); + if (event.type === "conversion") + gain( + point(card(p)) ?? source, + `${event.points * 2}${icon("coin")}→+${event.points}${icon("point")}`, + 450, + ); + } + if (before.first !== after.first) + fly( + icon("first"), + captured?.first, + point(query(".player-name [data-first-help]")), + 480, + ); + if ( + after.phase === "actions" && + before.phase === "actions" && + Number.isInteger(player) + ) { + const previous = before.majorities?.[player] ?? []; + for (const action of after.majorities?.[player] ?? []) + if ( + !previous.includes(action) && + after.players[player].markers[action] > 0 + ) + pulse(query(`[data-action="${action}"]`)); + } + }); + } + // Cancel overlays on scrolling instead of tracking layout on every frame. + const scrolled = (event) => { + // The journal follows new entries by scrolling its own list; that does not + // move the board and must not cancel feedback for the move just received. + if (event.target === doc || event.target.closest?.(".play")) cancel(); + }; + doc.addEventListener("scroll", scrolled, { capture: true, passive: true }); + view.addEventListener("resize", cancel, { passive: true }); + const visibility = () => { + if (doc.hidden) { + cancel(); + sound.stop(); + } + }; + doc.addEventListener("visibilitychange", visibility); + motion.addEventListener("change", cancel); + return { + capture, + show, + cancel, + drop, + setEnabled(value) { + enabled = value !== false; + if (!enabled) cancel(); + }, + destroy() { + cancel(); + doc.removeEventListener("scroll", scrolled, true); + view.removeEventListener("resize", cancel); + doc.removeEventListener("visibilitychange", visibility); + motion.removeEventListener("change", cancel); + layer.remove(); + }, + }; +} diff --git a/viewer/index.js b/viewer/index.js index d1634a9..9dc237b 100644 --- a/viewer/index.js +++ b/viewer/index.js @@ -101,17 +101,22 @@ registerViewer( } const data = log.data; if (data?.frames?.length && log.start === position - 1) { - ui.render({ ...data.frames[0], legal: [], historyLength: position }); + ui.render( + { ...data.frames[0], legal: [], historyLength: position }, + { live: false }, + ); ui.setEnabled(false); } }, onReplayStart() { replaying = true; + ui.stopEffects(); ui.setEnabled(false); seek(live?.historyLength ?? 1); }, onReplayTo(index) { replaying = true; + ui.stopEffects(); seek(index); }, onReplayEnd() { @@ -119,7 +124,7 @@ registerViewer( ui.setEnabled(true); if (live) { position = live.historyLength; - ui.render(live); + ui.render(live, { live: false }); } ctx.fetchState(); }, diff --git a/viewer/localization/da.json b/viewer/localization/da.json index 92cd8b5..336c93e 100644 --- a/viewer/localization/da.json +++ b/viewer/localization/da.json @@ -1,4 +1,5 @@ { + "Animations": "Animationer", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/de.json b/viewer/localization/de.json index 0f99ec6..3d8da9f 100644 --- a/viewer/localization/de.json +++ b/viewer/localization/de.json @@ -1,4 +1,5 @@ { + "Animations": "Animationen", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/el.json b/viewer/localization/el.json index dbdd3d7..11c3a7c 100644 --- a/viewer/localization/el.json +++ b/viewer/localization/el.json @@ -1,4 +1,5 @@ { + "Animations": "Κινούμενα εφέ", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/en.json b/viewer/localization/en.json index f5d6850..4e8188c 100644 --- a/viewer/localization/en.json +++ b/viewer/localization/en.json @@ -1,4 +1,5 @@ { + "Animations": "Animations", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/fa.json b/viewer/localization/fa.json index a748946..a9e418d 100644 --- a/viewer/localization/fa.json +++ b/viewer/localization/fa.json @@ -1,4 +1,5 @@ { + "Animations": "پویانمایی", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/fr.json b/viewer/localization/fr.json index 5940051..ef88a37 100644 --- a/viewer/localization/fr.json +++ b/viewer/localization/fr.json @@ -1,4 +1,5 @@ { + "Animations": "Animations", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/hi.json b/viewer/localization/hi.json index 8d377dc..b137237 100644 --- a/viewer/localization/hi.json +++ b/viewer/localization/hi.json @@ -1,4 +1,5 @@ { + "Animations": "एनिमेशन", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/it.json b/viewer/localization/it.json index ec28593..c8d4583 100644 --- a/viewer/localization/it.json +++ b/viewer/localization/it.json @@ -1,4 +1,5 @@ { + "Animations": "Animazioni", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/ko.json b/viewer/localization/ko.json index c6a9361..b80f115 100644 --- a/viewer/localization/ko.json +++ b/viewer/localization/ko.json @@ -1,4 +1,5 @@ { + "Animations": "애니메이션", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/nl.json b/viewer/localization/nl.json index d2fee66..bb66d93 100644 --- a/viewer/localization/nl.json +++ b/viewer/localization/nl.json @@ -1,4 +1,5 @@ { + "Animations": "Animaties", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/pl.json b/viewer/localization/pl.json index 47a17ad..7f2442d 100644 --- a/viewer/localization/pl.json +++ b/viewer/localization/pl.json @@ -1,4 +1,5 @@ { + "Animations": "Animacje", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/pt-BR.json b/viewer/localization/pt-BR.json index fafd009..cc62874 100644 --- a/viewer/localization/pt-BR.json +++ b/viewer/localization/pt-BR.json @@ -1,4 +1,5 @@ { + "Animations": "Animações", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/ro.json b/viewer/localization/ro.json index ba7b337..b0ed088 100644 --- a/viewer/localization/ro.json +++ b/viewer/localization/ro.json @@ -1,4 +1,5 @@ { + "Animations": "Animații", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/ru.json b/viewer/localization/ru.json index 34754e9..6e9bd6c 100644 --- a/viewer/localization/ru.json +++ b/viewer/localization/ru.json @@ -1,4 +1,5 @@ { + "Animations": "Анимации", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/vi.json b/viewer/localization/vi.json index 04d01c9..ac1fde7 100644 --- a/viewer/localization/vi.json +++ b/viewer/localization/vi.json @@ -1,4 +1,5 @@ { + "Animations": "Hiệu ứng chuyển động", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/zh-CN.json b/viewer/localization/zh-CN.json index 11f9f5f..ddec371 100644 --- a/viewer/localization/zh-CN.json +++ b/viewer/localization/zh-CN.json @@ -1,4 +1,5 @@ { + "Animations": "动画", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/localization/zh-TW.json b/viewer/localization/zh-TW.json index 91a1790..36fecb3 100644 --- a/viewer/localization/zh-TW.json +++ b/viewer/localization/zh-TW.json @@ -1,4 +1,5 @@ { + "Animations": "動畫", "\" alt=\"": "\" alt=\"", "\" aria-label=\"": "\" aria-label=\"", "\" aria-pressed=\"": "\" aria-pressed=\"", diff --git a/viewer/sound.js b/viewer/sound.js index 02110c5..b5c89bd 100644 --- a/viewer/sound.js +++ b/viewer/sound.js @@ -1,24 +1,84 @@ +// Short, locally synthesized materials: no audio download or looping ambience. export function createMoveSound( createContext = () => new (globalThis.AudioContext ?? globalThis.webkitAudioContext)(), ) { let context, + noise, ready = Promise.resolve(), enabled = false, - destroyed = false; + destroyed = false, + generation = 0; const active = new Set(); + function stop() { + generation++; + for (const source of [...active]) { + try { + source.stop(); + } catch {} + } + } + function voice(source, duration, volume, delay = 0, filter) { + const gain = context.createGain(); + const start = context.currentTime + delay; + gain.gain.setValueAtTime(0.0001, start); + gain.gain.exponentialRampToValueAtTime(volume, start + 0.008); + gain.gain.exponentialRampToValueAtTime(0.0001, start + duration); + if (filter) source.connect(filter).connect(gain); + else source.connect(gain); + gain.connect(context.destination); + active.add(source); + source.onended = () => { + active.delete(source); + source.disconnect(); + filter?.disconnect(); + gain.disconnect(); + }; + source.start(start); + source.stop(start + duration); + } + function tone( + frequency, + duration, + volume, + delay = 0, + end = frequency, + type = "sine", + ) { + const source = context.createOscillator(); + source.type = type; + source.frequency.setValueAtTime(frequency, context.currentTime + delay); + source.frequency.exponentialRampToValueAtTime( + end, + context.currentTime + delay + duration, + ); + voice(source, duration, volume, delay); + } + function rustle(frequency, duration, volume, delay = 0) { + if (!noise) { + noise = context.createBuffer(1, context.sampleRate, context.sampleRate); + const data = noise.getChannelData(0); + let seed = 9173; + for (let i = 0; i < data.length; i++) { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + data[i] = seed / 2147483648 - 1; + } + } + const source = context.createBufferSource(); + source.buffer = noise; + const filter = context.createBiquadFilter(); + filter.type = "lowpass"; + filter.frequency.value = frequency; + voice(source, duration, volume, delay, filter); + } return { setEnabled(value) { enabled = value === true; - if (!enabled) - for (const oscillator of active) { - try { - oscillator.stop(); - } catch {} - } + if (!enabled) stop(); }, + stop, unlock() { - // Called from the user's click, before awaiting the server's move response. + // Unlock on a user gesture, before waiting for a server response. if (!enabled || destroyed) return; try { context ??= createContext(); @@ -26,32 +86,74 @@ export function createMoveSound( ready = context.resume().catch(() => {}); } catch {} }, - async play() { + async play(kind = "marker") { + const request = ++generation; await ready; - if (!enabled || destroyed || context?.state !== "running") return; + if ( + !enabled || + destroyed || + request !== generation || + context?.state !== "running" + ) + return; try { - const oscillator = context.createOscillator(), - gain = context.createGain(); - gain.gain.setValueAtTime(0.025, context.currentTime); - gain.gain.exponentialRampToValueAtTime( - 0.001, - context.currentTime + 0.13, - ); - oscillator.frequency.value = 540; - oscillator.connect(gain).connect(context.destination); - active.add(oscillator); - oscillator.onended = () => { - active.delete(oscillator); - oscillator.disconnect(); - gain.disconnect(); - }; - oscillator.start(); - oscillator.stop(context.currentTime + 0.13); - } catch {} + // Fast bot moves replace the previous cue instead of building a queue. + stop(); + switch (kind) { + case "sail": + rustle(700, 0.42, 0.04); + rustle(1100, 0.28, 0.025, 0.12); + break; + case "fish": + tone(380, 0.13, 0.035, 0, 160); + tone(510, 0.16, 0.025, 0.1, 220); + break; + case "draw": + rustle(1800, 0.27, 0.025); + rustle(1300, 0.16, 0.018, 0.13); + break; + case "build": + tone(190, 0.1, 0.045, 0, 100); + tone(260, 0.14, 0.035, 0.12, 130); + break; + case "sell": + tone(880, 0.18, 0.022); + tone(1175, 0.24, 0.018, 0.075); + break; + case "buy": + tone(180, 0.12, 0.04, 0, 100); + tone(660, 0.25, 0.022, 0.08); + break; + case "complete": + tone(660, 0.28, 0.025); + tone(880, 0.3, 0.022, 0.1); + tone(1320, 0.34, 0.015, 0.2); + break; + case "explore": + tone(220, 0.09, 0.035, 0, 110); + tone(990, 0.32, 0.017, 0.08); + break; + case "rest": + case "tourist": + tone(440, 0.24, 0.022); + tone(660, 0.28, 0.012, 0.08); + break; + case "discard": + tone(160, 0.09, 0.018, 0, 110); + break; + default: + tone(260, 0.09, 0.04, 0, 130); + } + } catch { + // Sound is optional; unavailable audio must never interrupt the game. + stop(); + } }, destroy() { destroyed = true; + stop(); active.clear(); + noise = undefined; context?.close().catch(() => {}); }, }; diff --git a/viewer/style.css b/viewer/style.css index b3fba01..7c6b29f 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -54,6 +54,72 @@ outline: 3px solid #bb773c; outline-offset: 3px; } +.vanuatu .action-dock button { + background-image: linear-gradient(#ffffff38, #b9955720); + box-shadow: + inset 0 1px #fff9e8, + 0 2px 0 #244e5318; +} +.vanuatu .marker-stack, +.vanuatu .draft-marker { + box-shadow: + inset 0 1px #ffffff85, + 0 2px 0 #244e5333; +} +@media (prefers-reduced-motion: no-preference) { + .vanuatu:not([data-animations="false"]) + button:active:not(:disabled):not([aria-disabled="true"]) { + transform: translateY(1px); + } +} +.vanuatu .action-effects { + position: fixed; + inset: 0; + overflow: hidden; + pointer-events: none; + z-index: 25; +} +.vanuatu .action-effect { + position: absolute; + pointer-events: none; + transform: translate(-50%, -50%); +} +.vanuatu .effect-reward { + display: flex; + align-items: center; + gap: 8px; + padding: 5px 9px; + border: 1px solid #bba56d; + border-radius: 20px; + background: #fff9e8; + color: #244e53; + box-shadow: 0 3px 8px #173e3f22; + font-size: 15px; + font-weight: 750; + white-space: nowrap; +} +.vanuatu .effect-reward > span { + display: inline-flex; + align-items: center; + gap: 3px; +} +.vanuatu .effect-reward .icon { + width: 22px; + height: 22px; +} +.vanuatu .effect-piece, +.vanuatu .effect-stamp { + width: 36px; + height: 36px; +} +.vanuatu .effect-piece > .icon, +.vanuatu .effect-stamp > .icon { + width: 100%; + height: 100%; +} +.vanuatu[data-animations="false"] .water-shimmer { + animation: none; +} .vanuatu .icon { width: 23px; height: 23px; diff --git a/viewer/ui.js b/viewer/ui.js index 3f7a017..db57d8f 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -37,6 +37,7 @@ import { mountActivity } from "./activity.js"; import { pictogramText } from "./prose.js"; import { rulesHtml } from "./rules.js"; import { createMoveSound } from "./sound.js"; +import { createEffects, liveEvents } from "./effects.js"; import { languages, resolveLocale, @@ -102,6 +103,7 @@ export function mountGame(target, options = {}) { hostedLocale = false, colorBlind = false, sound = false, + animations = true, autoRetrieve = false, undoAvailable = false, revision, @@ -133,8 +135,14 @@ export function mountGame(target, options = {}) { renderToken(name, n, label ?? `${iconLabel(name, lang)}: ${n}`, colorBlind); let t = translator(lang); const moveSound = createMoveSound(); + const effects = createEffects(root, { icon, sound: moveSound, center }); const events = new AbortController(); const listener = { signal: events.signal }; + root.addEventListener("pointerdown", () => moveSound.unlock(), { + ...listener, + passive: true, + }); + root.addEventListener("keydown", () => moveSound.unlock(), listener); const mapZoom = mountMapZoom(play); const trayObserver = new ResizeObserver(([entry]) => { const parent = entry.target.parentElement; @@ -271,7 +279,7 @@ export function mountGame(target, options = {}) { } function playerCard(p, i) { const c = CHARACTERS[p.character]; - return `
${btn(`${avatars[i] ? `` : ""}${colorBlind ? symbol(i) + " " : ""}${esc(p.name)}${playerBadge(i)}`, `data-bgs-player="${i}" title="${esc(p.name)}"`, "profile")} ${s.first === i ? btn(icon("first", translateText(FIRST_HELP, lang)), `data-first-help aria-label="${t("first")}"`, "icon-button") : ""}${token("point", p.score)}
${token("coin", p.money)}${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}${token("build", p.hutsLeft)}
${c ? `` : ""}${i === player ? `
${legal().some((m) => m.type === "treasure") ? btn(`${icon("explore")} → ${icon("coin")}`, `data-free="treasure" title="${t("treasure")}"`) : ""}${legal().some((m) => m.type === "beg") ? btn(`${icon("point")} → ${icon("coin")}`, `data-free="beg" title="${t("beg")}"`) : ""}
` : ""}
`; + return `
${btn(`${avatars[i] ? `` : ""}${colorBlind ? symbol(i) + " " : ""}${esc(p.name)}${playerBadge(i)}`, `data-bgs-player="${i}" title="${esc(p.name)}"`, "profile")} ${s.first === i ? btn(icon("first", translateText(FIRST_HELP, lang)), `data-first-help aria-label="${t("first")}"`, "icon-button") : ""}${token("point", p.score)}
${token("coin", p.money)}${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}${token("build", p.hutsLeft)}
${c ? `` : ""}${i === player ? `
${legal().some((m) => m.type === "treasure") ? btn(`${icon("explore")} → ${icon("coin")}`, `data-free="treasure" title="${t("treasure")}"`) : ""}${legal().some((m) => m.type === "beg") ? btn(`${icon("point")} → ${icon("coin")}`, `data-free="beg" title="${t("beg")}"`) : ""}
` : ""}
`; } function dock() { const planning = ["plan", "neutral"].includes(s.phase) && working().length; @@ -346,7 +354,7 @@ export function mountGame(target, options = {}) { const stacks = s.players .map((p, i) => p.markers[a] - ? `${colorBlind ? symbol(i) : ""}${p.markers[a]}` + ? `${colorBlind ? symbol(i) : ""}${p.markers[a]}` : "", ) .join(""); @@ -422,7 +430,7 @@ export function mountGame(target, options = {}) { } function tradeShips() { const help = `Foreign trade\n${colorBlind ? "K: kava · C: copra · B: beef." : "Green: kava · White: copra · Red: beef."}\nEach export fills the first ship (1 → 3) still needing that good. ✓ = already delivered.\nCompleting a ship adds 2 prosperity points.`; - return `
${s.demands.map((d, i) => `
${i + 1}${d.goods.map((g, j) => `${icon(g)}${d.filled[j] ? icon("check") : ""}`).join("")}${icon("buy")}
`).join("")}
`; + return `
${s.demands.map((d, i) => `
${i + 1}${d.goods.map((g, j) => `${icon(g)}${d.filled[j] ? icon("check") : ""}`).join("")}${icon("buy")}
`).join("")}
`; } function renderControls() { const focus = document.activeElement?.getAttribute("data-action"); @@ -598,7 +606,6 @@ export function mountGame(target, options = {}) { closeDialog(); return; } - void moveSound.play(); selected = null; action = null; draft = []; @@ -725,6 +732,11 @@ export function mountGame(target, options = {}) { if (s.phase === "neutral") draft.sort((a, b) => ACTIONS.indexOf(a) - ACTIONS.indexOf(b)); renderControls(); + effects.drop( + play.querySelector(`[data-action="${d.action}"] .draft-marker`), + ); + moveSound.unlock(); + void moveSound.play("marker"); return; } else { action = d.action; @@ -809,7 +821,7 @@ export function mountGame(target, options = {}) { } if ("help" in d) { showDialog( - `

${t("help")}

${options.onSetting && Number.isInteger(player) && !analysis ? `` : ""}${ + `

${t("help")}

${options.onSetting && Number.isInteger(player) && !analysis ? `` : ""}${ hostedLocale ? "" : `