From 3de2e364dc67dee47cf44d530f7cb426bc540a64 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 5 Nov 2026 21:18:03 +0000 Subject: [PATCH] Improve tutorial guidance and add viewer replay controls --- README.md | 2 + bgs/tutorial.js | 9 ++- preview/app.js | 62 +++++++++++++++++-- preview/basics.js | 4 +- preview/locales/en.json | 11 ++-- preview/locales/fr.json | 11 ++-- preview/replay.js | 27 ++++++++ preview/resolution-effects.js | 3 + preview/server.js | 1 + preview/style.css | 37 +++++++++-- preview/tutorial-program.js | 37 +++++++++++ test/replay.test.js | 112 ++++++++++++++++++++++++++++++++++ test/tutorial-program.test.js | 84 +++++++++++++++++++++++++ 13 files changed, 377 insertions(+), 23 deletions(-) create mode 100644 preview/replay.js create mode 100644 preview/tutorial-program.js create mode 100644 test/replay.test.js create mode 100644 test/tutorial-program.test.js diff --git a/README.md b/README.md index ab141fe..3a53e09 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ Open . Start with **Flight school / École de vol**: nine For a full mission, expand **Local session / Session locale**. Select 1–5 humans, the crew, mission, threat pools and optional modules. In solo, you control four androids and have access to the full action deck. In multiplayer testing, open another tab with `?seat=1`, etc. Readiness lasts two minutes; everyone must be ready together. The local mission starts after a three-second countdown. If someone misses the window, the crew keeps waiting. Click a card half to fill the highlighted turn; the cursor advances afterward. Click any editable turn to select it, including a filled turn to replace its card. W leaves a wait and advances; Backspace clears the selected turn, or steps back if it is empty. The hourglass and erase buttons provide the same controls with a mouse or touch. Left/right arrow keys queue horizontal movement; up/down queue a deck change, using an available card. Typing in fields is unaffected. Shift-click or Combine retains multi-card selection; then choose a turn. Advance individual phases to lock previous turns, or let the shared clock do so. After programming, the captain can resolve one step at a time or finish the mission; everyone can inspect the replay and log. +During resolution or after completion, **Review a step** selects an already-resolved frame. **Play replay** animates consecutive frames from that selection (or restarts at the beginning when viewing the latest frame); **Pause replay** stops playback. **Jump to latest state** skips straight back without replaying animations. These viewer-only controls work in tutorials and full missions, never resolve new steps, and do not alter the mission clock. Playback stops at the last frame available when it began, even if another player resolves further steps meanwhile. + Training starts with its clock paused. **Start practice clock** and **Pause clock** control time only in training; normal missions retain their shared, continuous clock. You can also advance lesson phases explicitly. The local seat selector, “Ready all” and “Next announcement” buttons are development tools. This host has **no authentication** and deliberately listens only on `127.0.0.1`. It is not an online multiplayer deployment. Use external voice for cooperation; mission announcements are visual, with sound effects for game actions. Communications-blackout silence relies on the players. diff --git a/bgs/tutorial.js b/bgs/tutorial.js index df9a65a..c9417d9 100644 --- a/bgs/tutorial.js +++ b/bgs/tutorial.js @@ -7,6 +7,7 @@ import { LESSONS } from "../src/tutorials.js"; import { snapshot } from "../src/view.js"; import { mountConsole } from "../preview/app.js"; import { pictogram } from "../preview/icons.js"; +import { tutorialPhaseButton } from "../preview/tutorial-program.js"; import { duration, practiceClockText } from "../preview/clock.js"; import { createSoundDesign } from "../preview/sound.js"; import html from "../preview/index.html"; @@ -195,6 +196,10 @@ export async function mountLesson( .join("")}${pictogram("step")}`; } function renderGuide(s) { + // Put planning decisions beside the program tools, without moving playback. + if (s.state.stage === 'programming') + target.querySelector('#selection-tools').before(programControls); + else target.querySelector('#hand').after(programControls); const planned = s.state.game.programs[0].some( (slot) => slot?.cards?.length, ); @@ -210,7 +215,7 @@ export async function mountLesson( s.step === 2 && completedTurns(s.state) >= 3 && !s.completed; - programControls.innerHTML = `${chapter === "basics" && s.step === 3 ? `` : ""}${canPlay(s) ? transport("playback", playing ? "pause" : "right", playing ? t("basics.pause") : t("tutorial.play_program")) : ""}${!LESSONS[index].basics && chapter !== "first-shot" && s.step === 1 && s.state.phase === 1 ? transport("phase", "lock", t("tutorial.lock_phase", { phase: 1 }), s.busy) : ""}${!LESSONS[index].basics && s.step === 1 && (chapter !== "energy" || s.state.phase === 2) ? `` : ""}`; + programControls.innerHTML = `${chapter === "basics" && s.step === 3 ? `` : ""}${canPlay(s) ? transport("playback", playing ? "pause" : "right", playing ? t("basics.pause") : t("tutorial.play_program")) : ""}${!LESSONS[index].basics && chapter !== "first-shot" && s.step === 1 && s.state.phase === 1 ? tutorialPhaseButton(s.state, locale, s.busy) : ""}${!LESSONS[index].basics && s.step === 1 && (chapter !== "energy" || s.state.phase === 2) ? `` : ""}`; if (phaseLesson && s.state.stage === "programming" && s.step > 0) { const ready = s.state.game.programs[0][(s.state.phase === 1 ? 1 : 4) - 1]?.cards @@ -220,7 +225,7 @@ export async function mountLesson( s.state.mission.phaseEndsMs[s.state.phase - 1] - s.state.observedAt, ); - programControls.innerHTML = `
${s.state.phase === 1 ? transport("phase-deadline", "forward", t("phases.skip"), !ready || !s.state.game.threats.length || s.busy) : ``}
${t("phases.deadline", { phase: s.state.phase, time: phaseTime })}${t("phases.total")} · ${practiceClockText(s.state, locale)}
${transport("phase-clock", s.state.tutorial.clockRunning ? "pause" : "clock", t(s.state.tutorial.clockRunning ? "basics.pause" : "basics.start_clock"))}
`; + programControls.innerHTML = `
${s.state.phase === 1 ? transport("phase-deadline", "forward", t("phases.skip"), !ready || !s.state.game.threats.length || s.busy) : ``}
${t("phases.deadline", { phase: s.state.phase, time: phaseTime })}${t("phases.total")} · ${practiceClockText(s.state, locale)}
${transport("phase-clock", s.state.tutorial.clockRunning ? "pause" : "clock", t(s.state.tutorial.clockRunning ? "basics.pause" : "basics.start_clock"))}
`; } guide.innerHTML = `
${standalone ? `${t("tutorial.local_game")}` : ""}${transport("sound", soundOn ? "speaker" : "muted", soundOn ? t("tutorial.mute_sounds") : t("tutorial.enable_sounds"))}

${escape(s.title)}

${s.step === 0 && (chapter === "basics" || phaseLesson) ? missionOverview() : ""}${["basics", "first-shot", "energy"].includes(chapter) ? `${t("timing.exercise", { turns: chapter === "energy" ? 4 : 3 })}${chapter === "basics" ? ` · ${deadline ? 2 : 1}/2` : ""}` : ""}

${escape(missed ? t("tutorial.destination_missed_go_back_and_plan_another_route") : s.text)}

${chapter === "first-shot" && s.step < 2 ? `

${pictogram("shield")}${t("lesson.first-shot.shield")}

` : ""} diff --git a/preview/app.js b/preview/app.js index 3294db1..39d0a6d 100644 --- a/preview/app.js +++ b/preview/app.js @@ -1,3 +1,4 @@ +import { createReplay } from "./replay.js"; import { createResolutionEffects } from "./resolution-effects.js"; import { createSoundDesign } from "./sound.js"; import { plannedRoute } from "./program-route.js"; @@ -70,6 +71,17 @@ export function mountConsole(root, host = null) { root.ownerDocument.addEventListener("keydown", unlockSound, true); const effects = createResolutionEffects(root, cue); let autoResolve = false; + const replay = createReplay({ + index: () => replayFrame, + count: () => view?.game?.resolution?.frames.length ?? 0, + show: (index) => { replayFrame = index; rerender(); }, + busy: () => effects.busy() || root.ownerDocument.hidden, + }); + intervals.push(setInterval(() => { + const wasPlaying = replay.playing; + replay.tick(); + if (wasPlaying && !replay.playing) rerender(); + }, 100)); const t = (key, params) => translate(locale, key, params); const actionWords = (text) => text.replace( @@ -313,8 +325,14 @@ export function mountConsole(root, host = null) { showPlannedPosition(next ? Number(next.dataset.turn) : null); }); function render(next, force = false) { + if (!next.game?.resolution || (replayFrame !== null && + replayFrame >= next.game.resolution.frames.length)) { + replay.pause(); + effects.reset(); + replayFrame = null; + } view = next; - received = performance.now(); + if (!force) received = performance.now(); const newKey = `${view.revision}/${seat}/${locale}`; renderCareers(next); if (!force && key === newKey) return; @@ -583,7 +601,7 @@ export function mountConsole(root, host = null) { $("#player-help").textContent = planning ? selected.length ? t("app.choose_a_turn_for_this_card") - : t("app.click_a_card_to_fill_the_next_turn") + : "" : view.stage === "presence" ? t("app.ready_lasts_two_minutes_we_wait_until_everyone") : view.stage === "resolution" @@ -603,7 +621,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" ? '" : ""; @@ -728,7 +746,7 @@ 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")}` : 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 ? '" : ""}` + ? `

${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 @@ -1028,6 +1046,7 @@ export function mountConsole(root, host = null) { }); }); async function command(type, extra = {}, target = seat) { + if (replayFrame !== null) return; // Reviewing never sends engine commands. if (host) { if (target !== seat || seat < 0) throw Error("Only your own seat can send commands"); @@ -1300,6 +1319,8 @@ export function mountConsole(root, host = null) { seat = 0; crew = 0; selected = []; + replay.pause(); + effects.reset(); replayFrame = null; basicsStarted = false; basicsPicked = false; @@ -1353,6 +1374,8 @@ export function mountConsole(root, host = null) { } if (el.id === "campaign-next") { perform(async () => { + replay.pause(); + effects.reset(); replayFrame = null; selected = []; await localPost("/api/campaign-next", { @@ -1460,6 +1483,7 @@ export function mountConsole(root, host = null) { else { cue('select'); rerender(); } return; } + if (el.dataset.command && replayFrame !== null) return; if (el.dataset.command === "resolve-all") { autoResolve = !autoResolve; rerender(); @@ -1521,7 +1545,18 @@ export function mountConsole(root, host = null) { }).then((r) => r.json()); render(result); }); + if (el.id === "replay-play") { + autoResolve = false; + if (replay.playing) replay.pause(); + else { + effects.reset(); // Establish a silent starting frame, then animate adjacent frames. + replay.play(); + } + rerender(); + } if (el.id === "live") { + replay.pause(); + effects.reset(); replayFrame = null; rerender(); } @@ -1539,8 +1574,20 @@ export function mountConsole(root, host = null) { selected = []; rerender(); }); + // Stop immediately while dragging; commit the selected frame on change so + // rendering does not replace the range input underneath the pointer. + listenRoot("input", (e) => { + if (e.target.id === "replay-slider") { + replay.pause(); + autoResolve = false; + effects.reset(); + } + }); listenRoot("change", (e) => { if (e.target.id === "replay-slider") { + replay.pause(); + autoResolve = false; + effects.reset(); replayFrame = Number(e.target.value); rerender(); } @@ -1590,6 +1637,8 @@ export function mountConsole(root, host = null) { }); const next = await res.json(); if (!res.ok) throw Error(next.error); + replay.pause(); + effects.reset(); replayFrame = null; selected = []; crew = seat; @@ -1665,7 +1714,7 @@ export function mountConsole(root, host = null) { })(); } return { - isAnimating: () => effects.busy(), + isAnimating: () => effects.busy() || replayFrame !== null, resetTutorial() { previewTurn = null; cursor.reset(); @@ -1673,6 +1722,8 @@ export function mountConsole(root, host = null) { basicsPicked = false; basicsStarted = false; selected = []; + replay.pause(); + effects.reset(); replayFrame = null; key = ""; }, @@ -1708,6 +1759,7 @@ export function mountConsole(root, host = null) { rerender(); }, destroy() { + replay.pause(); effects.destroy(); audio?.destroy(); root.ownerDocument.removeEventListener("pointerdown", unlockSound, true); diff --git a/preview/basics.js b/preview/basics.js index 8a88d6b..44c0730 100644 --- a/preview/basics.js +++ b/preview/basics.js @@ -11,7 +11,7 @@ export function basicsView(view, locale, { started, picked, shipMarkup }) { const playing = view.stage === "resolution"; if (view.tutorial.nativeStep !== undefined) { const control = (id, glyph, description, disabled = false) => - ``; + ``; if (view.tutorial.nativeStep === 0) return ""; if (playing) return view.tutorial.timing @@ -70,7 +70,7 @@ export function basicsView(view, locale, { started, picked, shipMarkup }) { ? btn("basics-start", t("basics.try_with_two_cards")) : `
${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 && 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 6a2d1be..80627f8 100644 --- a/preview/locales/en.json +++ b/preview/locales/en.json @@ -5,11 +5,11 @@ "lesson.first-shot.lane": "Center lane", "lesson.first-shot.shield": "The center shield absorbs hits automatically while charged.", "lesson.energy.title": "Energy and coordination", - "lesson.energy.instruction.0": "The center laser needs one energy per shot. Its reactor starts with three: refill it to fire four times.", + "lesson.energy.instruction.0": "The center laser needs one energy per shot. Its reactor starts with three: refill it to fire four times. One refill uses a fuel capsule to fill the central reactor to capacity—not just add one energy. It does not refill the other reactors or shields.", "lesson.energy.instruction.1": "Android 1: fire on turns 1-4. Android 3: use the lift on turn 1, refill on turn 2. Then lock phase 1 to plan turn 4.", "lesson.repairs.title": "Repairing a malfunction", "lesson.repairs.instruction.0": "Repair the highlighted malfunction.", - "lesson.repairs.instruction.1": "→ on turn 1, then energy on turns 2-4.", + "lesson.repairs.instruction.1": "Move right on turn 1, then use B on turns 2, 3 and 4. While the malfunction is active, B repairs it instead of recharging the shield; it needs three repair actions.", "lesson.battlebots.title": "Battlebots and interceptors", "lesson.battlebots.instruction.0": "Collect the battlebots, then reach the interceptors.", "lesson.battlebots.instruction.1": "→ · systems · ← · ← · systems. In flight, play battlebots to fire; leave a slot empty to return.", @@ -177,7 +177,9 @@ "app.damage": "Damage", "app.threat_actions": "Threat actions", "app.review_a_step": "Review a step", - "app.back_to_live": "Back to live", + "app.back_to_live": "Jump to latest state", + "app.play_replay": "Play replay", + "app.pause_replay": "Pause replay", "app.laser": "Laser", "app.pulse": "Pulse", "app.shield": "Shield", @@ -606,5 +608,6 @@ "program.selected_turn": "Turn {turn}", "program.choose_turn": "Click a turn to edit", "lesson.energy.retry": "{count}/4 shots fired. Go back and plan four center-laser shots with a reactor refill.", - "tutorial.lock_phase": "Lock phase {phase}" + "tutorial.lock_phase": "Lock phase {phase}", + "tutorial.phase_ready": "Required actions programmed — ready to lock." } diff --git a/preview/locales/fr.json b/preview/locales/fr.json index 90c2fc3..3939a5c 100644 --- a/preview/locales/fr.json +++ b/preview/locales/fr.json @@ -5,11 +5,11 @@ "lesson.first-shot.lane": "Zone centrale", "lesson.first-shot.shield": "Le bouclier central absorbe les tirs automatiquement tant qu’il est chargé.", "lesson.energy.title": "Énergie et coordination", - "lesson.energy.instruction.0": "Le laser central consomme une énergie par tir. Son réacteur en contient trois : ravitaillez-le pour tirer quatre fois.", + "lesson.energy.instruction.0": "Le laser central consomme une énergie par tir. Son réacteur en contient trois : ravitaillez-le pour tirer quatre fois. Un ravitaillement consomme une capsule et remplit le réacteur central jusqu’à sa capacité, au lieu d’ajouter une seule énergie. Il ne remplit pas les autres réacteurs ni les boucliers.", "lesson.energy.instruction.1": "Androïde 1 : tirer aux tours 1-4. Androïde 3 : ascenseur au tour 1, énergie au tour 2. Verrouillez ensuite la phase 1 pour préparer le tour 4.", "lesson.repairs.title": "Réparer une panne", "lesson.repairs.instruction.0": "Réparez la panne surlignée.", - "lesson.repairs.instruction.1": "→ au tour 1, puis énergie aux tours 2-4.", + "lesson.repairs.instruction.1": "Allez à droite au tour 1, puis utilisez B aux tours 2, 3 et 4. Tant que la panne est active, B la répare au lieu de recharger le bouclier ; trois actions de réparation sont nécessaires.", "lesson.battlebots.title": "Robots et intercepteurs", "lesson.battlebots.instruction.0": "Prenez les robots, puis rejoignez les intercepteurs.", "lesson.battlebots.instruction.1": "→ · systèmes · ← · ← · systèmes. En vol, jouez robots pour tirer ; laissez vide pour rentrer.", @@ -177,7 +177,9 @@ "app.damage": "Dégâts", "app.threat_actions": "Actions des menaces", "app.review_a_step": "Revoir une étape", - "app.back_to_live": "Revenir au direct", + "app.back_to_live": "Aller au dernier état", + "app.play_replay": "Lire la reprise", + "app.pause_replay": "Mettre la reprise en pause", "app.laser": "Laser", "app.pulse": "Impulsion", "app.shield": "Bouclier", @@ -606,5 +608,6 @@ "program.selected_turn": "Tour {turn}", "program.choose_turn": "Cliquez un tour à modifier", "lesson.energy.retry": "{count}/4 tirs effectués. Revenez à la préparation : quatre tirs du laser central et un ravitaillement du réacteur.", - "tutorial.lock_phase": "Verrouiller la phase {phase}" + "tutorial.lock_phase": "Verrouiller la phase {phase}", + "tutorial.phase_ready": "Actions requises programmées — vous pouvez verrouiller." } diff --git a/preview/replay.js b/preview/replay.js new file mode 100644 index 0000000..3881f7b --- /dev/null +++ b/preview/replay.js @@ -0,0 +1,27 @@ +// Viewer transport only. The caller supplies already-visible frame counts; +// this controller has no engine, clock or network access. +export function createReplay({ index, count, show, busy, now = () => performance.now() }) { + let playing = false, end = -1, due = 0; + return { + get playing() { return playing; }, + pause() { playing = false; }, + play() { + end = count() - 1; // Freeze the horizon: incoming live frames are not replayed. + if (end < 1) return; + playing = true; + const start = index(); + show(start === null || start >= end ? 0 : start); + due = now() + 450; + }, + tick() { + if (!playing || busy() || now() < due) return; + const current = index(); + if (current === null || count() <= end || current >= end) { + playing = false; + return; + } + show(current + 1); + due = now() + 450; + }, + }; +} diff --git a/preview/resolution-effects.js b/preview/resolution-effects.js index 6750b23..2c207b2 100644 --- a/preview/resolution-effects.js +++ b/preview/resolution-effects.js @@ -142,6 +142,9 @@ export function createResolutionEffects(root, cue) { function delta(p, value, color, icon = "") { if (!p || !value) return; const n = node("fx-delta", p, color); + // Cancelling the finished animation restores the underlying style before + // the removal timer runs. Keep that style hidden to avoid a one-frame flash. + n.style.opacity = "0"; n.textContent = `${icon}−${value}`; animate(n, [{ transform: "translate(-50%,-20%)", opacity: 1 }, { transform: `translate(-50%,${reduced.matches ? "-20%" : "-140%"})`, opacity: 0 }], 750); diff --git a/preview/server.js b/preview/server.js index 3132671..9f5ac67 100644 --- a/preview/server.js +++ b/preview/server.js @@ -480,6 +480,7 @@ export function createPreviewServer({ clock = Date.now, storagePath } = {}) { "/program-route.js": "program-route.js", "/program-cursor.js": "program-cursor.js", "/resolution-effects.js": "resolution-effects.js", + "/replay.js": "replay.js", "/sound.js": "sound.js", "/i18n.js": "i18n.js", "/locales/en.json": "locales/en.json", diff --git a/preview/style.css b/preview/style.css index 2a6953b..71e6c0b 100644 --- a/preview/style.css +++ b/preview/style.css @@ -2448,10 +2448,9 @@ input:not([type="checkbox"]):not([type="range"]) { .native-tutorial.learning-basics #ship .station-title { visibility: hidden; } .native-tutorial.learning-basics[data-tutorial-stage="resolution"] #controls { display: flex !important; gap: 10px; } .native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay { display: block !important; } -.native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay label, -.native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay #live { display: none; } +.native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay label { display: block; } .native-tutorial.learning-basics[data-tutorial-step="3"] #controls { display: none !important; } -.native-tutorial.learning-basics[data-tutorial-step="3"] #replay { display: none !important; } +.native-tutorial.learning-basics[data-tutorial-step="3"] #replay:not(:empty) { display: block !important; } .training-ship .deck-upper .station, .training-ship .deck-lower .station { min-height: 104px; } @@ -2480,7 +2479,7 @@ input:not([type="checkbox"]):not([type="range"]) { margin: 12px 0 0; } .native-tutorial.learning-basics #program { width: fit-content; max-width: 100%; } -.native-tutorial .practice-readiness #basics-run { margin-left: 12px; } +.native-tutorial .practice-readiness #basics-run { margin-left: 0; } .native-tutorial .practice-clock { margin: 12px 0; padding: 12px; gap: 12px; } .native-tutorial .practice-clock strong { font-size: 1rem; } @@ -2537,6 +2536,20 @@ input:not([type="checkbox"]):not([type="range"]) { .native-tutorial #lesson-guide { display: none !important; } .native-tutorial .lesson-focus { outline: 2px dashed #e8c984; outline-offset: 3px; } +/* Keep the repair target readable throughout; only its small outer halo breathes. + Static emphasis is the default, including when reduced motion is requested. */ +.native-tutorial[data-chapter="repairs"] .lesson-focus { + box-shadow: 0 0 0 4px #e8c98420, 0 0 10px 2px #e8c98428; +} +@media (prefers-reduced-motion: no-preference) { + .native-tutorial[data-chapter="repairs"] .lesson-focus { + animation: tutorial-repair-attention 2.8s ease-in-out infinite; + } +} +@keyframes tutorial-repair-attention { + 0%, 100% { box-shadow: 0 0 0 4px #e8c98420, 0 0 10px 2px #e8c98428; } + 50% { box-shadow: 0 0 0 5px #e8c98438, 0 0 16px 3px #e8c98448; } +} .native-tutorial .flight-layout { grid-template-columns: minmax(0, 600px) minmax(280px, 480px); gap: 28px; justify-content: start; } @media (max-width: 800px) { .native-tutorial .flight-layout { grid-template-columns: 1fr; } } /* BGS already supplies the game name and chapter header. */ @@ -2585,11 +2598,23 @@ input:not([type="checkbox"]):not([type="range"]) { } .native-tutorial[data-chapter="first-shot"] #latest { display: none; } -.lesson-program-controls { display: flex; align-items: center; gap: 10px; margin-top: 12px; } +.lesson-program-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 12px 0; } +.lesson-program-controls .lesson-phase-lock { min-height: 48px; font-weight: 700; } +.lesson-program-controls .lesson-phase-lock.ready { + background: var(--gold); + border-color: var(--gold); + color: #15242c; + box-shadow: 0 0 0 2px #e8c98433; +} +.lesson-phase-ready { color: var(--gold); font-size: 13px; } +.lesson-phase-lock, .lesson-run { max-width: 100%; min-width: 0; white-space: normal; } +.lesson-phase-lock span, .lesson-run span { min-width: 0; overflow-wrap: anywhere; } +.lesson-run kbd { flex-shrink: 0; } +.native-tutorial .practice-readiness, .phase-lesson-controls { flex-wrap: wrap; } .lesson-program-controls:empty { display: none; } .lesson-program-controls [data-guide="run"] { display: inline-flex; align-items: center; gap: 12px; min-height: 48px; } .lesson-program-controls kbd { font: inherit; font-size: 12px; color: var(--muted); } -.native-tutorial[data-chapter="first-shot"] #replay { display: none !important; } +.native-tutorial[data-chapter="first-shot"] #replay:not(:empty) { display: block !important; } .compact-console-header { flex-wrap: wrap; } .compact-console-header .console-nav { margin: 0 0 0 auto; padding: 0; border: 0; flex-wrap: nowrap; } diff --git a/preview/tutorial-program.js b/preview/tutorial-program.js new file mode 100644 index 0000000..e05c89b --- /dev/null +++ b/preview/tutorial-program.js @@ -0,0 +1,37 @@ +import { translate } from './i18n.js'; +import { pictogram } from './icons.js'; + +// A teaching cue, not a rule or a prediction of successful resolution. Check +// only the actions requested in this phase, never every slot: empty turns wait. +export function tutorialPhaseReady(state) { + if (state.stage !== 'programming' || state.phase !== 1) return false; + const actions = (crew, turn) => (state.game.programs[crew]?.[turn - 1]?.cards ?? []) + .flatMap(card => state.game.cards[card.id]?.sides[card.side] ?? []); + const has = (crew, turn, action) => actions(crew, turn).includes(action); + switch (state.tutorial?.id) { + case 'energy': + return [1, 2, 3].every(turn => has(0, turn, 'A')) && + has(2, 1, 'lift') && has(2, 2, 'B'); + case 'repairs': + return has(0, 1, 'blue') && [2, 3].every(turn => has(0, turn, 'B')); + case 'battlebots': + return has(0, 1, 'blue') && has(0, 2, 'C') && has(0, 3, 'red'); + case 'double-actions': + return [1, 2, 3].some(turn => { + const programmed = actions(0, turn); + return programmed.length === 2 && programmed.includes('blue') && programmed.includes('A'); + }); + case 'phasing': + return [1, 2, 3].every(turn => has(0, turn, 'A')); + case 'specializations': + return has(0, 1, 'special:rocketeer:basic'); + default: + return false; + } +} + +export function tutorialPhaseButton(state, locale, busy = false) { + const ready = tutorialPhaseReady(state); + const label = translate(locale, 'tutorial.lock_phase', { phase: state.phase }); + return `${ready ? `${translate(locale, 'tutorial.phase_ready')}` : ''}`; +} diff --git a/test/replay.test.js b/test/replay.test.js new file mode 100644 index 0000000..1739b6b --- /dev/null +++ b/test/replay.test.js @@ -0,0 +1,112 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createReplay } from "../preview/replay.js"; + +function transport(start = 0, length = 4) { + let index = start, count = length, time = 0, busy = false; + const shown = []; + const replay = createReplay({ + index: () => index, count: () => count, now: () => time, + busy: () => busy, show: value => { index = value; shown.push(value); }, + }); + return { replay, shown, + step(ms = 450) { time += ms; replay.tick(); }, + set busy(value) { busy = value; }, + set count(value) { count = value; }, + set index(value) { index = value; }, + }; +} + +test("replay from the scrubbed position visits consecutive resolved frames and stays in review", () => { + const t = transport(1); + t.replay.play(); + t.step(); t.step(); t.step(); + assert.deepEqual(t.shown, [1, 2, 3]); + assert.equal(t.replay.playing, false); +}); + +test("play from live or the final frame replays from the beginning, including completed missions", () => { + for (const start of [null, 3]) { + const t = transport(start); + t.replay.play(); + t.step(); t.step(); t.step(); t.step(); + assert.deepEqual(t.shown, [0, 1, 2, 3]); + assert.equal(t.replay.playing, false); + } +}); + +test("effect busy timing and minimum dwell prevent skipped or interrupted animations", () => { + const t = transport(); + t.replay.play(); + t.step(449); + assert.deepEqual(t.shown, [0]); + t.busy = true; + t.step(3000); + assert.deepEqual(t.shown, [0]); + t.busy = false; + t.step(1); + assert.deepEqual(t.shown, [0, 1]); + t.step(449); + assert.deepEqual(t.shown, [0, 1]); + t.step(1); + assert.deepEqual(t.shown, [0, 1, 2]); +}); + +test("pause (also used for scrub, reset and destroy) prevents any further frame updates", () => { + const t = transport(); + t.replay.play(); t.step(); + t.replay.pause(); t.step(10000); + assert.deepEqual(t.shown, [0, 1]); + t.index = 2; + t.replay.play(); t.step(); + assert.deepEqual(t.shown, [0, 1, 2, 3]); +}); + +test("incoming live frames cannot extend the captured replay horizon", () => { + const t = transport(0, 3); + t.replay.play(); + t.count = 20; + for (let i = 0; i < 25; i++) t.step(); + assert.deepEqual(t.shown, [0, 1, 2]); + assert.equal(t.replay.playing, false); +}); + +test("missing/reset frames and single-frame resolutions stop safely", () => { + const t = transport(); + t.replay.play(); + t.count = 1; + t.step(); + assert.equal(t.replay.playing, false); + assert.deepEqual(t.shown, [0]); + const empty = transport(null, 0), initial = transport(null, 1); + for (const fixture of [empty, initial]) { + fixture.replay.play(); fixture.step(); + assert.equal(fixture.replay.playing, false); + assert.deepEqual(fixture.shown, []); + } +}); + +test("replaying resolved snapshots reproduces movement effects without mutating resolution", async () => { + const { beginResolution, stepResolution } = await import("../src/game/resolution.js"); + const { resolutionEffects } = await import("../preview/resolution-effects.js"); + const { TRACKS } = await import("../src/game/catalog.js"); + let resolution = beginResolution({ crewSize: 1, seed: "replay", turns: 3, + programs: [[{ actions: ["blue"] }, null, null]], threats: [], + tracks: Object.fromEntries(["red", "white", "blue", "internal"].map(z => [z, TRACKS[6]])) }); + while (!resolution.outcome) resolution = stepResolution(resolution); + const original = JSON.stringify(resolution); + let index = 0, time = 0; + const events = []; + const replay = createReplay({ index: () => index, + count: () => resolution.frames.length, busy: () => false, now: () => time, + show(next) { + events.push(...resolutionEffects(resolution, resolution.frames[index], resolution.frames[next])); + index = next; + }, + }); + replay.play(); + while (replay.playing) { time += 450; replay.tick(); } + assert.ok(events.some(e => e.kind === "move" && e.from === "white-upper" && e.to === "blue-upper")); + assert.equal(index, resolution.frames.length - 1); + assert.equal(JSON.stringify(resolution), original); +}); diff --git a/test/tutorial-program.test.js b/test/tutorial-program.test.js new file mode 100644 index 0000000..3c0cdeb --- /dev/null +++ b/test/tutorial-program.test.js @@ -0,0 +1,84 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { tutorialPhaseReady, tutorialPhaseButton } from '../preview/tutorial-program.js'; +import { loadLocale } from '../preview/i18n.js'; +import { basicsView } from '../preview/basics.js'; + +function fixture(id) { + return { stage: 'programming', phase: 1, tutorial: { id }, game: { + programs: Array.from({ length: 4 }, () => Array.from({ length: 7 }, () => ({ cards: [] }))), cards: {}, + } }; +} +function place(state, crew, turn, ...actions) { + const id = `${crew}/${turn}`; + state.game.cards[id] = { sides: [actions] }; + state.game.programs[crew][turn - 1].cards = [{ id, side: 0 }]; +} + +test('energy readiness includes both crew objectives but not empty wait turns or next phase', () => { + const s = fixture('energy'); + for (const turn of [1, 2, 3]) place(s, 0, turn, 'A'); + assert.equal(tutorialPhaseReady(s), false); + place(s, 2, 1, 'lift'); + place(s, 2, 2, 'A'); + assert.equal(tutorialPhaseReady(s), false, 'wrong refill action'); + place(s, 2, 2, 'B'); + assert.equal(tutorialPhaseReady(s), true, 'crew 3 turn 3 and turn 4 intentionally empty'); + s.game.programs[2][0].cards = []; + assert.equal(tutorialPhaseReady(s), false, 'clearing a required action removes cue'); + place(s, 2, 1, 'lift'); + s.phase = 2; + assert.equal(tutorialPhaseReady(s), false); + s.phase = 1; + s.stage = 'resolution'; + assert.equal(tutorialPhaseReady(s), false); +}); + +test('phase cues follow the requested actions for each exercise', () => { + for (const [id, turns] of [ + ['repairs', [['blue'], ['B'], ['B']]], + ['battlebots', [['blue'], ['C'], ['red']]], + ['double-actions', [['blue', 'A']]], + ['phasing', [['A'], ['A'], ['A']]], + ['specializations', [['special:rocketeer:basic']]], + ]) { + const s = fixture(id); + assert.equal(tutorialPhaseReady(s), false, id); + turns.forEach((actions, i) => place(s, 0, i + 1, ...actions)); + assert.equal(tutorialPhaseReady(s), true, id); + } + assert.equal(tutorialPhaseReady(fixture('unknown')), false); +}); + +test('lock labels are visible in EN/FR; readiness is advisory and busy still disables', async () => { + for (const [locale, label] of [['en', 'Lock phase 1'], ['fr', 'Verrouiller la phase 1']]) { + await loadLocale(locale); + const s = fixture('specializations'); + const initial = tutorialPhaseButton(s, locale); + assert.ok(initial.includes(`${label}`)); + assert.ok(!initial.includes('disabled')); + assert.ok(!initial.includes('role="status"')); + place(s, 0, 1, 'special:rocketeer:basic'); + const ready = tutorialPhaseButton(s, locale, true); + assert.match(ready, /lesson-phase-lock ready/); + assert.match(ready, /role="status"/); + assert.match(ready, /disabled/); + } +}); + +test('native first lesson retains a visible localized execution label and enablement', async () => { + for (const [locale, label] of [['en', 'Run program'], ['fr', 'Exécuter le programme']]) { + await loadLocale(locale); + const s = fixture('basics'); + s.mission = { phaseEndsMs: [600000] }; + s.missionStartAt = 0; + s.observedAt = 0; + s.tutorial.nativeStep = 1; + const html = basicsView(s, locale, {}); + assert.ok(html.includes(`${label}`)); + assert.match(html, /id="basics-run"[^>]*disabled/); + place(s, 0, 1, 'blue'); + place(s, 0, 2, 'lift'); + assert.doesNotMatch(basicsView(s, locale, {}), /id="basics-run"[^>]*disabled/); + } +});