${threatPortrait(th)}${symbol("speed", `${th.speed} ${t("app.spaces_per_turn")}`, th.speed)}
${th.position === "internal" ? esc(th.stations.map((s) => stationLabel(s, locale)).join(", ")) + " · " + esc(label(th.repair)) : esc(zoneName(th.zone))}
${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 ``;
+ 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 ``;
})
.join("");
+ if (!basic && !firstShot) {
+ const lastTurn = resolution?.lastTurn ?? (view.mission.phaseEndsMs.length === 2 ? 7 : 12);
+ const jumping = activeTurn > lastTurn;
+ $("#program").insertAdjacentHTML("beforeend",
+ `${pictogram("ship")}${t("app.jump")}${resolution?.outcome?.survived ? pictogram("check") : ""}
`);
+ }
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"
- ? ``
+ ? ``
: view.stage === "cancelled"
? '"
: "";
@@ -677,13 +693,13 @@ export function mountConsole(root, host = null) {
.join("")
: "";
$("#replay").innerHTML = resolution
- ? `${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : ${resolution.outcome.score} · ${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])}`}
${replayFrame !== null ? '" : ""}`
+ ? `${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : ${resolution.outcome.score} · ${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])}`}
${replayFrame !== null ? '" : ""}`
: "";
renderCampaign(g?.campaign);
$("#announcements").innerHTML = resolution
? resolution.log
.filter((_, i) => !frame || i < frame.logEnd)
- .map((e) => `T${e.turn} · ${esc(logText(e))}`)
+ .map((e) => `${e.turn > resolution.lastTurn ? t("app.jump") : `${t("app.turn")} ${e.turn}`} · ${esc(logText(e))}`)
.join("")
: announcements
.map(
@@ -716,6 +732,7 @@ export function mountConsole(root, host = null) {
`${t("app.left_center_and_right_correspond_to_red_white")}
` +
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 `${appearance ? `${pictogram(appearance.icon)}${esc(appearance.value)}` : current ? "●" : ""}`;
})
.join(
"",
- )}${groups.length ? `T${groups.map((group, i) => `${group.turn}`).join("")}
` : ""}${pictogram("ship")}`;
+ )}${groups.length ? `${t("app.turn")}${groups.map((group, i) => `${group.turn === finalTurn ? pictogram("ship") : group.turn}`).join("")}
` : ""}${pictogram("ship")}`;
}
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();
diff --git a/preview/basics.js b/preview/basics.js
index bb7ec3b..f50c3d8 100644
--- a/preview/basics.js
+++ b/preview/basics.js
@@ -68,7 +68,7 @@ export function basicsView(view, locale, { started, picked, shipMarkup }) {
${
intro
? btn("basics-start", t("basics.try_with_two_cards"))
- : `${pictogram("cards")}${t("basics.program")}${pictogram("right")}
${[1, 2, 3].map((n) => ``).join("")}
+ : `${pictogram("cards")}${t("basics.program")}${pictogram("right")}
${[1, 2, 3].map((n) => ``).join("")}
${!playing ? `${pictogram("cards")} ${placed}/2 ${["red", "blue"].map((action) => ``).join("")}
` : ""}
${!playing && ready ? `${practiceClockText(view, locale)}${t("basics.to_plan_safe_practice")}
` : ""}
${playing ? (turn < 3 ? `` : `${t("basics.planning_against_a_clock_and_carrying_out_turns")}
`) : ""}`
diff --git a/preview/locales/en.json b/preview/locales/en.json
index deff66b..6861b14 100644
--- a/preview/locales/en.json
+++ b/preview/locales/en.json
@@ -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."
}
diff --git a/preview/locales/fr.json b/preview/locales/fr.json
index 7d920f7..cb133ce 100644
--- a/preview/locales/fr.json
+++ b/preview/locales/fr.json
@@ -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é."
}
diff --git a/preview/resolution-effects.js b/preview/resolution-effects.js
new file mode 100644
index 0000000..702a008
--- /dev/null
+++ b/preview/resolution-effects.js
@@ -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);
+ },
+ };
+}
diff --git a/preview/server.js b/preview/server.js
index e807acd..bf407ba 100644
--- a/preview/server.js
+++ b/preview/server.js
@@ -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",
diff --git a/preview/sound.js b/preview/sound.js
index 5028156..5487809 100644
--- a/preview/sound.js
+++ b/preview/sound.js
@@ -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();
diff --git a/preview/style.css b/preview/style.css
index bdc14b5..596e53d 100644
--- a/preview/style.css
+++ b/preview/style.css
@@ -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; }
diff --git a/preview/tactical.js b/preview/tactical.js
index 2549965..749b648 100644
--- a/preview/tactical.js
+++ b/preview/tactical.js
@@ -125,7 +125,7 @@ export function createTacticalView({
level === "upper"
? t("tactical.upper_deck")
: t("tactical.lower_deck");
- return `${level === "upper" && s.damage.length ? `${symbol("warning", `${t("tactical.zone_damage")} : ${s.damage.length}/6`, `${s.damage.length}/6`)}` : ""}
${stationControls({ station, zone, deck: level, ship, power, capacity, system, cIcon, c, canPlan })}${occupants.map((p) => `${isAndroid(p.id) ? equipmentPicture("android") : pictogram("crew")}${p.id + 1}${p.bots !== null ? `${pictogram("bots")}` : ""}`).join("")}
`;
+ return `${level === "upper" && s.damage.length ? `${symbol("warning", `${t("tactical.zone_damage")} : ${s.damage.length}/6`, `${s.damage.length}/6`)}` : ""}
${stationControls({ station, zone, deck: level, ship, power, capacity, system, cIcon, c, canPlan })}${occupants.map((p) => `${isAndroid(p.id) ? equipmentPicture("android") : pictogram("crew")}${p.id + 1}${p.bots !== null ? `${pictogram("bots")}` : ""}`).join("")}
`;
})
.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;
diff --git a/preview/threat-track.js b/preview/threat-track.js
index 8ccb84b..0f4c161 100644
--- a/preview/threat-track.js
+++ b/preview/threat-track.js
@@ -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;
diff --git a/src/tutorial-controller.js b/src/tutorial-controller.js
index b9a42cb..de1c4d3 100644
--- a/src/tutorial-controller.js
+++ b/src/tutorial-controller.js
@@ -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",
+ ),
},
});
}
diff --git a/test/preview.test.js b/test/preview.test.js
index a488b4d..887cc02 100644
--- a/test/preview.test.js
+++ b/test/preview.test.js
@@ -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 });
diff --git a/test/resolution-effects.test.js b/test/resolution-effects.test.js
new file mode 100644
index 0000000..695dea9
--- /dev/null
+++ b/test/resolution-effects.test.js
@@ -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"));
+});
diff --git a/test/sound.test.js b/test/sound.test.js
new file mode 100644
index 0000000..62b3cf9
--- /dev/null
+++ b/test/sound.test.js
@@ -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; }
+});
diff --git a/test/threat-track.test.js b/test/threat-track.test.js
index 881040b..18f69c6 100644
--- a/test/threat-track.test.js
+++ b/test/threat-track.test.js
@@ -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/);
+});