Stop firing exercise at its objective and clarify planning controls and clock

This commit is contained in:
coyotte508 2026-10-31 18:46:05 +01:00
commit 36f68c8644
7 changed files with 117 additions and 14 deletions

View file

@ -24,7 +24,7 @@
"name": "sound",
"type": "checkbox",
"label": "Spoken announcements",
"default": false
"default": true
}
],
"options": [

View file

@ -12,11 +12,17 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
const index = LESSONS.findIndex(l => l.id === chapter);
if (index < 0) throw Error("Unknown tutorial chapter");
const sound = createSoundDesign();
let soundOn = false, disposed = false, lastStep = -1, lastTurn = 0, lastTick = performance.now();
let soundOn = true, disposed = false, lastStep = -1, lastTurn = 0, lastTick = performance.now();
let playing = false, previousStage, playbackBusy = false;
const canPlay = s => s.state.stage === "resolution" && !s.completed && !s.state.game.resolution?.outcome && !(chapter === "basics" && completedTurns(s.state) >= 3);
const shotExerciseEnded = s => chapter === "first-shot" && s.state.tutorial.stopAtTarget &&
s.state.game.resolution?.turn >= 3 && ["threats", "computer", "appear"].includes(s.state.game.resolution.step);
const canPlay = s => !shotExerciseEnded(s) && s.state.stage === "resolution" && !s.completed && !s.state.game.resolution?.outcome && !(chapter === "basics" && completedTurns(s.state) >= 3);
let storage;
try { storage = window.localStorage; } catch {}
try { storage = window.localStorage; soundOn = storage.getItem("space-alert:tutorial-sound") !== "off"; } catch {}
// Unlock audio on the first real interaction, respecting browser autoplay rules.
const unlockSound = () => sound.enable(soundOn);
target.ownerDocument.addEventListener("pointerdown", unlockSound, true);
target.ownerDocument.addEventListener("keydown", unlockSound, true);
const tutorial = await createLessonTutorial(chapter, { locale, storage, onProgress });
target.innerHTML = html.split("<body>")[1].split('<script type="module"')[0].split("</body>")[0];
const style = document.createElement("style");
@ -31,6 +37,9 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
target.querySelector("#planning").append(target.querySelector("#basics-guide"));
target.querySelector("#ship").classList.add("training-ship");
}
const programControls = document.createElement("div");
programControls.className = "lesson-program-controls";
target.querySelector("#hand").after(programControls);
if (chapter === "first-shot") {
const threats = target.querySelector("#threats");
const heading = target.querySelector("#threat-title").closest(".section-heading");
@ -61,6 +70,9 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
await tick();
await play({ type: "practice-clock", running: body.running });
lastTick = performance.now();
} else if (path === "/api/lesson-deadline") {
await play({ type: "practice-deadline" });
lastTick = performance.now();
} else if (path === "/api/lesson-next") await play({ type: "practice-phase" });
else throw Error("Unsupported tutorial action");
},
@ -75,9 +87,10 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
const planned = s.state.game.programs[0].some(slot => slot?.cards?.length);
const readyToFire = chapter === "first-shot" && [1, 2].every(i => s.state.game.programs[0][i]?.cards?.length);
const missed = LESSONS[index].basics && s.step === 2 && completedTurns(s.state) >= 3 && !s.completed;
programControls.innerHTML = `${canPlay(s) ? transport("playback", playing ? "pause" : "right", playing ? t("Pause", "Pause") : t("Lire le programme", "Play program")) : ""}${!LESSONS[index].basics && chapter !== "first-shot" && s.step === 1 && s.state.phase === 1 ? transport("phase", "step", t("Phase 2", "Phase 2"), s.busy) : ""}${!LESSONS[index].basics && s.step === 1 ? `<button data-guide="run" class="primary icon-button" aria-keyshortcuts="Enter" title="${t("Exécuter le programme", "Run program")} · ↵" aria-label="${t("Exécuter le programme", "Run program")}" ${(chapter === "first-shot" ? !readyToFire : !planned) || s.busy ? "disabled" : ""}>${pictogram("step")}<kbd>↵</kbd></button>` : ""}`;
guide.innerHTML = `<div class="native-guide-row"><nav class="basics-stages" aria-label="${t("Étapes", "Steps")}">${label.map((name, i) => `<button data-guide-step="${i}" class="quiet ${Math.min(s.step, 2) === i ? 'active' : ''}" ${i > s.step || s.busy ? 'disabled' : ''} ${s.step === i ? 'aria-current="step"' : ''}><span class="step-number">${i + 1}</span><span>${name}</span></button>`).join('')}</nav><div class="native-guide-tools">${standalone ? `<a href="/">${t("Partie locale", "Local game")}</a>` : ''}${transport("sound", soundOn ? "speaker" : "muted", soundOn ? t("Couper les sons", "Mute sounds") : t("Activer les sons", "Enable sounds"))}</div></div>
<h1>${escape(s.title)}</h1><p class="native-guide-text">${escape(missed ? t("Destination manquée. Revenez préparer un autre trajet.", "Destination missed. Go back and plan another route.") : s.text)}</p>
<div class="native-guide-controls">${canPlay(s) ? transport("playback", playing ? "pause" : "right", playing ? t("Pause", "Pause") : t("Lire le programme", "Play program")) : ""}${transport("restart", "rewind", t("Recommencer l’exercice", "Restart exercise"), s.busy)}${transport("previous", "left", t("Étape précédente", "Previous step"), s.step === 0 || s.busy)}${transport("replay", "restart", t("Rejouer cette étape", "Replay step"), s.busy || s.step === 0)}${!LESSONS[index].basics && chapter !== "first-shot" && s.step === 1 && s.state.phase === 1 ? transport("phase", "step", t("Phase 2", "Phase 2"), s.busy) : ""}${!LESSONS[index].basics && s.step === 1 ? transport("run", "step", t("Exécuter le programme · ↵", "Run program · ↵"), (chapter === "first-shot" ? !readyToFire : !planned) || s.busy) : ""}${s.canContinue ? `<button data-guide="continue" class="primary icon-button" title="${t("Commencer", "Start")}" aria-label="${t("Commencer", "Start")}">${pictogram("right")}</button>` : ''}${s.completed && (nextChapter || standalone && LESSONS[index + 1]) ? `<button data-guide="next" class="primary icon-label"><span>${t("Exercice suivant", "Next exercise")}</span>${pictogram("right")}</button>` : ''}</div>
<div class="native-guide-controls">${transport("restart", "rewind", t("Recommencer l’exercice", "Restart exercise"), s.busy)}${transport("previous", "left", t("Étape précédente", "Previous step"), s.step === 0 || s.busy)}${transport("replay", "restart", t("Rejouer cette étape", "Replay step"), s.busy || s.step === 0)}${s.canContinue ? `<button data-guide="continue" class="primary icon-button" title="${t("Commencer", "Start")}" aria-label="${t("Commencer", "Start")}">${pictogram("right")}</button>` : ''}${s.completed && (nextChapter || standalone && LESSONS[index + 1]) ? `<button data-guide="next" class="primary icon-label"><span>${t("Exercice suivant", "Next exercise")}</span>${pictogram("right")}</button>` : ''}</div>
${s.error ? `<p role="alert">${escape(s.error)}</p>` : ''}`;
}
const unsubscribe = tutorial.subscribe(s => {
@ -119,11 +132,13 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
if (!button || tutorial.snapshot.busy) return;
const action = button.dataset.guide;
if (action === "sound") {
soundOn = !soundOn; sound.enable(soundOn); sound.cue("select"); renderGuide(tutorial.snapshot); return;
soundOn = !soundOn;
try { storage?.setItem("space-alert:tutorial-sound", soundOn ? "on" : "off"); } catch {}
sound.enable(soundOn); sound.cue("select"); renderGuide(tutorial.snapshot); return;
}
if (action === "phase") { await play({ type: "practice-phase" }); return; }
if (action === "run") {
while (tutorial.snapshot.state.stage === "programming") await play({ type: "practice-phase" });
await play({ type: "practice-run" });
return;
}
if (action === "playback") {
@ -149,6 +164,7 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
lastTick = performance.now();
};
guide.addEventListener("click", onClick);
programControls.addEventListener("click", onClick);
// Playback pacing only: each tick executes the next deterministic engine step.
const playback = setInterval(async () => {
if (!playing || disposed || playbackBusy || tutorial.snapshot.busy || !canPlay(tutorial.snapshot)) return;
@ -159,10 +175,13 @@ export async function mountLesson(target, { chapter = "basics", locale = "en", o
}, 450);
const ticker = setInterval(() => {
if (!tutorial.snapshot.busy) void tick().catch(() => {});
}, 5000);
}, 1000);
return () => {
disposed = true; clearInterval(playback); clearInterval(ticker); unsubscribe(); tutorial.destroy(); ui.destroy(); sound.destroy();
guide.removeEventListener("click", onClick);
programControls.removeEventListener("click", onClick);
target.ownerDocument.removeEventListener("pointerdown", unlockSound, true);
target.ownerDocument.removeEventListener("keydown", unlockSound, true);
target.classList.remove("native-tutorial");
};
}

View file

@ -64,6 +64,11 @@ export function mountConsole(root, host = null) {
locale: () => locale,
hosted: !!host,
});
if (host && !host.tutorial) {
const header = $("header");
header.classList.add("compact-console-header");
header.insertBefore($("#console-nav"), header.querySelector(".header-tools"));
}
let appearance = {};
const playerColor = (i) => {
const color = appearance.playerColors?.[i];
@ -480,7 +485,7 @@ export function mountConsole(root, host = null) {
!own.finishedPlanning &&
phaseFor(slot.turn) === ownPhase;
const description = `T+${slot.turn} · ${slot.cards.map((c) => (c.sides ? c.sides[c.side].map(label).join(" → ") : c.category === "movement" ? t("Déplacement", "Movement") : t("Action", "Action"))).join(" + ") || t("Vide", "Empty")}`;
return `<button class="slot ${slot.cards.length ? "filled" : "empty"} ${basic && resolution && slot.turn === (resolution.step === "damage" ? resolution.turn : Math.max(0, resolution.turn - 1)) ? "current" : ""} ${phaseFor(slot.turn) < ownPhase ? "locked" : ""} ${phaseFor(slot.turn) > ownPhase ? "future" : ""}" data-turn="${slot.turn}" ${editable ? "" : "disabled"} title="${esc(description)}" aria-label="${esc(description)}">${firstShot && slot.turn === 2 ? `<span class="slot-arrival" title="${t("La cible arrive avant ce tir", "Target arrives before this shot")}">${pictogram("down")}${t("Arrivée", "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></button>`;
return `<button class="slot ${slot.cards.length ? "filled" : "empty"} ${(basic || firstShot) && resolution && slot.turn === (resolution.step === "damage" ? resolution.turn : Math.max(0, resolution.turn - 1)) ? "current" : ""} ${phaseFor(slot.turn) < ownPhase ? "locked" : ""} ${phaseFor(slot.turn) > ownPhase ? "future" : ""}" data-turn="${slot.turn}" ${editable ? "" : "disabled"} title="${esc(description)}" aria-label="${esc(description)}">${firstShot && slot.turn === 2 ? `<span class="slot-arrival" title="${t("La cible arrive avant ce tir", "Target arrives before this shot")}">${pictogram("down")}${t("Arrivée", "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></button>`;
})
.join("");
$("#program").setAttribute("aria-keyshortcuts", "ArrowLeft ArrowRight ArrowUp ArrowDown Backspace");
@ -1051,6 +1056,10 @@ export function mountConsole(root, host = null) {
});
return;
}
if (el.id === "lesson-deadline" && host?.tutorial) {
perform(() => localPost("/api/lesson-deadline", {}));
return;
}
if (el.id === "lesson-clock") {
perform(() =>
localPost("/api/lesson-clock", {

View file

@ -8,10 +8,10 @@ export function basicsView(view, locale, { started, picked, shipMarkup }) {
const turn = r?.step === "damage" ? r.turn : Math.max(0, (r?.turn ?? 0) - 1);
const playing = view.stage === "resolution";
if (view.tutorial.nativeStep !== undefined) {
const control = (id, glyph, description, disabled = false) => `<button id="${id}" class="primary icon-button" ${id === "basics-run" ? 'aria-keyshortcuts="Enter"' : ""} title="${description}${id === "basics-run" ? " · ↵" : ""}" aria-label="${description}" ${disabled ? "disabled" : ""}>${pictogram(glyph)}</button>`;
const control = (id, glyph, description, disabled = false) => `<button id="${id}" class="primary icon-button" ${id === "basics-run" ? 'aria-keyshortcuts="Enter"' : ""} title="${description}${id === "basics-run" ? " · ↵" : ""}" aria-label="${description}" ${disabled ? "disabled" : ""}>${pictogram(glyph)}${id === "lesson-deadline" ? "<small>5 s</small>" : ""}</button>`;
if (view.tutorial.nativeStep === 0) return "";
if (playing) return "";
return `<div class="planning-shortcuts" title="${t("Flèches : déplacement · ↑/↓ : changer de pont · Retour arrière : annuler · Entrée : exécuter", "Arrows: move · ↑/↓: change deck · Backspace: undo · Enter: run")}" aria-label="${t("Raccourcis : flèches pour se déplacer ; retour arrière pour annuler ; entrée pour exécuter", "Shortcuts: arrow keys to move; Backspace to undo; Enter to run")}"><kbd>←</kbd><kbd>→</kbd><kbd>↑</kbd><kbd>↓</kbd><kbd>⌫</kbd><kbd>↵</kbd></div><div class="practice-readiness" role="status" aria-label="${placed}/2 ${t("actions placées", "actions placed")}"><span>${pictogram("cards")} ${placed}/2</span><span class="ready-dots" aria-hidden="true">${[0,1].map(i => `<i class="${i < placed ? "filled" : ""}"></i>`).join("")}</span>${control("basics-run", "step", t("Exécuter le programme", "Run program"), placed !== 2)}</div><div class="practice-clock"><div><strong data-practice-time></strong><small>${t("Préparation", "Planning")}</small></div>${control("lesson-clock", view.tutorial.clockRunning ? "pause" : "clock", view.tutorial.clockRunning ? t("Pause", "Pause") : t("Lancer le chrono", "Start clock"))}</div>`;
return `<div class="planning-shortcuts" title="${t("Flèches : déplacement · ↑/↓ : changer de pont · Retour arrière : annuler · Entrée : exécuter", "Arrows: move · ↑/↓: change deck · Backspace: undo · Enter: run")}" aria-label="${t("Raccourcis : flèches pour se déplacer ; retour arrière pour annuler ; entrée pour exécuter", "Shortcuts: arrow keys to move; Backspace to undo; Enter to run")}"><kbd>←</kbd><kbd>→</kbd><kbd>↑</kbd><kbd>↓</kbd><kbd>⌫</kbd><kbd>↵</kbd></div><div class="practice-readiness" role="status" aria-label="${placed}/2 ${t("actions placées", "actions placed")}"><span>${pictogram("cards")} ${placed}/2</span><span class="ready-dots" aria-hidden="true">${[0,1].map(i => `<i class="${i < placed ? "filled" : ""}"></i>`).join("")}</span>${control("basics-run", "step", t("Exécuter le programme", "Run program"), placed !== 2)}</div><div class="practice-clock"><div><strong data-practice-time></strong><small>${t("Temps pour programmer", "Time to plan")}</small></div>${control("lesson-deadline", "forward", t("Aller à 5 s de la fin du chrono", "Jump to 5 seconds before the deadline"), placed !== 2)}${control("lesson-clock", view.tutorial.clockRunning ? "pause" : "clock", view.tutorial.clockRunning ? t("Pause", "Pause") : t("Lancer le chrono", "Start clock"))}</div>`;
}
const intro = !started && !placed && !playing;
const ready = placed === 2;

View file

@ -2515,3 +2515,16 @@ input:not([type="checkbox"]):not([type="range"]) {
margin-top: 0;
}
.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: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; }
.compact-console-header { flex-wrap: wrap; }
.compact-console-header .console-nav { margin: 0 0 0 auto; padding: 0; border: 0; flex-wrap: nowrap; }
.compact-console-header .header-tools { flex: 0 0 auto; }
@media (max-width: 760px) {
.compact-console-header .console-nav button { flex-direction: row; padding: 6px; }
}

View file

@ -16,6 +16,21 @@ export function createLessonTutorial(id, { locale = "en", storage, onProgress }
game: "space-alert", id, version: lesson.basics ? 3 : 2, storage, onProgress,
initialState: () => createLesson(id, 1000),
move(state, move) {
if (move.type === "practice-deadline") {
if (state.stage !== "programming") throw Error("Planning has ended");
state.tutorial.clockRunning = true;
return advanceClock(state, Math.max(state.observedAt,
state.missionStartAt + state.mission.phaseEndsMs.at(-1) - 5000));
}
if (move.type === "practice-run") {
if (state.stage !== "programming") throw Error("Planning has ended");
// Record the objective-based ending in new histories. Older saved
// full-mission runs remain replayable without losing completed progress.
state.tutorial.stopAtTarget = id === "first-shot";
while (state.stage === "programming")
state = advanceClock(state, state.missionStartAt + state.mission.phaseEndsMs[state.phase - 1]);
return state;
}
if (move.type === "practice-phase") {
if (state.stage !== "programming") throw Error("Planning has ended");
return advanceClock(state, state.missionStartAt + state.mission.phaseEndsMs[state.phase - 1]);
@ -37,14 +52,17 @@ export function createLessonTutorial(id, { locale = "en", storage, onProgress }
},
steps: [
{ id: "discover", title: lesson.title[locale === "fr" ? 0 : 1],
text: lesson.basics ? t("Préparez vos actions, puis regardez-les s’exécuter. Commençons sans menace, avec un seul androïde.", "Plan your actions, then watch them execute. Start without threats, with one android.") : lesson.instructions[0]?.[locale === "fr" ? 0 : 1] ?? "" },
text: lesson.basics ? t("Le chrono limite la préparation. Les tours s’exécutent ensuite, dans l’ordre.", "The clock limits planning time. Your turns execute afterward, in order.") : lesson.instructions[0]?.[locale === "fr" ? 0 : 1] ?? "" },
{ id: "plan", title: t("Préparer le programme", "Plan the program"),
text: id === "first-shot" ? t("Placez un tir dans chaque case surlignée, puis ↵.", "Place a shot in each highlighted slot, then ↵.") : lesson.basics ? t("Rejoignez la salle marquée en deux actions. La troisième case reste vide : attendre.", "Reach the marked room in two actions. Leave the third slot empty: wait.") : lesson.instructions[1]?.[locale === "fr" ? 0 : 1] ?? lesson.instructions[0]?.[locale === "fr" ? 0 : 1] ?? "",
complete: state => state.stage === "resolution" },
{ id: "execute", title: t("Exécuter les tours", "Run the turns"),
text: t("Programme verrouillé. Les équipiers agissent ensemble, puis les menaces.", "Program locked. Crew act together, then threats."),
complete: state => lesson.basics ? completedTurns(state) >= 3 && state.game.resolution.ship.crew[0].station === state.tutorial.targetStation : !!state.game.resolution?.outcome },
complete: state => lesson.basics ? completedTurns(state) >= 3 && state.game.resolution.ship.crew[0].station === state.tutorial.targetStation
: id === "first-shot" && state.tutorial.stopAtTarget
? state.game.resolution.threats.some(threat => threat.id === lesson.threat && threat.status === "destroyed")
: !!state.game.resolution?.outcome },
],
completion: { title: t("Exercice terminé", "Exercise complete"), text: lesson.basics ? t("Destination atteinte ! Votre programme vous y a conduit.", "Destination reached! Your program took you there.") : t("Rejouez pour comparer un autre programme, ou passez à la suite.", "Replay to compare another program, or move on.") },
completion: { title: t("Exercice terminé", "Exercise complete"), text: lesson.basics ? t("Destination atteinte ! Votre programme vous y a conduit.", "Destination reached! Your program took you there.") : id === "first-shot" ? t("Cible détruite.", "Target destroyed.") : t("Rejouez pour comparer un autre programme, ou passez à la suite.", "Replay to compare another program, or move on.") },
});
}

View file

@ -113,3 +113,47 @@ test("every chapter can plan, execute, complete, and replay through native contr
tutorial.destroy();
}
});
test("first shot stops on target destruction at turn 3, and preserves new and legacy saves", async () => {
for (const objective of [true, false]) {
const data = new Map();
const storage = { getItem: key => data.get(key), setItem: (key, value) => data.set(key, value) };
const tutorial = await createLessonTutorial("first-shot", { storage });
await tutorial.continue();
await place(tutorial, 2, "A");
await place(tutorial, 3, "A");
if (objective) await tutorial.play({ type: "practice-run" });
else while (tutorial.snapshot.state.stage === "programming") await tutorial.play({ type: "practice-phase" });
for (let i = 0; i < 100 && !tutorial.snapshot.completed; i++)
assert.equal(await tutorial.play({ type: "resolve" }), true);
assert.equal(tutorial.snapshot.completed, true);
const resolution = tutorial.snapshot.state.game.resolution;
if (objective) {
assert.equal(resolution.turn, 3);
assert.equal(resolution.step, "threats");
assert.equal(resolution.outcome, null);
assert.equal(resolution.threats[0].status, "destroyed");
} else assert.ok(resolution.outcome);
const restored = await createLessonTutorial("first-shot", { storage });
assert.equal(restored.snapshot.completed, true);
assert.deepEqual(restored.snapshot.state, tutorial.snapshot.state);
restored.destroy(); tutorial.destroy();
}
});
test("the clock demonstration waits until the actual planning deadline before resolution", async () => {
const tutorial = await createLessonTutorial("basics");
await tutorial.continue();
await place(tutorial, 1, "blue");
await place(tutorial, 2, "lift");
await tutorial.play({ type: "practice-deadline" });
assert.equal(tutorial.snapshot.state.stage, "programming");
assert.equal(snapshot(tutorial.snapshot.state, 0).game.ship.crew[0].station, "white-upper");
assert.equal(completedTurns(tutorial.snapshot.state), 0);
await tutorial.play({ type: "practice-tick", ms: 4999 });
assert.equal(tutorial.snapshot.state.stage, "programming");
await tutorial.play({ type: "practice-tick", ms: 1 });
assert.equal(tutorial.snapshot.state.stage, "resolution");
assert.equal(completedTurns(tutorial.snapshot.state), 0);
tutorial.destroy();
});