Add tactile action feedback and contextual sounds
This commit is contained in:
parent
8b9b36cd0b
commit
beff51dbb9
28 changed files with 1168 additions and 43 deletions
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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],
|
||||
|
|
|
|||
359
test/effects-browser.mjs
Normal file
359
test/effects-browser.mjs
Normal file
|
|
@ -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(
|
||||
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/viewer.css"><div id="game"></div><script src="/viewer.js"></script>',
|
||||
);
|
||||
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();
|
||||
}
|
||||
73
test/effects.test.js
Normal file
73
test/effects.test.js
Normal file
|
|
@ -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);
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 += `<g class="boat ${pi === player ? "own" : ""}" transform="translate(${x - 24} ${y - 24})" style="color:${p.color}" filter="url(#${prefix}-boat-shadow)"><title>${esc(help)}</title>${svgIcon("sail", 0, 0, 48, p.color, help)}${colorBlind ? `<text x="25" y="40" class="color-symbol">${symbols[pi]}</text>` : ""}</g>`;
|
||||
svg += `<g data-boat="${pi}" class="boat ${pi === player ? "own" : ""}" transform="translate(${x - 24} ${y - 24})" style="color:${p.color}" filter="url(#${prefix}-boat-shadow)"><title>${esc(help)}</title>${svgIcon("sail", 0, 0, 48, p.color, help)}${colorBlind ? `<text x="25" y="40" class="color-symbol">${symbols[pi]}</text>` : ""}</g>`;
|
||||
}
|
||||
svg += "</g>";
|
||||
}
|
||||
|
|
|
|||
396
viewer/effects.js
vendored
Normal file
396
viewer/effects.js
vendored
Normal file
|
|
@ -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(
|
||||
`<svg class="icon" viewBox="${box ? `${box.x} ${box.y} ${box.width} ${box.height}` : "0 0 48 48"}">${node?.innerHTML ?? ""}</svg>`,
|
||||
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 }) =>
|
||||
`<span>${value > 0 ? "+" : "−"}${Math.abs(value)}${icon(name)}</span>`,
|
||||
)
|
||||
.join(""),
|
||||
event.action === "sail" ? 500 : 130,
|
||||
);
|
||||
if (event.type === "conversion")
|
||||
gain(
|
||||
point(card(p)) ?? source,
|
||||
`<span>${event.points * 2}${icon("coin")}</span><span>→</span><span>+${event.points}${icon("point")}</span>`,
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -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();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animationer",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animationen",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Κινούμενα εφέ",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animations",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "پویانمایی",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animations",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "एनिमेशन",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animazioni",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "애니메이션",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animaties",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animacje",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animações",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Animații",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Анимации",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "Hiệu ứng chuyển động",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "动画",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"Animations": "動畫",
|
||||
"\" alt=\"": "\" alt=\"",
|
||||
"\" aria-label=\"": "\" aria-label=\"",
|
||||
"\" aria-pressed=\"": "\" aria-pressed=\"",
|
||||
|
|
|
|||
158
viewer/sound.js
158
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(() => {});
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
50
viewer/ui.js
50
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 `<section class="player-card ${i === s.actor && !s.finished ? "active" : ""} ${i === player ? "own" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}"><div class="player-name">${btn(`${avatars[i] ? `<img class="player-avatar" src="${esc(avatars[i])}" alt="">` : ""}<span>${colorBlind ? symbol(i) + " " : ""}${esc(p.name)}</span>${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") : ""}<strong class="score">${token("point", p.score)}</strong></div><div class="player-supplies">${token("coin", p.money)}<span class="hand" title="${t("fishStock")}">${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}</span><span class="hand" title="${t("treasure")}">${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}</span>${token("build", p.hutsLeft)}</div>${c ? `<button type="button" class="character-owned ${p.used ? "used" : ""}" data-character="${p.character}" title="${charName(p.character)}"><img src="${assets["character-" + c.art]}" alt=""><span>${charName(p.character)}</span>${p.used ? icon("check") : icon(c.action ?? "point")}</button>` : ""}${i === player ? `<div class="free-actions">${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")}"`) : ""}</div>` : ""}</section>`;
|
||||
return `<section data-player-card="${i}" class="player-card ${i === s.actor && !s.finished ? "active" : ""} ${i === player ? "own" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}"><div class="player-name">${btn(`${avatars[i] ? `<img class="player-avatar" src="${esc(avatars[i])}" alt="">` : ""}<span>${colorBlind ? symbol(i) + " " : ""}${esc(p.name)}</span>${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") : ""}<strong class="score">${token("point", p.score)}</strong></div><div class="player-supplies">${token("coin", p.money)}<span class="hand" title="${t("fishStock")}">${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}</span><span class="hand" title="${t("treasure")}">${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}</span>${token("build", p.hutsLeft)}</div>${c ? `<button type="button" class="character-owned ${p.used ? "used" : ""}" data-character="${p.character}" title="${charName(p.character)}"><img src="${assets["character-" + c.art]}" alt=""><span>${charName(p.character)}</span>${p.used ? icon("check") : icon(c.action ?? "point")}</button>` : ""}${i === player ? `<div class="free-actions">${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")}"`) : ""}</div>` : ""}</section>`;
|
||||
}
|
||||
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]
|
||||
? `<span class="marker-stack ${s.majorities?.[i]?.includes(a) ? "majority" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}" title="${esc(p.name)}: ${p.markers[a]}">${colorBlind ? symbol(i) : ""}${p.markers[a]}</span>`
|
||||
? `<span data-marker-player="${i}" class="marker-stack ${s.majorities?.[i]?.includes(a) ? "majority" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}" title="${esc(p.name)}: ${p.markers[a]}">${colorBlind ? symbol(i) : ""}${p.markers[a]}</span>`
|
||||
: "",
|
||||
)
|
||||
.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 `<div class="demand-ships" title="${esc(help)}" aria-label="${esc(help)}">${s.demands.map((d, i) => `<div class="demand-ship"><small>${i + 1}</small>${d.goods.map((g, j) => `<span class="${d.filled[j] ? "filled" : ""}">${icon(g)}${d.filled[j] ? icon("check") : ""}</span>`).join("")}${icon("buy")}</div>`).join("")}</div>`;
|
||||
return `<div class="demand-ships" title="${esc(help)}" aria-label="${esc(help)}">${s.demands.map((d, i) => `<div class="demand-ship" data-ship="${d.id}"><small>${i + 1}</small>${d.goods.map((g, j) => `<span class="${d.filled[j] ? "filled" : ""}">${icon(g)}${d.filled[j] ? icon("check") : ""}</span>`).join("")}${icon("buy")}</div>`).join("")}</div>`;
|
||||
}
|
||||
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(
|
||||
`<h2>${t("help")}</h2><div class="preferences"><label><input type="checkbox" data-pref="colorBlind" ${colorBlind ? "checked" : ""}>${t("colorBlind")}</label><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label>${options.onSetting && Number.isInteger(player) && !analysis ? `<label><input type="checkbox" data-setting="autoRetrieve" ${autoRetrieve ? "checked" : ""}>${esc(translateText("Automatically retrieve markers when there is no choice", lang))}</label>` : ""}${
|
||||
`<h2>${t("help")}</h2><div class="preferences"><label><input type="checkbox" data-pref="colorBlind" ${colorBlind ? "checked" : ""}>${t("colorBlind")}</label><label><input type="checkbox" data-pref="animations" ${animations ? "checked" : ""}>${esc(translateText("Animations", lang))}</label><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label>${options.onSetting && Number.isInteger(player) && !analysis ? `<label><input type="checkbox" data-setting="autoRetrieve" ${autoRetrieve ? "checked" : ""}>${esc(translateText("Automatically retrieve markers when there is no choice", lang))}</label>` : ""}${
|
||||
hostedLocale
|
||||
? ""
|
||||
: `<select data-language aria-label="Language">${Object.entries(
|
||||
|
|
@ -870,6 +882,11 @@ export function mountGame(target, options = {}) {
|
|||
if (key === "colorBlind") {
|
||||
colorBlind = value;
|
||||
}
|
||||
if (key === "animations") {
|
||||
animations = value;
|
||||
effects.setEnabled(value);
|
||||
root.dataset.animations = String(value);
|
||||
}
|
||||
if (key === "sound") {
|
||||
sound = value;
|
||||
moveSound.setEnabled(value);
|
||||
|
|
@ -922,13 +939,18 @@ export function mountGame(target, options = {}) {
|
|||
);
|
||||
return {
|
||||
root,
|
||||
render(state) {
|
||||
render(state, { live = true } = {}) {
|
||||
const before = s;
|
||||
const incoming = live && !analysis ? liveEvents(before, state) : [];
|
||||
const captured = incoming.length ? effects.capture() : null;
|
||||
const next = `${state.historyLength ?? state.round + ":" + state.phase}:${player}`;
|
||||
const key = JSON.stringify(state);
|
||||
rawState = state;
|
||||
s = displayState(state);
|
||||
if (stateKey === key && next === revision) return;
|
||||
stateKey = key;
|
||||
effects.cancel();
|
||||
if (!incoming.length) moveSound.stop();
|
||||
if (next !== revision) {
|
||||
selected = null;
|
||||
action = null;
|
||||
|
|
@ -936,6 +958,7 @@ export function mountGame(target, options = {}) {
|
|||
revision = next;
|
||||
}
|
||||
render();
|
||||
if (incoming.length) effects.show(incoming, before, s, captured, player);
|
||||
},
|
||||
setAvatars(value) {
|
||||
if (JSON.stringify(avatars) === JSON.stringify(value)) return;
|
||||
|
|
@ -951,6 +974,10 @@ export function mountGame(target, options = {}) {
|
|||
selected = null;
|
||||
render();
|
||||
},
|
||||
stopEffects() {
|
||||
effects.cancel();
|
||||
moveSound.stop();
|
||||
},
|
||||
setEnabled(v) {
|
||||
if (enabled === v) return;
|
||||
enabled = v;
|
||||
|
|
@ -979,9 +1006,17 @@ export function mountGame(target, options = {}) {
|
|||
)
|
||||
: [];
|
||||
s = displayState(rawState);
|
||||
animations = p.animations !== false;
|
||||
effects.setEnabled(animations);
|
||||
if (root.dataset.animations !== String(animations))
|
||||
root.dataset.animations = String(animations);
|
||||
sound = p.sound === true;
|
||||
moveSound.setEnabled(sound);
|
||||
for (const [name, value] of Object.entries({ colorBlind, sound })) {
|
||||
for (const [name, value] of Object.entries({
|
||||
colorBlind,
|
||||
sound,
|
||||
animations,
|
||||
})) {
|
||||
const checkbox = dialog.querySelector(`[data-pref="${name}"]`);
|
||||
if (checkbox && checkbox.checked !== value) checkbox.checked = value;
|
||||
}
|
||||
|
|
@ -1005,6 +1040,7 @@ export function mountGame(target, options = {}) {
|
|||
events.abort();
|
||||
mapZoom.destroy();
|
||||
trayObserver.disconnect();
|
||||
effects.destroy();
|
||||
moveSound.destroy();
|
||||
offChat?.();
|
||||
activity.destroy();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue