diff --git a/README.md b/README.md index 910ceb0..90948c6 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,12 @@ npm test npm run dev ``` -Open . Start with **Flight school / École de vol**: seven untimed exercises use the real engine, with editable programs and a teammate already maintaining the computer. The examples cover firing, energy, malfunctions, battlebots/interceptors, double actions, phasing and specializations. +Open . Start with **Flight school / École de vol**: eight exercises use the real engine. Start with **Planning turns**: one crew member, two movement cards, and an empty turn. Arrange the cards, try the start/pause practice clock, then watch each turn execute. The later exercises have editable programs and a teammate already maintaining the computer; they cover firing, energy, malfunctions, battlebots/interceptors, double actions, phasing and specializations. 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. Select a card half, then 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. +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; browser speech synthesis is optional and communications-blackout silence relies on the players. ## Implemented @@ -48,7 +50,7 @@ No publisher artwork, scanned cards, rulebook files or official voice recordings ## Build for BGS -The BGS integration requires the published `@boardgamers/protocol` **0.8.x** package: +The BGS integration requires the published `@boardgamers/protocol` **0.10.0** package: ```sh npm install @@ -67,3 +69,21 @@ npm run build ``` Upload the generated engine tarball and `dist/viewer.js` through BGS admin. Use the metadata in [`bgs/gameinfo.json`](bgs/gameinfo.json): engine entry `bgs/engine.js`, viewer global `SpaceAlert`, game-managed time control, and no Elo. Keep the version private during playtesting. BGS assigns uploaded asset URLs; the example intentionally has no viewer URL. See [the integration notes](docs/realtime-host.md) for clock, table and career behavior. + + +### Playable tutorials + +Open `/learn?chapter=basics&locale=fr` on the local preview server. Lessons use +`@boardgamers/protocol/tutorial` for validated action history, checkpoints, +previous/replay/restart controls, and browser-local progress. The BGS viewer +registers the same `mountLesson` through `launchTutorial`; chapter metadata still +needs configuring when the viewer is published. Nothing has been published by +this local change. + +Tutorials mount the ordinary console, ship, card controls and program slots. +The first chapter hides unrelated systems, card sides and crew members. Both +ship decks retain the same room height. Resolution is untimed and uses the +ordinary resolution controls; the planning clock never drives individual turns. +The speaker toggle enables short synthesized action cues (off initially). + +[BGS playable tutorial API](https://codeberg.org/boardgamers/boardgamers/src/branch/main/apps/docs/docs/guide/tutorials.md) diff --git a/bgs/engine.js b/bgs/engine.js index 136a7e5..e384d75 100644 --- a/bgs/engine.js +++ b/bgs/engine.js @@ -118,22 +118,26 @@ export function init(players, expansions, options, seed, creator, context) { if (progress && progress.version !== 1) throw Error("Unsupported Space Alert career version"); const previous = progress?.data?.explorers ?? {}; - const explorers = Object.fromEntries( - playerIds - .filter((id) => options.careers || previous[id]) - .map((id, i) => [ - id, - previous[id] - ? structuredClone(previous[id]) - : createExplorer(id, `Explorer ${i + 1}`), - ]), - ); + // A table career survives games its owner sits out. + const explorers = { + ...structuredClone(previous), + ...Object.fromEntries( + playerIds + .filter((id) => options.careers || previous[id]) + .map((id, i) => [ + id, + previous[id] + ? structuredClone(previous[id]) + : createExplorer(id, `Explorer ${i + 1}`), + ]), + ), + }; if (Object.values(explorers).some((e) => e.activeRun)) throw Error("Previous explorers have not returned from their mission"); if ( options.careers && campaignLimit && - Object.values(explorers).some((e) => e.level < 2) + playerIds.some((id) => explorers[id].level < 2) ) throw Error("Career explorers need level 2 before a campaign"); const state = createSession( @@ -379,7 +383,9 @@ export function stripSecret(state, seat, context) { const id = state.bgs.playerIds[seat]; view.careerIds = state.bgs.playerIds; view.explorers = ( - state.bgs.settings.careers ? Object.values(state.bgs.explorers) : [] + state.bgs.settings.careers + ? state.bgs.playerIds.map((id) => state.bgs.explorers[id]) + : [] ).map((e) => ({ ...e, activeRun: !!e.activeRun, diff --git a/bgs/tutorial.js b/bgs/tutorial.js new file mode 100644 index 0000000..2e86ad1 --- /dev/null +++ b/bgs/tutorial.js @@ -0,0 +1,128 @@ +import { createLessonTutorial, completedTurns } from "../src/tutorial-controller.js"; +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 { createSoundDesign } from "../preview/sound.js"; +import html from "../preview/index.html"; +import css from "../preview/style.css"; + +export async function mountLesson(target, { chapter = "basics", locale = "en", onProgress, nextChapter, standalone = false } = {}) { + const t = (fr, en) => locale === "fr" ? fr : en; + 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 storage; + try { storage = window.localStorage; } catch {} + const tutorial = await createLessonTutorial(chapter, { locale, storage, onProgress }); + target.innerHTML = html.split("")[1].split(''); + } + if (req.method === "GET" && url.pathname === "/tutorial-bundle.js") { + const { build } = await import("esbuild"); + const bundle = await build({ + entryPoints: [fileURLToPath(new URL("tutorial-entry.js", import.meta.url))], + bundle: true, write: false, format: "esm", loader: { ".html": "text", ".css": "text" }, + }); + res.writeHead(200, { "Content-Type": "text/javascript", "Cache-Control": "no-store" }); + return res.end(bundle.outputFiles[0].text); + } const file = { "/": "index.html", "/app.js": "app.js", + "/basics.js": "basics.js", "/local.js": "local.js", "/text.js": "text.js", "/navigation.js": "navigation.js", diff --git a/preview/sound.js b/preview/sound.js new file mode 100644 index 0000000..c23cdf1 --- /dev/null +++ b/preview/sound.js @@ -0,0 +1,41 @@ +// Short, quiet synthesized cues; no downloads, looping soundtrack or timing authority. +export function createSoundDesign() { + let context; + let enabled = false; + function enable(value) { + enabled = value; + if (enabled) { + const Audio = window.AudioContext || window.webkitAudioContext; + if (!Audio) return; + context ??= new Audio(); + void context.resume().catch(() => {}); + } else if (context) void context.suspend().catch(() => {}); + } + function cue(kind, pan = 0) { + if (!enabled || !context || context.state !== "running") return; + const notes = { + select: [[660, 0, .045]], place: [[440, 0, .065], [660, .06, .09]], + start: [[330, 0, .09], [440, .1, .09], [660, .2, .14]], + turn: [[300, 0, .07], [450, .08, .12]], wait: [[260, 0, .13]], + complete: [[440, 0, .1], [550, .12, .1], [660, .24, .22]], + back: [[440, 0, .07], [330, .08, .09]], error: [[180, 0, .12]], + }[kind] ?? []; + for (const [frequency, delay, duration] of notes) { + const oscillator = context.createOscillator(); + const gain = context.createGain(); + const stereo = context.createStereoPanner(); + const at = context.currentTime + delay; + oscillator.type = "sine"; + oscillator.frequency.value = frequency; + stereo.pan.value = pan; + gain.gain.setValueAtTime(0, at); + gain.gain.linearRampToValueAtTime(.045, at + .008); + gain.gain.exponentialRampToValueAtTime(.001, at + duration); + oscillator.connect(gain).connect(stereo).connect(context.destination); + oscillator.start(at); + oscillator.stop(at + duration + .02); + oscillator.onended = () => { oscillator.disconnect(); gain.disconnect(); stereo.disconnect(); }; + } + } + return { enable, cue, destroy() { if (context) void context.close(); } }; +} diff --git a/preview/style.css b/preview/style.css index 9fc0852..770d983 100644 --- a/preview/style.css +++ b/preview/style.css @@ -101,7 +101,7 @@ header { align-items: center; justify-content: space-between; gap: 12px; - max-width: 1260px; + max-width: none; margin: auto; padding: 22px 28px; border-bottom: 1px solid var(--line); @@ -127,7 +127,7 @@ header { gap: 7px; } main { - max-width: 1260px; + max-width: none; margin: auto; padding: 22px 28px; } @@ -186,6 +186,11 @@ h1 { grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 30px; } +.tactical { + width: 100%; + max-width: 760px; + min-width: 0; +} .section-heading { display: flex; align-items: center; @@ -312,13 +317,21 @@ h2 { gap: 5px; } .slot { + position: relative; + display: flex; + align-items: center; + justify-content: center; min-width: 0; min-height: 64px; - padding: 5px 3px; + padding: 20px 3px; background: #101f2b; border-color: #344553; } .slot .turn { + position: absolute; + top: 7px; + left: 3px; + right: 3px; font-size: 9px; color: var(--muted); display: block; @@ -757,7 +770,7 @@ input:not([type="checkbox"]):not([type="range"]) { display: flex; flex-wrap: wrap; gap: 4px; - max-width: 1260px; + max-width: none; margin: auto; padding: 8px 28px; border-bottom: 1px solid var(--line); @@ -1127,14 +1140,23 @@ input:not([type="checkbox"]):not([type="range"]) { .cutaway { position: relative; container-type: inline-size; - padding: 0 9px; - border-inline: 5px solid #526c79; - border-radius: 40% 40% 18px 18px / 24px 24px 18px 18px; +} +.ship-hull { + position: relative; + padding: 0 14px 12px; +} +.ship-hull::before { + content: ""; + position: absolute; + inset: 39px 0 0; + border: 2px solid #8296a0; + border-top: 0; + border-radius: 0 0 18px 18px; background: #172c39; - box-shadow: inset 0 0 0 2px #263f4d; } .ship-bow { - margin: 0 -9px; + position: relative; + margin: 0 -14px; height: 40px; } .ship-bow svg { @@ -1145,7 +1167,7 @@ input:not([type="checkbox"]):not([type="range"]) { fill: none; } .ship-bow .hull-shell { - fill: #314e5c; + fill: #172c39; } .ship-bow .bridge-window { fill: #79ccd4; @@ -1494,15 +1516,16 @@ input:not([type="checkbox"]):not([type="range"]) { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; - padding: 0 10px; + padding: 0 14px 18px; } .ship-stern > span { display: flex; gap: 5px; justify-content: center; - width: 65%; + width: min(55%, 100px); margin: auto; - padding: 6px 10px 9px; + padding: 0 8px; + height: 20px; border: 2px solid #81939a; border-top: 0; border-radius: 0 0 12px 12px; @@ -1511,6 +1534,7 @@ input:not([type="checkbox"]):not([type="range"]) { .ship-stern i { width: 12px; height: 14px; + transform: translateY(12px); background: #95dfe7; border-radius: 0 0 6px 6px; box-shadow: 0 3px 7px #82eff04a; @@ -1678,13 +1702,17 @@ input:not([type="checkbox"]):not([type="range"]) { } @media (max-width: 760px) { .cutaway { - margin-inline: -9px; - padding-inline: 6px; - border-inline-width: 3px; + margin-inline: 0; + } + .ship-hull { + padding-inline: 9px; + } + .ship-hull::before { + top: 29px; } .ship-bow { height: 30px; - margin-inline: -6px; + margin-inline: -9px; } } /* Shared equipment inspector and threat cards. */ @@ -1771,14 +1799,14 @@ input:not([type="checkbox"]):not([type="range"]) { .threat-portrait { display: block; position: relative; - height: 180px; + height: 204px; background: #10212d; overflow: hidden; } .threat-portrait > .equipment-art { width: 128px; height: 118px; - margin: 24px auto 0; + margin: 66px auto 0; border-radius: 0; } .threat-timing { @@ -1789,6 +1817,10 @@ input:not([type="checkbox"]):not([type="range"]) { white-space: nowrap; } .threat-target { + position: absolute; + top: 8px; + left: 50%; + transform: translateX(-50%); display: flex; justify-content: center; align-items: end; @@ -1963,3 +1995,401 @@ input:not([type="checkbox"]):not([type="range"]) { height: 115px; } } + +/* The first lesson reveals only the idea currently being taught. */ +.learning-basics .flight-layout, +.learning-basics .mission-line, +.learning-basics #lesson-guide, +.learning-basics #crew, +.learning-basics .header-tools { + display: none !important; +} +#basics-guide { + max-width: 760px; + margin: 16px auto 60px; +} +.basics-top, +.basics-stages { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.basics-top > span { + font-size: 0.75rem; + letter-spacing: 0.12em; + color: #b4c8d9; +} +.basics-stages { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + margin: 24px 0; + color: #a0aabb; +} +.basics-stages button { + display: flex; + align-items: center; + justify-content: flex-start; + gap: 10px; + min-height: 52px; + margin: 0; + padding: 10px 12px; + border: 0; + border-bottom: 3px solid transparent; + border-radius: 0; + font-size: inherit; + line-height: 1.3; + text-align: left; +} +.basics-stages .step-number { + display: grid; + place-items: center; + width: 26px; + height: 26px; + flex: 0 0 26px; + border: 1px solid currentColor; + border-radius: 50%; + font-size: .8rem; +} +.basics-stages .active { + color: #b8ffe3; + border-bottom-color: #74e8bd; + background: #142b32; +} +#basics-guide h1 { + font-size: clamp(1.5rem, 4vw, 2.25rem); + line-height: 1.2; +} +.basics-explanation { + max-width: 62ch; + line-height: 1.65; + min-height: 4.5em; +} +.basics-program button { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px 8px; +} +.basics-program button:disabled { + opacity: 1; + color: #b9c9d7; + background: #17232e; + cursor: default; +} +.basics-program button:not(:disabled), +.basics-program button.current { + outline: 2px solid #74e8bd; + outline-offset: 2px; +} +.basics-program strong, +.basics-card strong { + font-size: 2.2rem; + line-height: 1; +} +.basics-card-area { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; +} +.basics-card { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + min-width: 165px; + padding: 20px; +} +.basics-card.selected { + outline: 3px solid #74e8bd; + outline-offset: 3px; +} +.practice-clock { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 16px; + padding: 18px; + margin: 20px 0; + border: 1px solid #496071; + border-radius: 12px; +} +.practice-clock strong, +.practice-clock small { + display: block; +} +.practice-clock strong { + font-size: 1.35rem; + font-variant-numeric: tabular-nums; +} +#basics-run { + width: 100%; +} +@media (max-width: 520px) { + .basics-top { + align-items: flex-start; + } + .basics-stages { + font-size: 0.85rem; + } + .basics-program { + gap: 7px; + } +} + +.shared-equipment-icon { + fill: none; + stroke: #b7e3e9; + stroke-width: 1.7; + stroke-linecap: round; + stroke-linejoin: round; +} +.system-card .action-key { + width: 22px; + height: 22px; + display: grid; + place-items: center; +} +.action-key .pictogram { + width: 17px; + height: 17px; +} +.ship-key .pictogram { + width: 18px; + height: 18px; + color: var(--gold); +} +#hand-filter .pictogram { + width: 23px; + height: 23px; +} +#resources .symbol-stat small { + font-size: 0.72rem; +} + +/* Crew selectors and board markers share the same drawing and number treatment. */ +.crew-tabs .equipment-art { + width: 27px; + height: 27px; + flex: 0 0 27px; + color: #bfd0db; +} +.crew-tabs [aria-pressed="true"] .equipment-art { + color: #ffe0a0; +} +.crew-pawn { + width: auto; + height: 30px; + gap: 2px; + align-items: center; +} +.crew-pawn > svg.equipment-art { + width: 27px; + height: 27px; + fill: none; + stroke: #162e3d; + stroke-width: 2; +} +.crew-pawn > svg.pictogram { + width: 23px; + height: 27px; + fill: none; + stroke: currentColor; +} +.crew-pawn b { + position: static; + width: auto; + min-width: 8px; + color: currentColor; + text-shadow: none; + font-size: 11px; +} + +.lesson-actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px; + padding-top: 4px; +} +.lesson-actions > button { + min-height: 44px; + margin: 0; + padding: 10px 14px; + line-height: 22px; +} +.lesson-actions > .icon-button { + width: 44px; + padding: 10px; + flex: 0 0 44px; +} +.lesson-actions .pictogram { + width: 22px; + height: 22px; +} +.basics-card-choices { + display: flex; + justify-content: center; + flex-wrap: wrap; + gap: 16px; +} +.basics-card-choices .basics-card { + min-width: 135px; +} +.basics-program strong .pictogram, +.basics-card strong .pictogram { + width: 32px; + height: 32px; +} +.basics-card-choices .basics-card { + min-width: 88px; + min-height: 80px; +} + +/* Teach on the real ship; reveal its systems in later lessons. */ +.training-ship { + max-width: 530px; + margin: 20px auto 28px; +} +.training-ship .systems, +.training-ship .between-decks, +.training-ship .ship-passage, +.training-ship .ship-key, +.training-ship .damage { + display: none; +} +.training-ship .deck-upper .station { + min-height: 88px; +} +.training-ship .deck-upper .occupants { + align-items: center; + min-height: 50px; + padding: 8px 0; +} +.training-ship .deck-lower { + margin-top: 10px; + opacity: 0.25; +} +.training-ship .deck-lower .station { + min-height: 88px; +} +.training-ship .deck-lower .occupants { + display: none; +} +.training-ship .crew-pawn > svg.equipment-art { + width: 36px; + height: 36px; +} +.training-ship .crew-pawn { + height: 38px; +} +.basics-program-heading { + display: flex; + gap: 8px; + align-items: center; + margin-bottom: 10px; + color: #b9c9d7; + font-size: 0.85rem; +} +.basics-program.program { + display: flex; + gap: 16px; + justify-content: flex-start; + margin: 0 0 20px; + padding: 14px; + border-left: 3px solid #e6b66b; + background: #101e28; + border-radius: 0 8px 8px 0; +} +.basics-program button.slot { + width: 76px; + min-height: 90px; + flex: 0 0 76px; + border-radius: 6px; + gap: 16px; +} +.basics-program .turn { + font-size: 0.72rem; +} +.basics-card-area { + align-items: flex-start; +} + +/* BGS checkpoint controller, with a localized guide matching the ship console. */ +.native-guide { margin: 0 0 24px; } +.native-guide-top, .native-guide-tools, .native-guide-controls { + display: flex; align-items: center; gap: 12px; flex-wrap: wrap; +} +.native-guide-top { justify-content: space-between; color: #b4c8d9; } +.native-guide-tools a { color: #a9d7e7; font-size: .8rem; } +.native-guide h1 { font-size: clamp(1.4rem, 3vw, 2rem); margin: 20px 0 8px; } +.native-guide-text { line-height: 1.6; white-space: pre-line; max-width: 65ch; } +.native-guide-controls { margin-top: 16px; } +.native-guide-controls small { color: #9db0bf; margin-left: auto; } +.native-guide .basics-stages { grid-template-columns: repeat(3, 1fr); margin: 16px 0; } +.native-tutorial .basics-top, +.native-tutorial #basics-guide > .basics-stages, +.native-tutorial #basics-guide > h1, +.native-tutorial .basics-explanation, +.native-tutorial #basics-start, +.native-tutorial .basics-complete, +.native-tutorial #console-nav, +.native-tutorial .header-tools, +.native-tutorial .mission-line, +.native-tutorial #crew, +.native-tutorial #lesson-guide > ol, +.native-tutorial #lesson-guide [data-lesson] { display: none; } +.native-tutorial #basics-guide { margin-top: 0; } +.native-tutorial .training-ship { margin-top: 0; } +.practice-readiness { display: flex; align-items: center; gap: 12px; margin: 12px 0; color: #b8ffe3; } +.practice-readiness progress { width: 80px; height: 6px; accent-color: #74e8bd; } +@media (max-width: 520px) { + .native-guide .basics-stages { gap: 3px; } + .native-guide .basics-stages button { flex-direction: column; gap: 6px; padding: 10px 4px; text-align: center; } + .native-guide-controls small { width: 100%; margin: 0; } +} +.native-tutorial #basics-run { width: 64px; height: 48px; } +.practice-readiness > span { display: inline-flex; align-items: center; gap: 6px; } +.native-tutorial.learning-basics .flight-layout { display: grid !important; margin: 0; align-items: start; } +.native-tutorial.learning-basics #planning { min-width: 0; } +.native-tutorial.learning-basics #program { display: flex; gap: 12px; border-left: 3px solid #e6b66b; padding: 12px; background: #101e28; } +.native-tutorial.learning-basics #program .slot { flex: 0 0 72px; min-height: 90px; } +.native-tutorial.learning-basics #program .slot.current { border-color: #74e8bd; box-shadow: 0 0 0 2px #74e8bd55; } +.native-tutorial.learning-basics #hand { grid-template-columns: repeat(2, 80px); } +.native-tutorial.learning-basics #hand .card { min-height: 68px; } +.native-tutorial.learning-basics #hand .copies, +.native-tutorial.learning-basics #program-crew, +.native-tutorial.learning-basics .crew-tabs, +.native-tutorial.learning-basics #player-help, +.native-tutorial.learning-basics #card-help, +.native-tutorial.learning-basics #controls, +.native-tutorial.learning-basics #hand-filter, +.native-tutorial.learning-basics #resources, +.native-tutorial.learning-basics #threats, +.native-tutorial.learning-basics #comms, +.native-tutorial.learning-basics #latest, +.native-tutorial.learning-basics #replay, +.native-tutorial.learning-basics .tactical .section-heading:has(#threat-title), +.native-tutorial[data-tutorial-step="0"] #planning { display: none !important; } + +.native-tutorial.learning-basics .tactical { max-width: 600px; } +.native-tutorial.learning-basics #ship { width: 100%; max-width: 600px; margin: 0; } +.ready-dots { display: flex; gap: 6px; } +.ready-dots i { display: block; width: 14px; height: 18px; border: 1px solid #688999; border-radius: 3px; } +.ready-dots i.filled { background: #74e8bd; border-color: #74e8bd; } +.practice-readiness #basics-run { margin-left: auto; } +@media (max-width: 720px) { + .native-tutorial.learning-basics .flight-layout { grid-template-columns: 1fr; } +} +.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-step="3"] #controls { display: none !important; } + +.training-ship .deck-upper .station, +.training-ship .deck-lower .station { min-height: 104px; } diff --git a/preview/tactical.js b/preview/tactical.js index 89122c8..6aee1b9 100644 --- a/preview/tactical.js +++ b/preview/tactical.js @@ -1,5 +1,5 @@ import { illustration, threatIllustration } from "./art.js"; -import { pictogram, shipLocator } from "./icons.js"; +import { pictogram, shipLocator, equipmentPicture } from "./icons.js"; export function createTacticalView({ t, @@ -8,6 +8,13 @@ export function createTacticalView({ zoneName, playerColor = () => "", }) { + const actionName = (key) => + ({ + A: t("Armes", "Weapons"), + B: t("Énergie", "Energy"), + C: t("Systèmes", "Systems"), + })[key]; + const actionWords = (text) => text.replace(/\b[ABC]\b/g, actionName); const meter = (value, capacity) => ``; @@ -77,15 +84,15 @@ export function createTacticalView({ "Perform C here on turns 1–2, 4–5 and 8–9 to maintain the computer each phase and avoid delaying programs.", ), "blue-upper": t( - "C prend les robots de cette salle, ou réactive ceux que vous portez déjà.", + "C prend les robots de combat de cette salle, ou réactive ceux que vous portez déjà.", "C takes this room’s battlebots, or reactivates the team you already carry.", ), "red-lower": t( - "C prend les robots de cette salle, ou réactive ceux que vous portez déjà.", + "C prend les robots de combat de cette salle, ou réactive ceux que vous portez déjà.", "C takes this room’s battlebots, or reactivates the team you already carry.", ), "red-upper": t( - "Avec des robots actifs, C vous fait décoller en intercepteur. Un seul équipier peut être dans l’espace à la fois.", + "Avec des robots de combat actifs, C vous fait décoller en intercepteur. Un seul équipier peut être dans l’espace à la fois.", "With active battlebots, C launches you in an interceptor. Only one crew member can be in space at a time.", ), "white-lower": t( @@ -99,15 +106,21 @@ export function createTacticalView({ }[station]; const flow = `
${illustration(sourceIcon)}${sourceValue}${esc(sourceName)}${pictogram("right")}${illustration(system)}${s[system]}/${capacity}${esc(energyName)}
`; const details = (key, art, text, extra = "") => - ``; + ``; return `
-
${details("A", weaponArt, fireText, `
${symbol("hull", `${t("Puissance", "Power")} ${power}`, power)}${symbol(light ? "check" : "reactor", light ? t("Batterie autonome", "Own battery") : t("Coût : 1 énergie", "Cost: 1 energy"), light ? t("Autonome", "Own battery") : "−1")}
`)}
-
${details("B", system, chargeText, flow)}
-
${details("C", cIcon, cText)}
+
${details("A", weaponArt, fireText, `
${symbol("hull", `${t("Puissance", "Power")} ${power}`, power)}${symbol(light ? "check" : "reactor", light ? t("Batterie autonome", "Own battery") : t("Coût : 1 énergie", "Cost: 1 energy"), light ? t("Autonome", "Own battery") : "−1")}
`)}
+
${details("B", system, chargeText, flow)}
+
${details("C", cIcon, cText)}
`; } - function shipCutaway({ ship, selectedCrew, canPlan, crewLabel }) { + function shipCutaway({ + ship, + selectedCrew, + canPlan, + crewLabel, + isAndroid = () => false, + }) { const zones = ["red", "white", "blue"]; const movementHelp = (lift) => ``; @@ -128,8 +141,8 @@ export function createTacticalView({ const [cIcon, c] = { "red-upper": ["interceptor", t("Intercepteurs", "Interceptors")], "white-upper": ["computer", t("Ordinateur", "Computer")], - "blue-upper": ["bots", t("Robots", "Battlebots")], - "red-lower": ["bots", t("Robots", "Battlebots")], + "blue-upper": ["bots", t("Robots de combat", "Battlebots")], + "red-lower": ["bots", t("Robots de combat", "Battlebots")], "white-lower": [ "observation", t("Observation", "Visual confirmation"), @@ -147,12 +160,12 @@ export function createTacticalView({ level === "upper" ? t("Pont supérieur", "Upper deck") : t("Pont inférieur", "Lower deck"); - return `
${esc(zoneName(zone))}${symbol(level === "upper" ? "up" : "down", deckName)}${level === "upper" && s.damage.length ? `${symbol("warning", `${t("Dégâts de la zone", "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) => `${p.id + 1}${p.bots !== null ? `${pictogram("bots")}` : ""}`).join("")}
`; + return `
${symbol(level === "upper" ? "up" : "down", deckName)}${level === "upper" && s.damage.length ? `${symbol("warning", `${t("Dégâts de la zone", "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( "", )}${[1, 2].map((i) => `
${movementHelp(false)}
`).join("")}`; - return `${deck("upper")}
${zones.map((z) => `
${movementHelp(true)}
`).join("")}
${deck("lower")}
A${t("Tirer", "Fire")}B${t("Énergie", "Energy")}C${t("Systèmes", "Systems")}
`; + return `
${deck("upper")}
${zones.map((z) => `
${movementHelp(true)}
`).join("")}
${deck("lower")}
${pictogram("A")}${t("Tirer", "Fire")}${pictogram("B")}${t("Énergie", "Energy")}${pictogram("C")}${t("Systèmes", "Systems")}
`; } function threatPortrait(th) { @@ -180,7 +193,7 @@ export function createTacticalView({ .join(", ")}` : `${t("Trajectoire", "Trajectory")} : ${zoneName(th.zone)}`; const target = `${shipLocator(stations, internal ? null : th.zone)}`; - return `${visual}${symbol("hull", `${t("Points de vie", "Hit points")} : ${hp}/${th.hp}`, `${hp}/${th.hp}`)}${target}${symbol("shield", `${t("Bouclier", "Shield")} : ${th.shield}`, `${th.shield}`)}${status ? `${esc(status)}` : ""}`; + return `${target}${visual}${symbol("hull", `${t("Points de vie", "Hit points")} : ${hp}/${th.hp}`, `${hp}/${th.hp}`)}${symbol("shield", `${t("Bouclier", "Shield")} : ${th.shield}`, `${th.shield}`)}${status ? `${esc(status)}` : ""}`; } return { shipCutaway, threatPortrait }; } diff --git a/preview/tutorial-entry.js b/preview/tutorial-entry.js new file mode 100644 index 0000000..95499f6 --- /dev/null +++ b/preview/tutorial-entry.js @@ -0,0 +1,7 @@ +import { mountLesson } from "../bgs/tutorial.js"; +const query = new URL(location.href).searchParams; +mountLesson(document.body, { + chapter: query.get("chapter") ?? "basics", + locale: query.get("locale") ?? "fr", + standalone: true, +}).catch(error => { document.body.textContent = error.message; }); diff --git a/src/tutorial-controller.js b/src/tutorial-controller.js new file mode 100644 index 0000000..795e804 --- /dev/null +++ b/src/tutorial-controller.js @@ -0,0 +1,50 @@ +import { createTutorial } from "@boardgamers/protocol/tutorial"; +import { LESSONS, createLesson } from "./tutorials.js"; +import { advanceClock, submit } from "./session.js"; + +export function completedTurns(state) { + const r = state.game.resolution; + return r?.step === "damage" ? r.turn : Math.max(0, (r?.turn ?? 0) - 1); +} + +// BGS owns checkpoints and saved action history. All moves still use our engine. +export function createLessonTutorial(id, { locale = "en", storage, onProgress } = {}) { + const lesson = LESSONS.find(l => l.id === id); + if (!lesson) throw Error("Unknown lesson"); + const t = (fr, en) => locale === "fr" ? fr : en; + return createTutorial({ + game: "space-alert", id, version: 2, storage, onProgress, + initialState: () => createLesson(id, 1000), + move(state, move) { + 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]); + } + if (move.type === "practice-clock") { + if (state.stage !== "programming") throw Error("Planning has ended"); + state.tutorial.clockRunning = !!move.running; + state.revision++; + return state; + } + if (move.type === "practice-tick") { + if (!state.tutorial.clockRunning || state.stage !== "programming") return state; + if (!Number.isSafeInteger(move.ms) || move.ms < 0) throw Error("Invalid practice time"); + return advanceClock(state, state.observedAt + move.ms); + } + const result = submit(state, 0, { ...move, sequence: state.players[0].lastSequence + 1 }, state.observedAt); + if (!result.accepted) throw Error(result.error); + return result.state; + }, + 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.map(p => p[locale === "fr" ? 0 : 1]).join("\n\n") }, + { id: "plan", title: t("Préparer le programme", "Plan the program"), + text: lesson.basics ? t("Placez deux flèches dans le programme. Le vaisseau attend. La troisième case reste vide : attendre.", "Place two arrows in the program. The ship waits. The third slot stays empty: wait.") : t("Programmez les cartes sur le vaisseau, puis terminez la programmation. Le chrono est facultatif ici.", "Program cards on the ship, then finish planning. The clock is optional here."), + complete: state => state.stage === "resolution" }, + { id: "execute", title: t("Exécuter les tours", "Run the turns"), + text: t("Programme verrouillé. Avancez la résolution avec ▶. Les équipiers agissent ensemble, puis les menaces.", "Program locked. Advance resolution with ▶. Crew act together, then threats."), + complete: state => lesson.basics ? completedTurns(state) >= 3 : !!state.game.resolution?.outcome }, + ], + completion: { title: t("Exercice terminé", "Exercise complete"), text: lesson.basics ? t("Le chrono sert à préparer. Les tours exécutent ensuite votre programme. Une case vide signifie attendre.", "The clock is for planning. Turns then execute your program. An empty slot means wait.") : t("Rejouez pour comparer un autre programme, ou passez à la suite.", "Replay to compare another program, or move on.") }, + }); +} diff --git a/src/tutorials.js b/src/tutorials.js index af6fc06..330fc07 100644 --- a/src/tutorials.js +++ b/src/tutorials.js @@ -9,6 +9,12 @@ const lesson = (id, title, instructions, options = {}) => ({ ...options, }); export const LESSONS = [ + lesson( + "basics", + ["Commencer ici : programmer les tours", "Start here: planning turns"], + [], + { basics: true }, + ), lesson( "first-shot", ["Votre premier tir", "Your first shot"], @@ -155,7 +161,7 @@ export function createLesson(id, now) { id: `lesson-${id}`, title: l.title[1], doubleActions: !!l.doubleActions, - phaseEndsMs: [600000, 1200000], + phaseEndsMs: [300000, 600000], events: l.threat ? [ { @@ -186,7 +192,13 @@ export function createLesson(id, now) { ); s = submit(s, 0, { type: "ready", sequence: 1 }, now).state; s = advanceClock(s, now + 3000); - s.tutorial = { id, title: l.title, instructions: l.instructions }; + s.tutorial = { + id, + title: l.title, + instructions: l.instructions, + basics: !!l.basics, + clockRunning: false, + }; s.game.tracks = Object.fromEntries( ["red", "white", "blue", "internal"].map((z) => [ z, diff --git a/test/bgs.test.js b/test/bgs.test.js index 8c943c4..04a2468 100644 --- a/test/bgs.test.js +++ b/test/bgs.test.js @@ -227,3 +227,66 @@ test("career progress is bounded, contains no mission secrets, and rejects unkno assert.equal(next.players[0].ready, false); assert.equal(next.players[0].lastSequence, 0); }); + +test("table careers survive sitting out a game without gating the current crew", () => { + const old = initial({ careers: true }); + old.bgs.explorers.alice.level = 2; + old.bgs.explorers.alice.xp = 24; + // Bob is still level zero and must not prevent Alice's solo campaign. + const progress = e.tableProgress(e.dropPlayer(old)); + const solo = e.init( + 1, + [], + { careers: true, campaign: 3 }, + "solo", + 0, + ctx(2000, { + gameId: "solo", + playerIds: ["alice"], + present: [0], + table: { id: "table", round: 2, progress }, + }), + ); + assert.equal(solo.bgs.explorers.bob.level, 0); + assert.deepEqual( + e.stripSecret(solo, 0, ctx(2000)).explorers.map((x) => x.id), + ["alice"], + ); + const soloProgress = e.tableProgress(e.dropPlayer(solo)); + const disabled = e.init( + 1, + [], + { careers: false }, + "disabled", + 0, + ctx(3000, { + gameId: "disabled", + playerIds: ["bob"], + present: [0], + table: { id: "table", round: 3, progress: soloProgress }, + }), + ); + assert.deepEqual(e.stripSecret(disabled, 0, ctx(3000)).explorers, []); + const returned = e.init( + 2, + [], + { careers: true }, + "return", + 0, + ctx(4000, { + gameId: "return", + playerIds: ["bob", "alice"], + table: { + id: "table", + round: 4, + progress: e.tableProgress(e.dropPlayer(disabled)), + }, + }), + ); + assert.equal(returned.bgs.explorers.alice.xp, 24); + assert.equal(returned.bgs.explorers.alice.level, 2); + assert.equal(returned.bgs.explorers.alice.activeRun, null); + assert.equal(returned.players[1].lastSequence, 0); + assert.equal(returned.players[1].ready, false); + assert.equal(progress.data.explorers.alice.xp, 24); +}); diff --git a/test/preview.test.js b/test/preview.test.js index be5c457..a488b4d 100644 --- a/test/preview.test.js +++ b/test/preview.test.js @@ -205,3 +205,96 @@ test("untimed lessons advance only explicitly and remain paused after restart", await rm(dir, { recursive: true, force: true }); } }); + +test("practice clock starts, pauses, resumes without charging paused time, and rejects ordinary games", async () => { + let now = 1000; + const server = createPreviewServer({ clock: () => now }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const base = `http://127.0.0.1:${server.address().port}`; + const post = (path, body) => + fetch(base + path + "?seat=0", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + const state = () => fetch(base + "/api/state?seat=0").then((r) => r.json()); + try { + assert.equal( + (await post("/api/lesson-clock", { running: true })).status, + 400, + ); + let s = await (await post("/api/lesson", { lesson: "basics" })).json(); + const start = s.serverNow; + now += 1000000; + assert.equal((await state()).serverNow, start); + s = await (await post("/api/lesson-clock", { running: true })).json(); + assert.equal(s.tutorial.clockRunning, true); + now += 12000; + s = await (await post("/api/lesson-clock", { running: false })).json(); + assert.equal(s.serverNow, start + 12000); + now += 1000000; + assert.equal((await state()).serverNow, start + 12000); + await post("/api/lesson-clock", { running: true }); + now += 5000; + assert.equal((await state()).serverNow, start + 17000); + now += 300000; + s = await state(); + assert.equal(s.phase, 2); + assert.equal(s.game.ship.crew[0].station, "white-upper"); + await post("/api/lesson-clock", { running: false }); + now += 1000000; + assert.equal((await state()).phase, 2); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + +test("basics can return from playback to an editable plan with cards preserved", async () => { + const server = createPreviewServer({ clock: () => 1000 }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const base = `http://127.0.0.1:${server.address().port}`; + const post = async (path, body = {}) => { + const response = await fetch(base + path + "?seat=0", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + assert.equal(response.status, 200); + return response.json(); + }; + try { + let s = await post("/api/lesson", { lesson: "basics" }); + const card = s.game.hand.find(c => c.sides.some(side => side[0] === "blue")); + s = (await post("/api/command", { + type: "program", sequence: s.nextSequence, crew: 0, turn: 1, + slotVersion: s.game.programs[0][0].revision, + cards: [{ id: card.id, side: card.sides.findIndex(side => side[0] === "blue") }], + })).view; + const plan = structuredClone(s.game.programs[0]); + await post("/api/lesson-next"); + s = await post("/api/lesson-next"); + for (let i = 0; i < 10; i++) { + s = (await post("/api/command", { type: "resolve", sequence: s.nextSequence })).view; + if (s.game.resolution.turn === 1 && s.game.resolution.step === "damage") break; + } + assert.equal(s.game.ship.crew[0].station, "blue-upper"); + const revision = s.revision; + s = await post("/api/lesson-back"); + assert.equal(s.stage, "programming"); + assert.equal(s.phase, 1); + assert.equal(s.tutorial.clockRunning, false); + assert.ok(s.revision > revision); + assert.equal(s.game.ship.crew[0].station, "white-upper"); + assert.deepEqual(s.game.programs[0], plan); + const removed = await post("/api/command", { + type: "remove", sequence: s.nextSequence, crew: 0, turn: 1, + slotVersion: s.game.programs[0][0].revision, + }); + assert.equal(removed.accepted, true); + } finally { + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/test/tutorial-controller.test.js b/test/tutorial-controller.test.js new file mode 100644 index 0000000..1c3056e --- /dev/null +++ b/test/tutorial-controller.test.js @@ -0,0 +1,55 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { snapshot } from "../src/view.js"; +import { createLessonTutorial, completedTurns } from "../src/tutorial-controller.js"; + +async function place(tutorial, turn, direction) { + const s = tutorial.snapshot.state; + const id = s.game.hands[0].find(id => s.game.cards[id].sides.some(side => side.length === 1 && side[0] === direction)); + const side = s.game.cards[id].sides.findIndex(side => side.length === 1 && side[0] === direction); + assert.equal(await tutorial.play({ type: "program", crew: 0, turn, + slotVersion: s.game.slotVersions[0][turn - 1], cards: [{ id, side }] }), true, tutorial.snapshot.error); +} + +test("BGS tutorial validates moves, saves progress, and restores native checkpoints", async () => { + const data = new Map(); + const storage = { getItem: key => data.get(key), setItem: (key, value) => data.set(key, value) }; + const t = await createLessonTutorial("basics", { storage }); + assert.equal(t.snapshot.step, 0); + await t.continue(); + await place(t, 1, "blue"); + await place(t, 2, "red"); + assert.equal(snapshot(t.snapshot.state, 0).game.ship.crew[0].station, "white-upper"); + assert.equal(t.snapshot.step, 1); + await t.play({ type: "practice-phase" }); + await t.play({ type: "practice-phase" }); + assert.equal(t.snapshot.step, 2); + assert.equal(completedTurns(t.snapshot.state), 0); + for (let i = 0; i < 10 && completedTurns(t.snapshot.state) < 1; i++) + assert.equal(await t.play({ type: "resolve" }), true); + assert.equal(t.snapshot.state.game.resolution.ship.crew[0].station, "blue-upper"); + const restored = await createLessonTutorial("basics", { storage }); + assert.deepEqual(restored.snapshot.state, t.snapshot.state); + await restored.restartStep(); + assert.equal(restored.snapshot.step, 2); + assert.equal(completedTurns(restored.snapshot.state), 0); + assert.ok(restored.snapshot.state.game.programs[0][0].cards.length); + await restored.previousStep(); + assert.equal(restored.snapshot.step, 1); + assert.equal(restored.snapshot.state.stage, "programming"); + assert.equal(restored.snapshot.state.game.programs[0][0], null); + await place(restored, 1, "red"); + restored.destroy(); t.destroy(); +}); + +test("practice clock advances planning only; resolution remains untimed", async () => { + const t = await createLessonTutorial("basics"); + await t.continue(); + await t.play({ type: "practice-clock", running: true }); + await t.play({ type: "practice-tick", ms: 600000 }); + assert.equal(t.snapshot.step, 2); + assert.equal(completedTurns(t.snapshot.state), 0); + await t.play({ type: "practice-tick", ms: 600000 }); + assert.equal(completedTurns(t.snapshot.state), 0); + t.destroy(); +}); diff --git a/test/tutorials.test.js b/test/tutorials.test.js index a81fc3e..70f240b 100644 --- a/test/tutorials.test.js +++ b/test/tutorials.test.js @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { LESSONS, createLesson } from "../src/tutorials.js"; +import { snapshot } from "../src/view.js"; import { submit, advanceClock } from "../src/session.js"; import { traitDescriptions, @@ -119,3 +120,20 @@ test("every catalogue effect has explanatory FR and EN text, and replay names wo /Fighter/, ); }); + +test("first lesson separates planning from movement and an empty turn waits", () => { + let s = createLesson("basics", 0); + s = program(s, 0, 1, ["blue"]); + s = program(s, 0, 2, ["red"]); + assert.equal(snapshot(s, 0).game.ship.crew[0].station, "white-upper"); + const r = resolve(s); + for (const [turn, station] of [ + [1, "blue-upper"], + [2, "white-upper"], + [3, "white-upper"], + ]) { + const frame = r.frames.find((f) => f.turn === turn && f.step === "damage"); + assert.equal(frame.ship.crew[0].station, station); + } + assert.equal(r.threats.length, 0); +});