Animate resolved actions and clarify the final threat movement

This commit is contained in:
coyotte508 2026-10-31 23:43:45 +01:00
commit 8a693b1cca
16 changed files with 633 additions and 45 deletions

View file

@ -258,10 +258,7 @@ export async function mountLesson(
const actions = action
? s.state.game.cards[action.id]?.sides[action.side]
: [];
sound.cue(
actions?.length ? "turn" : "wait",
actions?.includes("red") ? -0.5 : actions?.includes("blue") ? 0.5 : 0,
);
if (!actions?.length) sound.cue("wait");
}
lastTurn = turn;
const view = snapshot(s.state, 0);
@ -370,6 +367,8 @@ export async function mountLesson(
!playing ||
disposed ||
playbackBusy ||
ui.isAnimating() ||
target.ownerDocument.hidden ||
tutorial.snapshot.busy ||
!canPlay(tutorial.snapshot)
)

View file

@ -1,3 +1,5 @@
import { createResolutionEffects } from "./resolution-effects.js";
import { createSoundDesign } from "./sound.js";
import { plannedRoute } from "./program-route.js";
import { translate, createLocaleSelection, lessonCopy } from "./i18n.js";
import { basicsView } from "./basics.js";
@ -53,7 +55,7 @@ export function mountConsole(root, host = null) {
careerKey = "",
crew = seat,
replayFrame = null,
sound = false,
sound = true,
combine = false,
lastSpoken = 0,
basicsStarted = false,
@ -61,6 +63,13 @@ export function mountConsole(root, host = null) {
basicsMarkup;
let route = [],
previewTurn = null;
const audio = host?.cue ? null : createSoundDesign();
const cue = (kind, pan) => host?.cue ? host.cue(kind, pan) : audio.cue(kind, pan);
const unlockSound = () => audio?.enable(sound);
root.ownerDocument.addEventListener("pointerdown", unlockSound, true);
root.ownerDocument.addEventListener("keydown", unlockSound, true);
const effects = createResolutionEffects(root, cue);
let autoResolve = false;
const t = (key, params) => translate(locale, key, params);
const actionWords = (text) =>
text.replace(
@ -175,7 +184,7 @@ export function mountConsole(root, host = null) {
}
function announcement(e) {
if (e.type === "threat")
return `T${e.turn} · ${e.severity === "serious" ? t("app.serious_threat") : t("app.threat")} · ${e.position === "internal" ? t("app.internal") : zoneName(e.zone)}`;
return `${t("app.turn")} ${e.turn} · ${e.severity === "serious" ? t("app.serious_threat") : t("app.threat")} · ${e.position === "internal" ? t("app.internal") : zoneName(e.zone)}`;
return (
{
"phase-start": t("app.phase_begins", { phase: e.phase }),
@ -288,7 +297,7 @@ export function mountConsole(root, host = null) {
});
room.insertAdjacentHTML(
"beforeend",
`<span class="planned-pawn" role="img" aria-label="${esc(description)}" title="${esc(description)}">${view.game.solo || crew >= view.players.length ? equipmentPicture("android") : pictogram("crew")}<b>${crew + 1}</b><small>T${turn}</small></span>`,
`<span class="planned-pawn" role="img" aria-label="${esc(description)}" title="${esc(description)}">${view.game.solo || crew >= view.players.length ? equipmentPicture("android") : pictogram("crew")}<b>${crew + 1}</b><small>${t("app.turn")} ${turn}</small></span>`,
);
}
for (const type of ["pointerover", "focusin"])
@ -310,6 +319,7 @@ export function mountConsole(root, host = null) {
renderCareers(next);
if (!force && key === newKey) return;
key = newKey;
effects.beforeRender();
if (!host && !view.players[seat]) seat = 0;
if (crew >= view.crewSize) crew = seat;
root.lang = locale;
@ -458,7 +468,7 @@ export function mountConsole(root, host = null) {
threats
.map(
(th) =>
`<article class="threat illustrated-threat" style="--zone:var(--${th.zone ?? "gold"})"><button class="threat-card" data-inspect="${th.instance}" data-inspect-title="${esc(th.name)} · T${th.turn}" aria-haspopup="dialog" aria-label="${esc(th.name)} · ${t("app.turn")} ${th.turn} · ${esc(th.position === "internal" ? th.stations.map((s) => stationLabel(s, locale)).join(", ") : zoneName(th.zone))} · ${t("app.details")}"><span class="threat-heading"><strong>${esc(th.name)}</strong><span class="threat-timing" title="${t("app.arrival_on_turn")} ${th.turn}">${t("app.arrival")} T${th.turn}</span></span>${threatPortrait(th)}<span class="threat-footer">${symbol("speed", `${th.speed} ${t("app.spaces_per_turn")}`, th.speed)}<span>${t("app.details")}</span></span></button>${(th.track ?? g.tracks[th.zone ?? "internal"]) ? trackHtml(th, g) : ""}<template>${threatPortrait(th)}<div class="threat-facts">${symbol("speed", `${th.speed} ${t("app.spaces_per_turn")}`, th.speed)}</div><p>${th.position === "internal" ? esc(th.stations.map((s) => stationLabel(s, locale)).join(", ")) + " · " + esc(label(th.repair)) : esc(zoneName(th.zone))}</p>${traitDescriptions(
`<article class="threat illustrated-threat" data-threat="${esc(th.instance)}" style="--zone:var(--${th.zone ?? "gold"})"><button class="threat-card" data-inspect="${th.instance}" data-inspect-title="${esc(th.name)} · ${t("app.turn")} ${th.turn}" aria-haspopup="dialog" aria-label="${esc(th.name)} · ${t("app.turn")} ${th.turn} · ${esc(th.position === "internal" ? th.stations.map((s) => stationLabel(s, locale)).join(", ") : zoneName(th.zone))} · ${t("app.details")}"><span class="threat-heading"><strong>${esc(th.name)}</strong><span class="threat-timing" title="${t("app.arrival_on_turn")} ${th.turn}">${t("app.arrival")} · ${t("app.turn")} ${th.turn}</span></span>${threatPortrait(th)}<span class="threat-footer">${symbol("speed", `${th.speed} ${t("app.spaces_per_turn")}`, th.speed)}<span>${t("app.details")}</span></span></button>${(th.track ?? g.tracks[th.zone ?? "internal"]) ? trackHtml(th, g) : ""}<template>${threatPortrait(th)}<div class="threat-facts">${symbol("speed", `${th.speed} ${t("app.spaces_per_turn")}`, th.speed)}</div><p>${th.position === "internal" ? esc(th.stations.map((s) => stationLabel(s, locale)).join(", ")) + " · " + esc(label(th.repair)) : esc(zoneName(th.zone))}</p>${traitDescriptions(
th,
locale,
)
@ -524,10 +534,16 @@ export function mountConsole(root, host = null) {
const routeDescription = destination
? `${t("route.planned", { turn: slot.turn, room: stationLabel(destination, locale) })}. ${t("route.assumption")}`
: "";
const description = `T${slot.turn} · ${slot.cards.map((c) => (c.sides ? c.sides[c.side].map(label).join(" → ") : c.category === "movement" ? t("app.movement") : t("app.action"))).join(" + ") || t("app.empty")}`;
return `<button class="slot ${slot.cards.length ? "filled" : "empty"} ${slot.turn === activeTurn ? "current" : ""} ${phaseFor(slot.turn) < ownPhase ? "locked" : ""} ${phaseFor(slot.turn) > ownPhase ? "future" : ""}" data-turn="${slot.turn}" ${slot.turn === activeTurn ? 'aria-current="step"' : ""} ${editable ? "" : "disabled"} title="${esc(description + (routeDescription ? " · " + routeDescription : ""))}" aria-label="${esc(description + (routeDescription ? " · " + routeDescription : ""))}">${firstShot && slot.turn === 2 ? `<span class="slot-arrival" title="${t("app.target_arrives_before_this_shot")}">${pictogram("down")}${t("app.arrival")}</span>` : ""}<span class="turn">T${slot.turn} ${phaseFor(slot.turn) < ownPhase ? pictogram("lock") : ""}</span><span class="action">${slot.cards.map((c) => (c.sides ? c.sides[c.side].map(icon).join(" ") : pictogram(c.category === "movement" ? "move" : "cards"))).join(" + ") || pictogram("wait")}</span>${slot.cards.length && destination ? `<span class="planned-location" aria-hidden="true">${shipLocator([destination])}</span>` : ""}</button>`;
const description = `${t("app.turn")} ${slot.turn} · ${slot.cards.map((c) => (c.sides ? c.sides[c.side].map(label).join(" → ") : c.category === "movement" ? t("app.movement") : t("app.action"))).join(" + ") || t("app.empty")}`;
return `<button class="slot ${slot.cards.length ? "filled" : "empty"} ${slot.turn === activeTurn ? "current" : ""} ${phaseFor(slot.turn) < ownPhase ? "locked" : ""} ${phaseFor(slot.turn) > ownPhase ? "future" : ""}" data-turn="${slot.turn}" ${slot.turn === activeTurn ? 'aria-current="step"' : ""} ${editable ? "" : "disabled"} title="${esc(description + (routeDescription ? " · " + routeDescription : ""))}" aria-label="${esc(description + (routeDescription ? " · " + routeDescription : ""))}">${firstShot && slot.turn === 2 ? `<span class="slot-arrival" title="${t("app.target_arrives_before_this_shot")}">${pictogram("down")}${t("app.arrival")}</span>` : ""}<span class="turn">${slot.turn} ${phaseFor(slot.turn) < ownPhase ? pictogram("lock") : ""}</span><span class="action">${slot.cards.map((c) => (c.sides ? c.sides[c.side].map(icon).join(" ") : pictogram(c.category === "movement" ? "move" : "cards"))).join(" + ") || pictogram("wait")}</span>${slot.cards.length && destination ? `<span class="planned-location" aria-hidden="true">${shipLocator([destination])}</span>` : ""}</button>`;
})
.join("");
if (!basic && !firstShot) {
const lastTurn = resolution?.lastTurn ?? (view.mission.phaseEndsMs.length === 2 ? 7 : 12);
const jumping = activeTurn > lastTurn;
$("#program").insertAdjacentHTML("beforeend",
`<div class="program-jump ${jumping ? "current" : ""}" ${jumping ? 'aria-current="step"' : ""} title="${t("app.jump_after_turn", { turn: lastTurn })}">${pictogram("ship")}<span>${t("app.jump")}</span>${resolution?.outcome?.survived ? pictogram("check") : ""}</div>`);
}
showPlannedPosition(previewTurn);
$("#program").setAttribute(
"aria-keyshortcuts",
@ -556,7 +572,7 @@ export function mountConsole(root, host = null) {
: planning
? `${g?.solo ? "" : button("advance-phase", t("app.next_phase"), own.finishedPlanning || own.planningPhase >= view.mission.phaseEndsMs.length)}${button("finish-planning", t("app.lock_my_program"), own.finishedPlanning || view.phase < view.mission.phaseEndsMs.length)}${g.dataCredits ? button("draw", `${t("app.draw")} +${g.dataCredits}`) : ""}${g.androidDataCredits ? button("draw-android", t("app.android_card") + ` +${g.androidDataCredits}`, !g.canDrawAndroid) : ""}`
: view.stage === "resolution"
? `<button data-command="resolve" class="primary icon-button" title="${t("app.next_resolution_step")}" aria-label="${t("app.next_resolution_step")}" ${seat !== 0 || !!resolution?.outcome ? "disabled" : ""}>${pictogram("step")}</button><button data-command="resolve-all" class="quiet icon-button" title="${t("app.resolve_mission")}" aria-label="${t("app.resolve_mission")}" ${seat !== 0 || !!resolution?.outcome ? "disabled" : ""}>${pictogram("right")}${pictogram("right")}</button>`
? `<button data-command="resolve" class="primary icon-button" title="${t("app.next_resolution_step")}" aria-label="${t("app.next_resolution_step")}" ${seat !== 0 || !!resolution?.outcome ? "disabled" : ""}>${pictogram("step")}</button><button data-command="resolve-all" class="quiet icon-button" title="${t(autoResolve ? "basics.pause" : "app.resolve_mission")}" aria-label="${t(autoResolve ? "basics.pause" : "app.resolve_mission")}" ${seat !== 0 || !!resolution?.outcome ? "disabled" : ""}>${pictogram(autoResolve ? "pause" : "right")}</button>`
: view.stage === "cancelled"
? '<button id="open-setup">' + t("app.new_session") + "</button>"
: "";
@ -677,13 +693,13 @@ export function mountConsole(root, host = null) {
.join("")
: "";
$("#replay").innerHTML = resolution
? `<p>${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : <b>${resolution.outcome.score}</b> · ${resolution.outcome.threatPoints} ${t("app.threats_87b951")} + ${resolution.outcome.visual} ${t("app.visual")} − ${resolution.outcome.penalties} ${t("app.penalties")}` : `T${resolution.turn} · ${esc({ appear: t("app.appearances"), crew: t("app.crew_actions"), damage: t("app.damage"), threats: t("app.threat_actions"), computer: t("app.computer") }[resolution.step])}`}</p><label>${t("app.review_a_step")} <input id="replay-slider" type="range" min="0" max="${resolution.frames.length - 1}" value="${replayFrame ?? resolution.frames.length - 1}"></label>${replayFrame !== null ? '<button id="live" class="quiet">' + t("app.back_to_live") + "</button>" : ""}`
? `<p>${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : <b>${resolution.outcome.score}</b> · ${resolution.outcome.threatPoints} ${t("app.threats_87b951")} + ${resolution.outcome.visual} ${t("app.visual")} − ${resolution.outcome.penalties} ${t("app.penalties")}` : resolution.turn > resolution.lastTurn ? t("app.final_threat_movement") : `${t("app.turn")} ${resolution.turn} · ${esc({ appear: t("app.appearances"), crew: t("app.crew_actions"), damage: t("app.damage"), threats: t("app.threat_actions"), computer: t("app.computer") }[resolution.step])}`}</p><label>${t("app.review_a_step")} <input id="replay-slider" type="range" min="0" max="${resolution.frames.length - 1}" value="${replayFrame ?? resolution.frames.length - 1}"></label>${replayFrame !== null ? '<button id="live" class="quiet">' + t("app.back_to_live") + "</button>" : ""}`
: "";
renderCampaign(g?.campaign);
$("#announcements").innerHTML = resolution
? resolution.log
.filter((_, i) => !frame || i < frame.logEnd)
.map((e) => `<li>T${e.turn} · ${esc(logText(e))}</li>`)
.map((e) => `<li>${e.turn > resolution.lastTurn ? t("app.jump") : `${t("app.turn")} ${e.turn}`} · ${esc(logText(e))}</li>`)
.join("")
: announcements
.map(
@ -716,6 +732,7 @@ export function mountConsole(root, host = null) {
`<p>${t("app.left_center_and_right_correspond_to_red_white")}</p>` +
t("app.plan_choose_a_card_then_a_turn_click");
navigation.sync();
effects.afterRender(resolution, replayFrame ?? (resolution?.frames.length ?? 0) - 1);
}
function calledHtml(data) {
if (!data) return "";
@ -739,8 +756,14 @@ export function mountConsole(root, host = null) {
(replayFrame !== null
? g.resolution?.frames[replayFrame]
: g.resolution) ?? {};
const finalTurn = g.resolution?.finalTurn ?? (view.mission.phaseEndsMs.length === 2 ? 8 : 13);
const turnLabel = (turn) => turn === finalTurn
? t("app.final_threat_movement")
: `${t("app.turn")} ${turn}`;
const groups = forecastMovement(th, track, {
...context,
finalTurn,
outcome: replayFrame === null ? g.resolution?.outcome : null,
threats:
context.threats ?? g.threats.map((item) => ({ ...item, ...item.card })),
});
@ -759,13 +782,13 @@ export function mountConsole(root, host = null) {
group.positions.includes(n),
);
const group = groups[groupIndex];
const description = `${mark ? effects.map((effect) => effectDescription(effect, locale)).join(" · ") || t("app.no_effect") : t("app.space") + " " + n}${group ? ` · T${group.turn} · ${projection}` : ""}`;
const description = `${mark ? effects.map((effect) => effectDescription(effect, locale)).join(" · ") || t("app.no_effect") : t("app.space") + " " + n}${group ? ` · ${turnLabel(group.turn)} · ${projection}` : ""}`;
const current = !pending && th.positionOnTrack === n;
return `<span title="${esc(description)}" aria-label="${esc(description)}" ${current ? 'aria-current="step"' : ""} ${group ? `data-forecast-turn="${group.turn}"` : ""} class="${current ? "current" : ""} ${pending && n === track.length ? "entry" : ""} ${appearance ? "mark effect-mark" : ""} ${group ? `forecast-cell forecast-tone-${groupIndex % 2} ${n === group.positions[0] ? "forecast-start" : ""} ${n === group.positions.at(-1) ? "forecast-end" : ""}` : ""}">${appearance ? `${pictogram(appearance.icon)}<b>${esc(appearance.value)}</b>` : current ? "●" : ""}</span>`;
})
.join(
"",
)}</div>${groups.length ? `<div class="track-turns" aria-label="${esc(projection)}"><small title="${esc(projection)}">T</small>${groups.map((group, i) => `<span class="forecast-tone-${i % 2}" style="grid-column:${track.length - group.positions[0] + 1} / span ${group.positions.length}" title="${esc(`T${group.turn} · ${group.positions.length} ${t("app.spaces")} · ${projection}`)}" aria-label="${esc(`T${group.turn} · ${projection}`)}">${group.turn}</span>`).join("")}</div>` : ""}</div>${pictogram("ship")}</div>`;
)}</div>${groups.length ? `<div class="track-turns" aria-label="${esc(projection)}"><small title="${esc(projection)}">${t("app.turn")}</small>${groups.map((group, i) => `<span class="forecast-tone-${i % 2}" style="grid-column:${track.length - group.positions[0] + 1} / span ${group.positions.length}" title="${esc(`${turnLabel(group.turn)} · ${group.positions.length} ${t("app.spaces")} · ${projection}`)}" aria-label="${esc(`${turnLabel(group.turn)} · ${projection}`)}">${group.turn === finalTurn ? pictogram("ship") : group.turn}</span>`).join("")}</div>` : ""}</div>${pictogram("ship")}</div>`;
}
function logText(e) {
return eventDescription(
@ -986,8 +1009,8 @@ export function mountConsole(root, host = null) {
sequence: view.nextSequence,
...extra,
});
if (type === "program") host.cue?.("place");
if (type === "remove") host.cue?.("remove");
if (type === "program") cue("place");
if (type === "remove") cue("remove");
return result;
}
const s =
@ -1001,6 +1024,8 @@ export function mountConsole(root, host = null) {
}).then((r) => r.json());
if (target === seat) render(result.view);
if (!result.accepted) throw Error(result.error);
if (type === "program") cue("place");
if (type === "remove") cue("remove");
}
async function perform(fn) {
pending = true;
@ -1025,6 +1050,17 @@ export function mountConsole(root, host = null) {
$("#connection").textContent = t("app.reconnecting");
}
}
intervals.push(setInterval(() => {
if (!autoResolve || pending || effects.busy() || root.ownerDocument.hidden) return;
if (seat !== 0 || view?.stage !== "resolution" || view.game.resolution?.outcome || replayFrame !== null) {
autoResolve = false;
return;
}
void perform(async () => {
try { await command("resolve"); }
catch (error) { autoResolve = false; throw error; }
});
}, 450));
function rerender() {
if (view) render(view, true);
}
@ -1147,7 +1183,7 @@ export function mountConsole(root, host = null) {
return;
}
if (el.id === "basics-start" || el.dataset.basicsPick) {
host?.cue?.("select");
cue("select");
if (el.id === "basics-start") basicsStarted = true;
else
basicsPicked =
@ -1217,7 +1253,7 @@ export function mountConsole(root, host = null) {
perform(async () => {
while (view.stage === "programming")
await localPost("/api/lesson-next", {});
host?.cue?.("start");
cue("start");
rerender();
});
return;
@ -1368,7 +1404,7 @@ export function mountConsole(root, host = null) {
return;
}
if (el.dataset.card) {
host?.cue?.("select");
cue("select");
const choice = { id: el.dataset.card, side: Number(el.dataset.side) };
if (e.shiftKey || combine)
selected = [
@ -1404,7 +1440,13 @@ export function mountConsole(root, host = null) {
});
return;
}
if (el.dataset.command === "resolve-all") {
autoResolve = !autoResolve;
rerender();
return;
}
if (el.dataset.command) {
if (el.dataset.command === "resolve") autoResolve = false;
perform(async () => {
const type = el.dataset.command;
if (
@ -1441,8 +1483,9 @@ export function mountConsole(root, host = null) {
if (el.id === "sound") {
sound = !sound;
updateSound();
audio?.enable(sound);
if (sound) speak(t("app.announcements_enabled"));
else speechSynthesis.cancel();
else if ("speechSynthesis" in window) speechSynthesis.cancel();
}
if (el.id === "ready-all")
perform(async () => {
@ -1603,6 +1646,7 @@ export function mountConsole(root, host = null) {
})();
}
return {
isAnimating: () => effects.busy(),
resetTutorial() {
previewTurn = null;
placements.length = 0;
@ -1639,11 +1683,15 @@ export function mountConsole(root, host = null) {
setPreferences(prefs) {
appearance = prefs.bgs ?? {};
if (prefs.sound !== undefined) sound = !!prefs.sound;
if (prefs.sound !== undefined) { sound = !!prefs.sound; audio?.enable(sound); }
if (prefs.locale) return language.set(prefs.locale);
rerender();
},
destroy() {
effects.destroy();
audio?.destroy();
root.ownerDocument.removeEventListener("pointerdown", unlockSound, true);
root.ownerDocument.removeEventListener("keydown", unlockSound, true);
language.destroy();
root.ownerDocument.removeEventListener("keydown", handlePlanningKey);
navigation.destroy();

View file

@ -68,7 +68,7 @@ export function basicsView(view, locale, { started, picked, shipMarkup }) {
${
intro
? btn("basics-start", t("basics.try_with_two_cards"))
: `<div class="basics-program-heading">${pictogram("cards")}<span>${t("basics.program")}</span>${pictogram("right")}</div><div class="basics-program program">${[1, 2, 3].map((n) => `<button title="${t("app.turn")} ${n} · ${actionLabel(direction(n))}" aria-label="${t("app.turn")} ${n} · ${actionLabel(direction(n))}" data-basics-turn="${n}" ${playing || (!picked && !slots[n - 1].cards.length) || n === 3 ? "disabled" : ""} class="slot ${playing && n === turn ? "current" : ""}"><span class="turn">T${n}</span><strong class="action">${pictogram(direction(n) === "blue" ? "right" : direction(n) === "red" ? "left" : "wait")}</strong></button>`).join("")}</div>
: `<div class="basics-program-heading">${pictogram("cards")}<span>${t("basics.program")}</span>${pictogram("right")}</div><div class="basics-program program">${[1, 2, 3].map((n) => `<button title="${t("app.turn")} ${n} · ${actionLabel(direction(n))}" aria-label="${t("app.turn")} ${n} · ${actionLabel(direction(n))}" data-basics-turn="${n}" ${playing || (!picked && !slots[n - 1].cards.length) || n === 3 ? "disabled" : ""} class="slot ${playing && n === turn ? "current" : ""}"><span class="turn">${n}</span><strong class="action">${pictogram(direction(n) === "blue" ? "right" : direction(n) === "red" ? "left" : "wait")}</strong></button>`).join("")}</div>
${!playing ? `<div class="practice-readiness" role="status"><progress value="${placed}" max="2"></progress><span title="${t("basics.practice_actions_placed")}" aria-label="${placed}/2 ${t("basics.practice_actions_placed_2d48e9")}">${pictogram("cards")} ${placed}/2</span></div><div class="basics-card-area"><div class="basics-card-choices">${["red", "blue"].map((action) => `<button title="${actionLabel(action)}" aria-label="${actionLabel(action)}" data-basics-pick="${action}" aria-pressed="${picked === action}" class="basics-card ${picked === action ? "selected" : ""}"><strong>${pictogram(action === "blue" ? "right" : "left")}</strong></button>`).join("")}</div></div>` : ""}
${!playing && ready ? `<div class="practice-clock"><div><strong data-practice-time>${practiceClockText(view, locale)}</strong><small>${t("basics.to_plan_safe_practice")}</small></div><button id="lesson-clock" class="icon-button" title="${view.tutorial.clockRunning ? t("basics.pause_clock") : t("basics.start_clock")}" aria-label="${view.tutorial.clockRunning ? t("basics.pause_clock") : t("basics.start_clock")}">${pictogram(view.tutorial.clockRunning ? "pause" : "clock")}</button></div><button id="basics-run" class="primary icon-button" title="${t("basics.run_program")}" aria-label="${t("basics.run_program")}">${pictogram("check")}</button>` : ""}
${playing ? (turn < 3 ? `<button data-command="resolve" class="primary icon-button" title="${t("app.next_resolution_step")}" aria-label="${t("app.next_resolution_step")}">${pictogram("step")}</button>` : `<div class="basics-complete"><p>${t("basics.planning_against_a_clock_and_carrying_out_turns")}</p><button data-lesson="first-shot" class="primary">${t("basics.next_your_first_shot")}</button></div>`) : ""}`

View file

@ -45,8 +45,8 @@
"app.basic": "basic",
"app.heroic_move": "Heroic move · ",
"app.heroic": "Heroic · ",
"app.mute_voice_announcements": "Mute voice announcements",
"app.enable_voice_announcements": "Enable voice announcements",
"app.mute_voice_announcements": "Mute sounds",
"app.enable_voice_announcements": "Enable sounds",
"app.serious_threat": "Serious threat",
"app.threat": "Threat",
"app.internal": "internal",
@ -437,7 +437,7 @@
"text.simultaneous_repair_attempted": "Simultaneous repair attempted",
"text.repair": "Repair {value1} · {value2}",
"text.final_action_lost": "; final action lost",
"text.program_delayed_from_t": "Program delayed from T{from}{value1}",
"text.program_delayed_from_t": "Program delayed from turn {from}{value1}",
"text.knocked_out": "Knocked out · {value1}",
"text.no_effect": "No effect · {value1}",
"text.damage": "Damage {value1} · {value2}",
@ -577,7 +577,7 @@
"phases.listen": "The clock advances; the ship waits. Threats are announced during planning.",
"phases.revealed": "Threat revealed: it will arrive on execution turn 6. Place → in turn 1, then jump to the last 5 seconds of this phase.",
"phases.locked": "Turns 1–3 are locked; the ship still waits. Place a deck change in turn 4, then ↵.",
"phases.all_turns": "All 7 turns now execute. The threat enters on turn 6.",
"phases.all_turns": "Seven crew turns, then a final threat movement before the jump. The meteoroid arrives on turn 6.",
"phases.skip": "Jump to the last 5 seconds of phase 1",
"phases.full_program": "Complete program",
"overview.plan": "Plan",
@ -587,12 +587,17 @@
"overview.play": "Play the whole mission",
"overview.play_detail": "Every turn, in order. No more planning.",
"overview.turns": "Full mission · 12 turns",
"route.planned": "Planned position after T{turn}: {room}",
"route.planned": "Planned position after turn {turn}: {room}",
"route.assumption": "Intended route without disruptions: delays, threats or a busy lift may change it.",
"timing.deadline_shortcuts": "Arrows: move · Backspace: undo",
"phases.deadline": "Phase {phase} · {time}",
"phases.total": "Total",
"timing.destination_reached": "Destination reached",
"timing.deadline_ready": "Start the last 5 seconds. Let the clock run out.",
"timing.deadline_running": "Wait for zero: your unfinished program will execute automatically."
"timing.deadline_running": "Wait for zero: your unfinished program will execute automatically.",
"app.jump": "Jump",
"app.jump_after_turn": "After turn {turn}: threats move once more, then the ship jumps.",
"app.final_threat_movement": "Final threat movement before the jump",
"tactical.impact": "Impact",
"phases.complete": "The meteoroid hit during the final threat movement. Then the ship jumped."
}

View file

@ -45,8 +45,8 @@
"app.basic": "basique",
"app.heroic_move": "Déplacement héroïque · ",
"app.heroic": "Héroïque · ",
"app.mute_voice_announcements": "Désactiver les annonces vocales",
"app.enable_voice_announcements": "Activer les annonces vocales",
"app.mute_voice_announcements": "Couper le son",
"app.enable_voice_announcements": "Activer le son",
"app.serious_threat": "Menace sérieuse",
"app.threat": "Menace",
"app.internal": "interne",
@ -437,7 +437,7 @@
"text.simultaneous_repair_attempted": "Réparation simultanée tentée",
"text.repair": "Répare {value1} · {value2}",
"text.final_action_lost": " ; dernière action perdue",
"text.program_delayed_from_t": "Programme décalé à partir de T{from}{value1}",
"text.program_delayed_from_t": "Programme décalé à partir du tour {from}{value1}",
"text.knocked_out": "Assommé · {value1}",
"text.no_effect": "Sans effet · {value1}",
"text.damage": "Dégât {value1} · {value2}",
@ -577,7 +577,7 @@
"phases.listen": "Le chrono avance ; le vaisseau attend. Les menaces sont annoncées pendant la préparation.",
"phases.revealed": "Menace révélée : elle arrivera au tour 6 de l’exécution. Placez → au tour 1, puis avancez aux 5 dernières secondes de cette phase.",
"phases.locked": "Les tours 1–3 sont verrouillés ; le vaisseau attend toujours. Placez le changement de pont au tour 4, puis ↵.",
"phases.all_turns": "Les 7 tours s’exécutent maintenant. La menace entre au tour 6.",
"phases.all_turns": "Sept tours d’équipage, puis un dernier mouvement des menaces avant le saut. La météorite arrive au tour 6.",
"phases.skip": "Avancer aux 5 dernières secondes de la phase 1",
"phases.full_program": "Programme complet",
"overview.plan": "Préparer",
@ -587,12 +587,17 @@
"overview.play": "Exécuter toute la mission",
"overview.play_detail": "Tous les tours, dans l’ordre. Plus de programmation.",
"overview.turns": "Mission complète · 12 tours",
"route.planned": "Position prévue après T{turn} : {room}",
"route.planned": "Position prévue après le tour {turn} : {room}",
"route.assumption": "Trajet prévu, sans perturbations : retards, menaces ou ascenseur occupé peuvent le modifier.",
"timing.deadline_shortcuts": "Flèches : se déplacer · Retour arrière : annuler",
"phases.deadline": "Phase {phase} · {time}",
"phases.total": "Total",
"timing.destination_reached": "Destination atteinte",
"timing.deadline_ready": "Lancez les 5 dernières secondes. Laissez le chrono arriver à zéro.",
"timing.deadline_running": "Attendez zéro : votre programme incomplet s’exécutera automatiquement."
"timing.deadline_running": "Attendez zéro : votre programme incomplet s’exécutera automatiquement.",
"app.jump": "Saut",
"app.jump_after_turn": "Après le tour {turn} : les menaces avancent une dernière fois, puis le vaisseau saute.",
"app.final_threat_movement": "Dernier mouvement des menaces avant le saut",
"tactical.impact": "Impact",
"phases.complete": "La météorite a frappé lors du dernier mouvement des menaces. Puis le vaisseau a sauté."
}

View file

@ -0,0 +1,265 @@
// Presentation only: consume resolved events, never predict damage or change game state.
export function resolutionEffects(resolution, before, after) {
if (!before || !after || after.logEnd < before.logEnd) return [];
const events = resolution.log.slice(before.logEnd, after.logEnd);
const fires = resolution.log.filter(e => e.turn === after.turn && e.type === "fire");
const effects = [];
for (const e of events) {
if (e.type === "move" && e.from !== e.to) effects.push({ ...e, kind: "move" });
if (e.type === "fire") effects.push({ ...e, kind: "charge" });
if (e.type === "threat-hit" || e.type === "cryoshield-broken") {
const target = after.threats.find(t => t.instance === e.threat);
// A zone has one heavy and one light laser; the log supplies the weapons
// that actually hit. No guessed target or beam through an immune enemy.
const sources = fires.filter(f => {
const weapon = f.station === "white-lower" ? "pulse" : f.station.endsWith("upper") ? "heavy" : "light";
return (!e.weapons || e.weapons.includes(weapon)) &&
(weapon === "pulse" || f.station.split("-")[0] === target?.zone);
}).map(f => ({ station: f.station, weapon: f.station === "white-lower" ? "pulse" : "laser" }));
if (e.weapons?.includes("rocket")) sources.push({ station: "blue-lower", weapon: "rocket" });
if (e.weapons?.includes("interceptors")) sources.push({ station: "red-upper", weapon: "laser" });
effects.push({ kind: "hit", threat: e.threat, damage: e.damage ?? 0, shield: e.shield ?? 1, sources });
}
if (e.type === "attack") effects.push({ ...e, kind: "attack" });
if (e.type === "ship-damage" && !events.some(a => a.type === "attack" && a.zone === e.zone && a.threat === e.source)) {
if (!effects.some(a => a.kind === "direct-damage" && a.zone === e.zone && a.threat === e.source))
effects.push({ kind: "direct-damage", zone: e.zone, threat: e.source,
damage: events.filter(a => a.type === "ship-damage" && a.zone === e.zone && a.source === e.source).length });
}
if (e.type === "threat-destroyed" && !e.prevented) effects.push({ kind: "destroy", threat: e.threat });
if (e.type === "ship-destroyed") effects.push({ kind: "ship-destroy", zone: e.zone });
}
// Teleports, forced movement, repairs and non-weapon damage also change the
// displayed board, without necessarily producing move/threat-hit log entries.
for (const crew of after.ship.crew) {
const old = before.ship.crew.find(p => p.id === crew.id);
if (old && old.station !== crew.station && !effects.some(e => e.kind === "move" && e.crew === crew.id))
effects.push({ kind: "move", crew: crew.id, from: old.station, to: crew.station });
}
for (const target of after.threats) {
const old = before.threats.find(t => t.instance === target.instance);
const damage = (target.damage ?? 0) - (old?.damage ?? 0);
if (old && damage > 0 && !effects.some(e => e.kind === "hit" && e.threat === target.instance))
effects.push({ kind: "hit", threat: target.instance, damage, shield: 0, sources: [] });
}
// Firing into empty space still fires, but must never look like a hit.
if (before.step === "damage" && after.step === "threats") {
for (const f of fires)
if (!effects.some(e => e.kind === "hit" && e.sources.some(s => s.station === f.station)))
effects.push({ kind: "miss", station: f.station });
}
return effects;
}
export function createResolutionEffects(root, cue) {
const doc = root.ownerDocument;
const win = doc.defaultView;
const reduced = win.matchMedia("(prefers-reduced-motion: reduce)");
const layer = doc.createElement("div");
layer.className = "resolution-effects";
layer.setAttribute("aria-hidden", "true");
root.append(layer);
let previous = null, previousIndex = -1, busyUntil = 0;
let oldPawns = new Map();
const animations = new Set(), timers = new Set(), restores = [];
const q = selector => root.querySelector(selector);
const threat = id => q(`[data-threat="${id}"] .threat-portrait`);
const room = station => q(`[data-station="${station}"]`);
const weapon = station => q(`[data-inspect="system-${station}-A"] > .equipment-art`) ?? room(station);
const art = element => element?.querySelector(":scope > .equipment-art") ?? element;
function point(element) {
if (!element?.getClientRects().length) return null;
const r = element.getBoundingClientRect(), base = layer.getBoundingClientRect();
return { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top, width: r.width, height: r.height };
}
function later(callback, ms) {
const id = win.setTimeout(() => { timers.delete(id); callback(); }, ms);
timers.add(id);
}
function animate(element, frames, duration, delay = 0) {
if (!element?.animate) return;
const animation = element.animate(frames, { duration, delay, easing: "ease-out", fill: "both" });
animations.add(animation);
animation.finished.then(() => { animations.delete(animation); animation.cancel(); }, () => {});
busyUntil = Math.max(busyUntil, performance.now() + duration + delay);
}
function clear() {
for (const id of timers) win.clearTimeout(id);
timers.clear();
for (const animation of animations) animation.cancel();
animations.clear();
for (const restore of restores.splice(0)) restore();
layer.replaceChildren();
busyUntil = 0;
}
function node(name, p, color) {
const element = doc.createElement("span");
element.className = name;
element.style.cssText = `left:${p.x}px;top:${p.y}px;--fx-color:${color}`;
layer.append(element);
return element;
}
function burst(p, color, large = false) {
if (!p) return;
const ring = node("fx-ring", p, color);
animate(ring, [{ transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : .2})`, opacity: .9 },
{ transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : large ? 3 : 1.5})`, opacity: 0 }], large ? 650 : 380);
later(() => ring.remove(), 700);
if (reduced.matches) return;
for (let i = 0; i < (large ? 18 : 7); i++) {
const spark = node("fx-spark", p, color);
const angle = i * 2.39996, distance = (large ? 65 : 26) + (i % 4) * 9;
animate(spark, [{ transform: "translate(-50%,-50%) scale(1)", opacity: 1 },
{ transform: `translate(${Math.cos(angle) * distance}px,${Math.sin(angle) * distance}px) scale(.1)`, opacity: 0 }], large ? 700 : 400);
later(() => spark.remove(), 750);
}
}
function flash(element, color) {
animate(element, [{ boxShadow: `inset 0 0 24px ${color}`, filter: "brightness(1.35)" },
{ boxShadow: "inset 0 0 0 transparent", filter: "brightness(1)" }], 380);
}
function fly(from, to, color, kind = "laser") {
if (!from || !to || reduced.matches) return;
const dx = to.x - from.x, dy = to.y - from.y;
const beam = node(`fx-beam fx-${kind}`, from, color);
beam.style.transform = `rotate(${Math.atan2(dy, dx)}rad)`;
const bolt = doc.createElement("i");
beam.append(bolt);
animate(bolt, [{ transform: "translateX(0)", opacity: 1 },
{ transform: `translateX(${Math.hypot(dx, dy)}px)`, opacity: 1 }], 300);
later(() => beam.remove(), 310);
}
function delta(p, value, color, icon = "") {
if (!p || !value) return;
const n = node("fx-delta", p, color);
n.textContent = `${icon}−${value}`;
animate(n, [{ transform: "translate(-50%,-20%)", opacity: 1 },
{ transform: `translate(-50%,${reduced.matches ? "-20%" : "-140%"})`, opacity: 0 }], 750);
later(() => n.remove(), 760);
}
function deferMarkup(element, oldMarkup, delay) {
if (!element || oldMarkup === undefined) return;
const final = element.innerHTML;
element.innerHTML = oldMarkup;
const restore = () => { element.innerHTML = final; };
restores.push(restore);
later(restore, delay);
}
function play(events, before, after, oldMeters) {
const delay = reduced.matches ? 0 : 310;
const spoken = new Set();
const sound = (kind, p) => {
if (spoken.has(kind)) return;
spoken.add(kind);
cue(kind, p ? Math.max(-.7, Math.min(.7, p.x / Math.max(1, win.innerWidth) * 2 - 1)) : 0);
};
const moved = new Set();
for (const e of events) {
if (e.kind === "move" && !moved.has(e.crew)) {
moved.add(e.crew);
const pawn = q(`[data-crew="${e.crew}"]`), from = oldPawns.get(String(e.crew)), to = point(pawn);
if (!pawn || !from || !to) continue;
sound("move", to);
if (reduced.matches) { flash(room(e.to), "#76e5c660"); continue; }
const clone = pawn.cloneNode(true);
clone.removeAttribute("data-crew");
clone.classList.add("fx-pawn");
clone.style.cssText += `;left:${from.x}px;top:${from.y}px;width:${from.width}px;height:${from.height}px`;
layer.append(clone);
pawn.style.visibility = "hidden";
const restore = () => { pawn.style.visibility = ""; };
restores.push(restore);
const path = events.filter(x => x.kind === "move" && x.crew === e.crew);
const points = [from, ...path.slice(0, -1).map(x => point(room(x.to))).filter(Boolean), to];
animate(clone, points.map(p => ({ transform: `translate(calc(-50% + ${p.x - from.x}px),calc(-50% + ${p.y - from.y}px))` })), 460);
later(() => { restore(); clone.remove(); }, 465);
}
if (e.kind === "charge") {
flash(weapon(e.station), "#8eeaff80");
sound("charge", point(weapon(e.station)));
}
if (e.kind === "miss") {
const from = point(weapon(e.station));
if (from) fly(from, { x: from.x, y: from.y - 100 }, "#8eeaff");
sound("laser-fire", from);
}
if (e.kind === "hit") {
const portrait = threat(e.threat), targetArt = art(portrait), to = point(targetArt);
for (const source of e.sources) fly(point(weapon(source.station)), to, "#8eeaff", source.weapon);
if (e.sources.length) sound("laser-fire", to);
deferMarkup(portrait?.querySelector(".threat-hud"), oldMeters.get(`threat-${e.threat}`), delay);
later(() => {
if (e.shield) { burst(to, "#8eeaff"); flash(portrait?.querySelector(".shield-badge"), "#8eeaff80"); sound("shield-hit", to); }
if (e.damage) {
flash(portrait?.querySelector(".hull-gauge"), "#ffb78090");
burst(to, "#ffca86"); delta(point(portrait?.querySelector(".hull-gauge")), e.damage, "#ffca86");
sound("hull-hit", to);
}
}, delay);
}
if (e.kind === "attack" || e.kind === "direct-damage") {
const portrait = threat(e.threat), from = point(art(portrait));
const station = room(`${e.zone}-upper`), to = point(station);
const impact = after.threats.find(t => t.instance === e.threat)?.positionOnTrack === 1;
fly(from, to, "#ffab7d", impact ? "impact" : "laser");
const meter = station?.querySelector(".energy-system .system-caption");
deferMarkup(meter, oldMeters.get(`shield-${e.zone}`), delay);
deferMarkup(station?.querySelector(".station-title"), oldMeters.get(`damage-${e.zone}`), delay);
later(() => {
if (e.absorbed) { burst(to, "#8eeaff"); flash(station, "#8eeaff60"); delta(point(meter), e.absorbed, "#8eeaff", "⛨"); sound("shield-hit", to); }
if (e.damage) { burst(to, "#ffb780", impact); flash(station, "#ffb78080"); delta(to, e.damage, "#ffb780"); sound(impact ? "explosion" : "hull-hit", to); }
}, delay);
}
if (e.kind === "destroy" || e.kind === "ship-destroy") {
const element = e.kind === "destroy" ? art(threat(e.threat)) : q(".ship-hull");
const p = point(element);
const portrait = e.kind === "destroy" ? threat(e.threat) : null;
const outcome = portrait?.querySelector(".threat-outcome");
if (outcome) { outcome.style.visibility = "hidden"; restores.push(() => { outcome.style.visibility = ""; }); }
// Keep the intact silhouette until the shot lands, then break it apart.
animate(element, [{ opacity: 1, filter: "brightness(1)" }, { opacity: 1, filter: "brightness(1)" }], delay);
later(() => {
if (outcome) outcome.style.visibility = "";
burst(p, "#ffd193", true); sound("explosion", p);
animate(element, [{ opacity: 1, filter: "brightness(2)", transform: "scale(1)" },
{ opacity: .18, filter: "brightness(.6)", transform: reduced.matches ? "scale(1)" : "scale(.82)" }], 650);
}, delay);
}
}
if (events.length) busyUntil = Math.max(busyUntil, performance.now() +
(events.some(e => ["hit", "attack", "direct-damage", "destroy", "ship-destroy"].includes(e.kind)) ? delay + 780 : 480));
}
let oldMeters = new Map();
function beforeRender() {
clear();
oldPawns = new Map([...root.querySelectorAll("[data-crew]")].map(p => [p.dataset.crew, point(p)]));
oldMeters = new Map([...root.querySelectorAll("[data-threat]")].map(p => [`threat-${p.dataset.threat}`, p.querySelector(".threat-hud")?.innerHTML]));
for (const zone of ["red", "white", "blue"]) {
oldMeters.set(`shield-${zone}`, room(`${zone}-upper`)?.querySelector(".energy-system .system-caption")?.innerHTML);
oldMeters.set(`damage-${zone}`, room(`${zone}-upper`)?.querySelector(".station-title")?.innerHTML);
}
}
function afterRender(resolution, index) {
const current = resolution?.frames[index];
if (current && previous && index === previousIndex + 1 && !doc.hidden)
play(resolutionEffects(resolution, previous, current), previous, current, oldMeters);
previous = current;
previousIndex = index;
}
// Moving/resizing the viewport invalidates projectile coordinates.
win.addEventListener("resize", clear);
doc.addEventListener("scroll", clear, true);
const visibility = () => { if (doc.hidden) clear(); };
doc.addEventListener("visibilitychange", visibility);
return {
beforeRender, afterRender,
busy: () => performance.now() < busyUntil,
reset() { clear(); previous = null; previousIndex = -1; },
destroy() {
clear(); layer.remove();
win.removeEventListener("resize", clear);
doc.removeEventListener("scroll", clear, true);
doc.removeEventListener("visibilitychange", visibility);
},
};
}

View file

@ -478,6 +478,8 @@ export function createPreviewServer({ clock = Date.now, storagePath } = {}) {
"/tactical.js": "tactical.js",
"/threat-track.js": "threat-track.js",
"/program-route.js": "program-route.js",
"/resolution-effects.js": "resolution-effects.js",
"/sound.js": "sound.js",
"/i18n.js": "i18n.js",
"/locales/en.json": "locales/en.json",
"/locales/fr.json": "locales/fr.json",

View file

@ -1,6 +1,8 @@
// Short, quiet synthesized cues; no downloads, looping soundtrack or timing authority.
// Short layered effects. Audio follows resolved events and never controls game timing.
export function createSoundDesign() {
let context;
let noise;
const voices = new Set();
let enabled = false;
function enable(value) {
enabled = value;
@ -9,10 +11,70 @@ export function createSoundDesign() {
if (!Audio) return;
context ??= new Audio();
void context.resume().catch(() => {});
} else if (context) void context.suspend().catch(() => {});
} else if (context) {
for (const voice of voices) { try { voice.stop(); } catch {} }
voices.clear();
void context.suspend().catch(() => {});
}
}
function voice({ from = 440, to = from, duration = .2, volume = .035, delay = 0, type = "sine", cutoff = 1400 }, pan) {
const source = type === "noise" ? context.createBufferSource() : context.createOscillator();
if (type === "noise") {
if (!noise) {
noise = context.createBuffer(1, context.sampleRate * 2, context.sampleRate);
const data = noise.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
}
source.buffer = noise;
} else {
source.type = type;
source.frequency.setValueAtTime(from, context.currentTime + delay);
source.frequency.exponentialRampToValueAtTime(Math.max(20, to), context.currentTime + delay + duration);
}
const gain = context.createGain(), filter = context.createBiquadFilter(), stereo = context.createStereoPanner();
const at = context.currentTime + delay;
filter.type = "lowpass";
filter.frequency.setValueAtTime(cutoff, at);
filter.frequency.exponentialRampToValueAtTime(Math.max(80, cutoff * .2), at + duration);
stereo.pan.value = Math.max(-1, Math.min(1, pan));
gain.gain.setValueAtTime(.0001, at);
gain.gain.exponentialRampToValueAtTime(volume, at + .008);
gain.gain.exponentialRampToValueAtTime(.0001, at + duration);
source.connect(filter).connect(gain).connect(stereo).connect(context.destination);
voices.add(source);
source.onended = () => {
voices.delete(source);
source.disconnect(); filter.disconnect(); gain.disconnect(); stereo.disconnect();
};
source.start(at); source.stop(at + duration + .02);
}
function cue(kind, pan = 0) {
if (!enabled || !context || context.state !== "running") return;
const layers = {
move: [
{ from: 180, to: 370, type: "triangle", duration: .22, volume: .018 },
{ type: "noise", cutoff: 700, duration: .15, delay: .2, volume: .025 },
],
charge: [{ from: 150, to: 680, duration: .22, volume: .016 }],
"laser-fire": [
{ from: 1500, to: 160, type: "sawtooth", cutoff: 4200, duration: .22, volume: .045 },
{ from: 2100, to: 440, duration: .15, volume: .022 },
],
"shield-hit": [
{ type: "noise", cutoff: 4800, duration: .18, volume: .055 },
{ from: 920, to: 540, duration: .3, volume: .035 },
],
"hull-hit": [
{ type: "noise", cutoff: 2000, duration: .3, volume: .075 },
{ from: 150, to: 45, type: "triangle", duration: .3, volume: .08 },
],
explosion: [
{ type: "noise", cutoff: 2800, duration: .75, volume: .12 },
{ from: 110, to: 25, duration: .65, volume: .12 },
{ type: "noise", cutoff: 600, delay: .12, duration: .55, volume: .06 },
],
}[kind];
if (layers) { for (const layer of layers) voice(layer, pan); return; }
const notes =
{
select: [[660, 0, 0.045]],
@ -67,7 +129,9 @@ export function createSoundDesign() {
oscillator.connect(gain).connect(stereo).connect(context.destination);
oscillator.start(at);
oscillator.stop(at + duration + 0.02);
voices.add(oscillator);
oscillator.onended = () => {
voices.delete(oscillator);
oscillator.disconnect();
gain.disconnect();
stereo.disconnect();

View file

@ -2556,6 +2556,10 @@ input:not([type="checkbox"]):not([type="range"]) {
.track-turns { margin-top: 4px; align-items: center; text-align: center; font-size: 10px; }
.track-turns > small { grid-column: 1; color: var(--muted); font-size: 8px; }
.track-turns > span { padding: 2px 0; border-radius: 2px; border-bottom: 2px solid; }
.track-turns .pictogram { width: 12px; height: 12px; vertical-align: middle; }
.program-jump { grid-column: 1 / -1; flex-basis: 100%; display: flex; align-items: center; gap: 8px; padding: 8px 0; color: var(--muted); font-size: 12px; }
.program-jump.current { color: var(--gold); }
.program-jump .pictogram { width: 18px; height: 18px; }
.track-turns .forecast-tone-0 { color: #acf0e5; border-color: #72c9bb; background: #264d5580; }
.track-turns .forecast-tone-1 { color: #c0d5fa; border-color: #87a9e1; background: #30405c80; }
@ -2598,3 +2602,15 @@ input:not([type="checkbox"]):not([type="range"]) {
.planned-pawn > svg { width: 32px; height: 32px; }
.planned-pawn b, .planned-pawn small { font-size: 10px; }
.planned-pawn small { padding: 2px 3px; border: 1px dashed currentColor; border-radius: 3px; }
/* Resolution effects sit above the board without taking layout space or input. */
.resolution-effects { position: fixed; inset: 0; z-index: 80; pointer-events: none; overflow: hidden; }
.resolution-effects > span { position: absolute; pointer-events: none; }
.resolution-effects .fx-pawn { z-index: 2; margin: 0; filter: drop-shadow(0 0 8px #91e7ed90); }
.fx-beam { width: 0; height: 0; transform-origin: 0 0; }
.fx-beam i { position: absolute; right: 0; top: -2px; width: 46px; height: 4px; border-radius: 50%; background: linear-gradient(90deg,transparent,var(--fx-color),#fff); box-shadow: 0 0 9px var(--fx-color); }
.fx-pulse i { width: 24px; height: 24px; top: -12px; border: 2px solid var(--fx-color); background: #8eeaff40; border-radius: 50%; }
.fx-rocket i,.fx-impact i { width: 20px; height: 10px; top: -5px; }
.fx-ring { width: 52px; height: 52px; border: 2px solid var(--fx-color); border-radius: 50%; box-shadow: inset 0 0 20px var(--fx-color),0 0 12px var(--fx-color); }
.fx-spark { width: 5px; height: 5px; border-radius: 50%; background: var(--fx-color); box-shadow: 0 0 7px var(--fx-color); }
.fx-delta { color: var(--fx-color); font-size: 24px; font-weight: 800; text-shadow: 0 2px 4px #020a10,0 0 8px #020a10; white-space: nowrap; }

View file

@ -125,7 +125,7 @@ export function createTacticalView({
level === "upper"
? t("tactical.upper_deck")
: t("tactical.lower_deck");
return `<section class="station ${occupants.some((p) => p.id === selectedCrew) ? "selected-station" : ""}" data-station="${station}" style="--zone:var(--${zone})" aria-label="${esc(zoneName(zone))} · ${deckName}"><div class="station-title">${level === "upper" && s.damage.length ? `<span class="damage">${symbol("warning", `${t("tactical.zone_damage")} : ${s.damage.length}/6`, `${s.damage.length}/6`)}</span>` : ""}</div>${stationControls({ station, zone, deck: level, ship, power, capacity, system, cIcon, c, canPlan })}<div class="occupants">${occupants.map((p) => `<span style="${playerColor(p.id) ? `--player-color:${playerColor(p.id)};--player-stroke:#c4d4e0` : ""}" class="crew-pawn ${p.id === selectedCrew ? "selected" : ""} ${p.knockedOut ? "out" : ""}" role="img" title="${esc(crewLabel(p.id))}${p.knockedOut ? " · " + t("tactical.knocked_out") : ""}${p.bots !== null ? " · " + t("app.battlebots") : ""}" aria-label="${esc(crewLabel(p.id))}${p.knockedOut ? " · " + t("tactical.knocked_out") : ""}${p.bots !== null ? " · " + t("app.battlebots") : ""}">${isAndroid(p.id) ? equipmentPicture("android") : pictogram("crew")}<b>${p.id + 1}</b>${p.bots !== null ? `<i>${pictogram("bots")}</i>` : ""}</span>`).join("")}</div></section>`;
return `<section class="station ${occupants.some((p) => p.id === selectedCrew) ? "selected-station" : ""}" data-station="${station}" style="--zone:var(--${zone})" aria-label="${esc(zoneName(zone))} · ${deckName}"><div class="station-title">${level === "upper" && s.damage.length ? `<span class="damage">${symbol("warning", `${t("tactical.zone_damage")} : ${s.damage.length}/6`, `${s.damage.length}/6`)}</span>` : ""}</div>${stationControls({ station, zone, deck: level, ship, power, capacity, system, cIcon, c, canPlan })}<div class="occupants">${occupants.map((p) => `<span style="${playerColor(p.id) ? `--player-color:${playerColor(p.id)};--player-stroke:#c4d4e0` : ""}" data-crew="${p.id}" class="crew-pawn ${p.id === selectedCrew ? "selected" : ""} ${p.knockedOut ? "out" : ""}" role="img" title="${esc(crewLabel(p.id))}${p.knockedOut ? " · " + t("tactical.knocked_out") : ""}${p.bots !== null ? " · " + t("app.battlebots") : ""}" aria-label="${esc(crewLabel(p.id))}${p.knockedOut ? " · " + t("tactical.knocked_out") : ""}${p.bots !== null ? " · " + t("app.battlebots") : ""}">${isAndroid(p.id) ? equipmentPicture("android") : pictogram("crew")}<b>${p.id + 1}</b>${p.bots !== null ? `<i>${pictogram("bots")}</i>` : ""}</span>`).join("")}</div></section>`;
})
.join(
"",
@ -137,11 +137,15 @@ export function createTacticalView({
const hp = Math.max(0, th.hp - (th.damage ?? 0));
const pending = ["pending", "announced", "waiting"].includes(th.status);
const gone = ["destroyed", "survived", "discarded"].includes(th.status);
const impacted = th.positionOnTrack === 1 && th.effects?.Z?.some(
(effect) => effect.type === "attack" &&
["hp", "double-hp", "triple-hp"].includes(effect.amount),
);
const status =
th.status === "destroyed"
? t("tactical.destroyed")
: th.status === "survived"
? t("tactical.escaped")
? t(impacted ? "tactical.impact" : "tactical.escaped")
: th.status === "discarded"
? t("tactical.discarded")
: null;

View file

@ -1,6 +1,7 @@
// Display-only forecast from public threat state. No planned crew actions are read.
// Preserve the real distance spaces: each group is one upcoming movement step.
export function forecastMovement(threat, track, context = {}) {
if (context.outcome) return [];
const pending = !threat.status || ["pending", "announced", "waiting"].includes(threat.status);
if (!pending && threat.status !== "active") return [];
if (!Number.isFinite(threat.speed) || threat.speed <= 0) return [];
@ -18,7 +19,7 @@ export function forecastMovement(threat, track, context = {}) {
t.damage ??= 0;
let position = pending ? track.length : t.positionOnTrack;
const groups = [];
for (; position > 1 && groups.length < 24; turn++) {
for (; position > 1 && groups.length < 24 && turn <= (context.finalTurn ?? Infinity); turn++) {
// Changes crossed this turn affect the NEXT movement, just as in the resolver.
const speed = Math.max(0, t.speed);
if (!speed) break;

View file

@ -265,11 +265,13 @@ export async function createLessonTutorial(
title: t("tutorial_controller.exercise_complete"),
text: lesson.basics
? t("timing.complete")
: id === "first-shot"
? t("tutorial_controller.target_destroyed")
: t(
"tutorial_controller.replay_to_compare_another_program_or_move_on",
),
: lesson.phaseLesson
? t("phases.complete")
: id === "first-shot"
? t("tutorial_controller.target_destroyed")
: t(
"tutorial_controller.replay_to_compare_another_program_or_move_on",
),
},
});
}

View file

@ -3,6 +3,33 @@ import test from "node:test";
import { once } from "node:events";
import { createPreviewServer } from "../preview/server.js";
test("local console serves the full module graph including shared animation and sound", async () => {
const server = createPreviewServer();
server.listen(0, "127.0.0.1");
await once(server, "listening");
const pending = [`http://127.0.0.1:${server.address().port}/local.js`];
const seen = new Set();
try {
while (pending.length) {
const url = pending.pop();
if (seen.has(url)) continue;
seen.add(url);
const response = await fetch(url);
assert.equal(response.status, 200, url);
assert.match(response.headers.get("content-type"), /javascript/, url);
const source = await response.text();
for (const match of source.matchAll(/(?:from\s+|import\s*)["'](\.[^"']+)["']/g))
pending.push(new URL(match[1], url).href);
}
assert.ok([...seen].some(url => url.endsWith("/resolution-effects.js")));
assert.ok([...seen].some(url => url.endsWith("/sound.js")));
} finally {
server.close();
server.closeAllConnections();
await once(server, "close");
}
});
test("local host shares state across seats and commits deadline changes on rejected requests", async () => {
let now = 1_000_000;
const server = createPreviewServer({ clock: () => now });

View file

@ -0,0 +1,69 @@
import test from "node:test";
import assert from "node:assert/strict";
import { beginResolution, stepResolution } from "../src/game/resolution.js";
import { TRACKS } from "../src/game/catalog.js";
import { resolutionEffects } from "../preview/resolution-effects.js";
function mission(program, threats = []) {
return beginResolution({ crewSize: 1, seed: "effects", turns: 7,
programs: [Array.from({ length: 7 }, (_, i) => program[i] ? { actions: program[i] } : null)], threats,
tracks: Object.fromEntries(["red", "white", "blue", "internal"].map(z => [z, TRACKS[6]])) });
}
function next(r) {
const result = stepResolution(r);
return [result, resolutionEffects(result, r.frames.at(-1), result.frames.at(-1))];
}
test("movement effects follow actual movement; duplicate snapshots and initial loads are silent", () => {
let r = mission([["blue"], ["lift"]]);
let events;
[r] = next(r);
[r, events] = next(r);
assert.deepEqual(events.map(e => [e.kind, e.from, e.to]), [["move", "white-upper", "blue-upper"]]);
assert.deepEqual(resolutionEffects(r, r.frames.at(-1), r.frames.at(-1)), []);
assert.deepEqual(resolutionEffects(r, null, r.frames.at(-1)), []);
});
test("lasers use actual hit targets; health and destruction come from damage resolution", () => {
let r = mission([["A"], ["A"]], [{ cardId: "E1-07", turn: 1, zone: "white" }]);
let events;
[r] = next(r);
[r, events] = next(r);
assert.equal(events[0].kind, "charge");
assert.equal(events[0].station, "white-upper");
[r, events] = next(r);
const hit = events.find(e => e.kind === "hit");
assert.equal(hit.threat, 0);
assert.deepEqual(hit.sources, [{ station: "white-upper", weapon: "laser" }]);
assert.equal(hit.shield, 2);
assert.equal(hit.damage, 3);
assert.equal(r.threats[0].shield, 2, "enemy shield rating is not consumed");
assert.ok(!events.some(e => e.kind === "destroy"));
while (!(r.turn === 2 && r.step === "damage")) [r] = next(r);
[r, events] = next(r);
assert.deepEqual(events.map(e => e.kind), ["hit", "destroy"]);
});
test("firing before arrival or into another lane is a miss, never a fabricated hit", () => {
for (const threat of [{ cardId: "E1-07", turn: 2, zone: "white" }, { cardId: "E1-07", turn: 1, zone: "blue" }]) {
let r = mission([["A"]], [threat]);
while (r.step !== "damage") [r] = next(r);
const [resolved, events] = next(r);
assert.deepEqual(events, [{ kind: "miss", station: "white-upper" }]);
assert.equal(resolved.threats[0].damage, 0);
}
});
test("meteoroid impact reports shield absorption and hull damage once", () => {
let r = mission(Array(7).fill(null), [{ cardId: "E1-10", turn: 6, zone: "white" }]);
let effects = [];
while (!r.outcome) {
const [result, events] = next(r);
effects.push(...events); r = result;
}
const attack = effects.filter(e => e.kind === "attack");
assert.equal(attack.length, 1);
assert.equal(attack[0].absorbed, 1);
assert.equal(attack[0].damage, 4);
assert.ok(!effects.some(e => e.kind === "direct-damage" || e.kind === "destroy"));
});

54
test/sound.test.js Normal file
View file

@ -0,0 +1,54 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createSoundDesign } from "../preview/sound.js";
test("combat cues have distinct layers, mute stops active sounds, and re-enabling resumes audio", () => {
const nodes = [];
const parameter = () => ({ value: 0, setValueAtTime() {}, linearRampToValueAtTime() {}, exponentialRampToValueAtTime() {} });
const node = () => {
const n = { frequency: parameter(), gain: parameter(), pan: parameter(),
connect() { return this; }, disconnect() {},
start() { this.started = true; }, stop() { this.stops = (this.stops ?? 0) + 1; } };
nodes.push(n); return n;
};
let context;
class AudioContext {
constructor() { context = this; this.state = "suspended"; this.currentTime = 0; this.sampleRate = 8000; }
resume() { this.state = "running"; return Promise.resolve(); }
suspend() { this.state = "suspended"; return Promise.resolve(); }
close() { this.state = "closed"; return Promise.resolve(); }
createBuffer(channels, size) { return { getChannelData: () => new Float32Array(size) }; }
createBufferSource = node;
createOscillator = node;
createGain = node;
createBiquadFilter = node;
createStereoPanner = node;
}
const original = globalThis.window;
globalThis.window = { AudioContext };
const sound = createSoundDesign();
try {
sound.cue("laser-fire");
assert.equal(nodes.length, 0, "no audio before opt-in/gesture");
sound.enable(true);
const counts = [];
for (const kind of ["move", "charge", "laser-fire", "shield-hit", "hull-hit", "explosion"]) {
const before = nodes.filter(n => n.started).length;
sound.cue(kind, .5);
counts.push(nodes.filter(n => n.started).length - before);
}
assert.ok(counts.every(n => n > 0));
assert.ok(counts[5] > counts[1], "destruction has a richer tail than charging");
sound.enable(false);
assert.equal(context.state, "suspended");
assert.ok(nodes.filter(n => n.started).every(n => n.stops === 2), "mute cancels even scheduled voices");
const length = nodes.length;
sound.cue("explosion");
assert.equal(nodes.length, length, "muted events do not queue audio");
sound.enable(true);
sound.cue("place");
assert.ok(nodes.length > length);
sound.destroy();
assert.equal(context.state, "closed");
} finally { globalThis.window = original; }
});

View file

@ -3,6 +3,8 @@ import assert from "node:assert/strict";
import { forecastMovement, checkpointAppearance } from "../preview/threat-track.js";
import { THREATS, TRACKS } from "../src/game/catalog.js";
import { beginResolution, stepResolution } from "../src/game/resolution.js";
import { createTacticalView } from "../preview/tactical.js";
import { loadLocale, translate } from "../preview/i18n.js";
function scenario(id) {
return beginResolution({ crewSize: 4, seed: "track-forecast", programs: Array.from({ length: 4 }, () => Array(12).fill(null)),
@ -69,3 +71,28 @@ test("meteoroid empty checkpoints have no symbols and impact follows remaining h
meteor.damage = 3;
assert.deepEqual(checkpointAppearance(meteor, meteor.effects.Z), { icon: "impact", value: 2 });
});
test("a seven-turn mission includes the final threat movement, reports impact, and forecasts no later turns", async () => {
let r = beginResolution({
crewSize: 1, seed: "final-movement", turns: 7,
programs: [Array(7).fill(null)],
threats: [{ cardId: "E1-10", turn: 6, zone: "white" }],
tracks: Object.fromEntries(["red", "white", "blue", "internal"].map(zone => [zone, TRACKS[6]])),
});
assert.deepEqual(forecastMovement(r.threats[0], TRACKS[6], r).map(g => g.turn), [6, 7, 8]);
const lateFighter = { ...THREATS.find(t => t.id === "E1-07"), turn: 8 };
assert.deepEqual(forecastMovement(lateFighter, TRACKS[6], r).map(g => g.turn), [8]);
while (!r.outcome) r = stepResolution(r);
const hit = r.log.find(e => e.type === "attack");
assert.equal(hit.turn, 8);
assert.equal(hit.absorbed, 1);
assert.equal(hit.damage, 4);
assert.deepEqual(forecastMovement(r.threats[0], TRACKS[6], r), []);
await loadLocale("en");
const { threatPortrait } = createTacticalView({
t: (key) => translate("en", key), esc: String, symbol: () => "", zoneName: String,
});
const portrait = threatPortrait(r.threats[0]);
assert.match(portrait, /class="threat-outcome">Impact</);
assert.doesNotMatch(portrait, /Escaped/);
});