Master-of-Vega-Tutorial #3

Merged
brianfertig merged 2 commits from Master-of-Vega-Tutorial into main 2026-08-29 17:13:26 +00:00
14 changed files with 1933 additions and 9 deletions

Binary file not shown.

View File

@ -0,0 +1,343 @@
{
"version": 1,
"vars": ["species"],
"confirmSkip": {
"body": "Are you sure you want to skip the entire tutorial?",
"confirmLabel": "Skip tutorial",
"cancelLabel": "Keep learning"
},
"steps": [
{
"id": "intro",
"kind": "modal",
"voice": "vega/tutorial-intro-01",
"body": "All alone. Your species, the {species}, has spent its entire existence on a single planet.... but no more. Recent advances have given you the ability to explore and colonize nearby stars. It is time for your species to begin your exploration of the universe. Soon, you will find you're not alone afterall. But for now, you have prepared a scout ship and a colony ship with a singular mission: Find a habitable planet nearby to begin your expansion.",
"highlights": [],
"buttons": [
{ "action": "skip", "label": "Skip tutorial" },
{ "action": "next", "label": "Next" }
]
},
{
"id": "your-fleet",
"kind": "callout",
"voice": null,
"anchor": "homeFleet",
"highlights": ["homeFleet", "homeStar"],
"calloutText": "This is your fleet. A Scout Ship and Colony Ship. Click here to select them.",
"advanceOn": "hotspot",
"hotspotAction": "selectHomeFleet",
"buttons": []
},
{
"id": "ship-profiles",
"kind": "callout",
"voice": null,
"anchor": "fleetShipProfiles",
"highlights": ["fleetShipProfiles"],
"calloutText": "These are the ships in your fleet. Click on a ship's profile picture or video to view details of that ship.",
"advanceOn": "shipDetailClosed",
"buttons": []
},
{
"id": "ship-counts",
"kind": "callout",
"voice": null,
"anchor": "fleetCountControls",
"highlights": ["fleetCountControls"],
"calloutText": "You can remove or increase or decrease the number of ships in this fleet by clicking one of these buttons.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "nearby-stars",
"kind": "callout",
"voice": null,
"anchor": "homeFleet",
"highlights": ["homeFleet", "homeStar", "nearbyStars"],
"calloutText": "Your fleet isn't limited to your home star — it can also travel to any of the other stars highlighted nearby.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "map-controls",
"kind": "callout",
"voice": null,
"anchor": "homeFleet",
"highlights": ["mapArea"],
"freePan": true,
"calloutText": "Before you send your fleet anywhere, here's how to get around the map. Click and drag anywhere to pan in any direction. Scroll your mouse wheel up to zoom in, or down to zoom out. Try it now, then click Next when you're ready.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "click-star",
"kind": "callout",
"voice": null,
"anchor": "nearbyStars",
"highlights": ["nearbyStars"],
"starPick": "info",
"advanceOn": "starPick",
"fitReachableStars": true,
"calloutText": "Now click on one of the highlighted stars to see what's there.",
"buttons": []
},
{
"id": "read-star-info",
"kind": "callout",
"voice": null,
"anchor": "panel",
"highlights": ["panel"],
"calloutText": "This star hasn't been explored yet, so for now the panel only shows its class and a general description — different star classes support different amounts of population. Once a scout of yours actually reaches a system, this same panel will also reveal its worlds, how many of them are habitable for your species, and any colonies or fleets stationed there.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "move-fleet",
"kind": "callout",
"voice": null,
"anchor": "panel",
"highlights": ["nearbyStars", "panel"],
"starPick": "order",
"advanceOn": "fleetInFlight",
"selectHomeFleet": true,
"calloutText": "Let's send your fleet on its way. Click one of the highlighted stars again, then review the order in this panel and press Accept to launch your fleet.",
"buttons": []
},
{
"id": "fleet-moving",
"kind": "callout",
"voice": null,
"anchor": "travelingFleet",
"highlights": ["travelingFleet"],
"calloutText": "Your fleet is now underway! The number above it shows how many turns remain until it arrives at its destination.",
"buttons": [
{ "action": "next", "label": "Got it!" }
]
},
{
"id": "home-star",
"kind": "callout",
"voice": null,
"anchor": "homeStar",
"highlights": ["homeStar"],
"calloutText": "This is your home star. Click it to see your system's information.",
"advanceOn": "hotspot",
"hotspotAction": "showHomeStar",
"buttons": []
},
{
"id": "home-star-info",
"kind": "callout",
"voice": null,
"anchor": "panel",
"highlights": ["panel", "homeStar"],
"calloutText": "This panel shows your home system: how many worlds orbit it and how many are habitable, your colony's population, factories, output, and defences, and what it's currently building. Press View System at the bottom to see the whole system in detail.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "view-system",
"kind": "callout",
"voice": null,
"anchor": "panel",
"highlights": ["panel"],
"calloutText": "Press View System to open a detailed view of your home system.",
"advanceOn": "hotspot",
"hotspotAction": "openSystemView",
"buttons": []
},
{
"id": "system-view-planets",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"body": "This is your system view. Click on any of the worlds orbiting your star to inspect it — the panel on the right updates with its type, size, and richness.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "system-view-colony",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceOn": "external",
"body": "Click on your home world — the one flying a small colony flag above it — then press View Colony to open its colony screen.",
"buttons": []
},
{
"id": "colony-overview",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "colonyCenter",
"body": "This is your colony screen — everything you need to run this world lives here. The panel on the right shows its population, factories, output, trade, and defences.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "colony-allocation",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "colonyCenter",
"body": "Below that, the Allocation sliders split your production across five channels: Construction, Defence, Industry, Ecology, and Research. Drag a slider to change its share — the rest renormalise automatically. Click a channel's lock icon to hold its share fixed while you adjust the others. Ecology is always funded first, off the top.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "colony-focus",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "colonyCenter",
"body": "Colony Focus automates your build queue toward a goal — Expansion, Colony Improvement, Research, Fleet Production, Population Growth, Trade, or Homeworld Defense — instead of you queuing every building by hand. Allocation Focus applies a one-time preset to the sliders above, tuned to the same kinds of strategies. Open either one and your advisors will point out their recommended pick with a pulsing arrow and a short reason.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "colony-close",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceOn": "external",
"body": "When you're ready, close this colony screen, then close the system view too, to get back to the star map.",
"buttons": []
},
{
"id": "end-turn",
"kind": "callout",
"voice": null,
"anchor": "endTurnButton",
"highlights": ["endTurnButton"],
"calloutText": "You've given your fleet its orders and looked over your colony — press End Turn to advance to the next turn.",
"advanceOn": "hotspot",
"hotspotAction": "endTurn",
"buttons": []
},
{
"id": "empire-menu",
"kind": "callout",
"voice": null,
"anchor": "empireButton",
"highlights": ["empireButton"],
"calloutText": "Your turn is underway. Let's look at the rest of your empire — click the Empire menu to open it.",
"advanceOn": "hotspot",
"hotspotAction": "openEmpireMenu",
"buttons": []
},
{
"id": "open-research",
"kind": "callout",
"voice": null,
"anchor": "empireMenuResearch",
"highlights": ["empireMenuResearch"],
"calloutText": "Click Research to see what your empire is investigating.",
"advanceOn": "hotspot",
"hotspotAction": "openResearch",
"buttons": []
},
{
"id": "research-info",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceAction": "closeEmpireScreenReopenMenu",
"body": "Each tile is a research field — its current level, and a slider (with the same lock icon your colony's allocation sliders have) for how much of your research output feeds it. Click a field to see what you're currently working toward there and what comes after it.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "open-diplomacy",
"kind": "callout",
"voice": null,
"anchor": "empireMenuDiplomacy",
"highlights": ["empireMenuDiplomacy"],
"calloutText": "Click Diplomacy to see your relations with the species you've met.",
"advanceOn": "hotspot",
"hotspotAction": "openDiplomacy",
"buttons": []
},
{
"id": "diplomacy-info",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceAction": "closeEmpireScreenReopenMenu",
"body": "You haven't met another species yet, so this window is empty for now. Once you do, it will list each one here — their portrait, treaty status and attitude toward you, how many colonies and how much power they hold, and a Seek Audience button to open negotiations.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "open-leaders",
"kind": "callout",
"voice": null,
"anchor": "empireMenuLeaders",
"highlights": ["empireMenuLeaders"],
"calloutText": "Click Leaders to see who's available to hire.",
"advanceOn": "hotspot",
"hotspotAction": "openLeaders",
"buttons": []
},
{
"id": "leaders-info",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceAction": "closeEmpireScreenReopenMenu",
"body": "Leaders available for hire are listed here, each with their specialty and a one-time cost. Hire one to post them to a fleet or colony for a standing bonus.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "open-colonies",
"kind": "callout",
"voice": null,
"anchor": "empireMenuColonies",
"highlights": ["empireMenuColonies"],
"calloutText": "Click Colonies to see every world you own in one place.",
"advanceOn": "hotspot",
"hotspotAction": "openColonies",
"buttons": []
},
{
"id": "colonies-info",
"kind": "modal",
"voice": null,
"noDim": true,
"windowPos": "topBanner",
"advanceAction": "closeEmpireScreenAndMenu",
"body": "This lists every colony you own — population, factories, what's building, and its Colony Focus and Allocation Focus — so you can check and adjust any of them from one screen instead of opening each individually.",
"buttons": [
{ "action": "next", "label": "Next" }
]
},
{
"id": "keep-exploring",
"kind": "modal",
"voice": null,
"body": "That's the Empire menu. From here, keep exploring nearby star systems with your scouts — once you find a habitable planet, bring a colony ship and found a new colony there to keep growing your empire.",
"buttons": [
{ "action": "next", "label": "Understood" }
]
}
]
}

View File

@ -1772,6 +1772,71 @@ Mirror-match-bias and species-spread assertions (verifier sections 5/11)
both still passed at their existing tolerances — not re-measured as a both still passed at their existing tolerances — not re-measured as a
standalone figure here. standalone figure here.
## Guided tutorial (2026-08-28)
An in-game guided tutorial that opens on every brand-new game (never a
resumed/loaded one) and is re-triggerable from the ☰ menu ("Replay tutorial",
greyed once the starting fleet has moved/split). Phase 1 ships the framework
plus four steps: a centred intro modal, a "select your fleet" callout, a
"these are your ships" callout over the side panel's ship rows, and a
"change ship counts" callout over the /+/✕ cluster.
- **The script is data.** `data/mastervega-tutorial.json` — an ordered `steps[]`
list, each with `kind` (`modal` | `callout`), `body`/`calloutText`, `voice`
(path under `assets/speech/`, no `.mp3`, or `null`), `highlights[]` /
`anchor` (string ids), `advanceOn` (`hotspot` = click the lit anchor;
`shipDetailClosed` = the player opened and closed a ship detail window),
and `buttons[]` (`{action, label}`, action ∈ next/back/skip/finish). A step
with `buttons: []` is legal only when `advanceOn` is set. `{token}`
placeholders are interpolated against a `vars` allow-list (only `species`
so far → `rules.species[emp.speciesId].plural`). Adding later steps =
editing this file; no code change unless a step needs a **new** highlight
target or advance mode.
- **Target ids** (`TUTORIAL_TARGET_IDS`): `homeStar` / `homeFleet` on the star
map (accent ring), `fleetShipProfiles` / `fleetCountControls` on the side
panel (yellow box). Panel regions resolve through a new
`VegaSidePanel.tutorialRegion(name)` — screen-space union of per-stack rects
recorded in `stackRow()` into `this._tutorRows` on every `rebuild()`, keyed
off `this.x0/this.y0` (the panel's resting position, so it is right even
while the panel is still sliding in).
- **Two modules, split like `VegaGnn` / `VegaGnnScreen`.**
`VegaTutorialData.js` is **Phaser-free** (schema validation, interpolation,
`TUTORIAL_TARGET_IDS`) so `tools/verifyMasterOfVega.js` imports it (section
12). `VegaTutorial.js` is the Phaser half (overlay, callout, hotspot,
state machine). A highlightable thing needs an id in `TUTORIAL_TARGET_IDS`
**and** a `_resolveTarget` case in `VegaTutorial.js`.
- **Darken = four opaque strips framing one rectangular hole** (the union of
the step's resolved highlight rects, padded), NOT a mask cutout — every
target worth highlighting is rectangular. A pulsing accent ring is stroked
around each target on top. Empty `highlights` → one full-screen dim rect.
- **The map is frozen by `scene.modalOpen = true`** for the tutorial's whole
life. That one flag blocks star-map pan/zoom (`blockPointer`/`blockWheel`)
and every map/HUD handler — **but not the side panel's own controls**
(`detailHit`, `tinyButton`, `tinyCircleButton`, `openShipDetail` — none
check `modalOpen`), which is what lets the fleet-ship steps work: the hole
over the panel exposes real, clickable panel widgets (`input.topOnly` is on,
so the dark strips must genuinely not cover them — the four-strip hole does
exactly that). `centerOn(emp.homeStar)` on start. `finish()` restores
`modalOpen = false` + `refreshAll()`, mirroring `openModal`'s `done()`.
- **`D.tutorial = 75`** — deliberately just *below* `D.detail` (76). The
"these are your ships" step tells the player to click a ship profile, which
opens the real `openShipDetail` window; sitting below `D.detail` lets it
layer cleanly on top of the overlay. The step then advances when
`panel.detailOpen` goes true-then-false (polled in `VegaTutorial.update()`).
- The "click here to select them" hotspot is a transparent interactive rect
over the fleet marker; its handler does the real low-level selection
(`scene.selectedFleet = f; map.setSelectedFleet(f); panel.showFleet(f)`,
bypassing `onFleetClick`'s `modalOpen` guard) then `advance()`.
- The skip button opens a small confirm prompt drawn on the tutorial's own
container (not `openModal`), so it never touches `modalOpen`. Skip is a
per-step button in the JSON, present only on the intro step — once the
player clicks Next it is gone. A step with an empty `buttons[]` is legal
**only** when it has `advanceOn: "hotspot"` (the callout step advances by
clicking the fleet, nothing else); `validateTutorialData` enforces that.
- No `VegaLogic` change — runs every new game, so there is no "seen" flag to
serialize. A malformed JSON file is validated in `create()` and disables the
feature with a `console.warn` rather than crashing.
## Files touched to register the game ## Files touched to register the game
`src/data/gamesRegistry.js`, `src/main.js`, `src/scenes/GameRoomScene.js` `src/data/gamesRegistry.js`, `src/main.js`, `src/scenes/GameRoomScene.js`

View File

@ -148,6 +148,7 @@ export const MANIFEST = {
// only the JSON does. // only the JSON does.
mastervega: [ mastervega: [
{ type: 'json', key: 'mastervega-rules', path: 'data/mastervega-rules.json' }, { type: 'json', key: 'mastervega-rules', path: 'data/mastervega-rules.json' },
{ type: 'json', key: 'mastervega-tutorial', path: 'data/mastervega-tutorial.json' },
(scene) => sheetsFrom(scene, 'mastervega-artwork', ['sheets']), (scene) => sheetsFrom(scene, 'mastervega-artwork', ['sheets']),
(scene) => videosFrom(scene, 'mastervega-artwork', 'portraitVideos'), (scene) => videosFrom(scene, 'mastervega-artwork', 'portraitVideos'),
(scene) => nestedVideosFrom(scene, 'mastervega-artwork', 'shipVideos'), (scene) => nestedVideosFrom(scene, 'mastervega-artwork', 'shipVideos'),

View File

@ -44,6 +44,8 @@ import { openCouncilSessionScreen } from './VegaCouncilSession.js';
import { openAudienceScreen } from './VegaAudience.js'; import { openAudienceScreen } from './VegaAudience.js';
import { playIntroVideo } from './VegaIntroVideo.js'; import { playIntroVideo } from './VegaIntroVideo.js';
import { claimAudienceContacts, claimFleetComplaints, canNegotiate } from './VegaDiplomacy.js'; import { claimAudienceContacts, claimFleetComplaints, canNegotiate } from './VegaDiplomacy.js';
import { VegaTutorial } from './VegaTutorial.js';
import { validateTutorialData } from './VegaTutorialData.js';
const SAVE_KEY = 'mastervega-save'; const SAVE_KEY = 'mastervega-save';
// 10 manual slots, independent of the single SAVE_KEY auto-save above (which // 10 manual slots, independent of the single SAVE_KEY auto-save above (which
@ -78,6 +80,12 @@ export default class MasterOfVegaGame extends Phaser.Scene {
// Arcade already relies on instead of a bespoke in-place teardown. // Arcade already relies on instead of a bespoke in-place teardown.
this.pendingSavedState = data?.savedState ?? null; this.pendingSavedState = data?.savedState ?? null;
this.modalOpen = false; this.modalOpen = false;
// Set true by VegaTutorial for the one step that teaches pan/zoom — lets
// the star map's own drag/wheel handlers through despite modalOpen, while
// onStarClick/onFleetClick (and every other modalOpen-gated control)
// still check modalOpen directly and stay frozen. See blockWheel/
// blockPointer below.
this.tutorialFreePan = false;
this.busy = false; this.busy = false;
// Empire indices with a freshly-claimed contact waiting for their // Empire indices with a freshly-claimed contact waiting for their
// full-screen Audience — see runAudienceQueue(). // full-screen Audience — see runAudienceQueue().
@ -95,6 +103,17 @@ export default class MasterOfVegaGame extends Phaser.Scene {
console.info(`[MasterOfVega] procedural art for: ${procedural.join(', ')}`); console.info(`[MasterOfVega] procedural art for: ${procedural.join(', ')}`);
} }
// Guided-tutorial script (data/mastervega-tutorial.json). A malformed file
// must never take the game down with it — log and disable the feature.
this.tutorialData = this.cache.json.get('mastervega-tutorial') ?? null;
if (this.tutorialData) {
const { ok, errors } = validateTutorialData(this.tutorialData);
if (!ok) {
console.warn('[MasterOfVega] tutorial disabled — invalid mastervega-tutorial.json:', errors);
this.tutorialData = null;
}
}
try { try {
this.music = new VegaMusic(this, this.cache.json.get('masterofvega-music')); this.music = new VegaMusic(this, this.cache.json.get('masterofvega-music'));
} catch (err) { /* music is optional */ } } catch (err) { /* music is optional */ }
@ -129,6 +148,8 @@ export default class MasterOfVegaGame extends Phaser.Scene {
} }
teardown() { teardown() {
this.tutorial?.destroy();
this.tutorial = null;
resetSpeechQueue(); resetSpeechQueue();
this.panel?.destroy(); this.panel?.destroy();
this.map?.destroy(); this.map?.destroy();
@ -637,15 +658,17 @@ export default class MasterOfVegaGame extends Phaser.Scene {
onStarClick: (idx) => this.onStarClick(idx), onStarClick: (idx) => this.onStarClick(idx),
onFleetClick: (fleet) => this.onFleetClick(fleet), onFleetClick: (fleet) => this.onFleetClick(fleet),
onEmptyClick: () => this.clearSelection(), onEmptyClick: () => this.clearSelection(),
blockWheel: () => this.modalOpen || !!this.panel?.detailOpen, blockWheel: () => (this.modalOpen && !this.tutorialFreePan) || !!this.panel?.detailOpen,
// A modal blocks the map outright; so does the panel's ship detail // A modal blocks the map outright; so does the panel's ship detail
// pop-over, which veils the whole screen without being a modal. // pop-over, which veils the whole screen without being a modal.
// Otherwise only the side panel's own footprint does (so dragging a // Otherwise only the side panel's own footprint does (so dragging a
// slider there doesn't pan the galaxy underneath it). The old // slider there doesn't pan the galaxy underneath it). The old
// `!this.modalOpen && ...` form always short-circuited to false while a // `!this.modalOpen && ...` form always short-circuited to false while a
// modal was open, which let drags pan the star map right through the // modal was open, which let drags pan the star map right through the
// System View window. // System View window. `tutorialFreePan` punches a narrow exception
blockPointer: (p) => this.modalOpen || !!this.panel?.detailOpen // through modalOpen for pan/zoom only — onStarClick/onFleetClick are
// untouched, so clicking a star or fleet is still fully frozen.
blockPointer: (p) => (this.modalOpen && !this.tutorialFreePan) || !!this.panel?.detailOpen
|| !!this.panel?.containsPoint(p.x, p.y), || !!this.panel?.containsPoint(p.x, p.y),
}); });
@ -663,6 +686,38 @@ export default class MasterOfVegaGame extends Phaser.Scene {
this.buildHud(); this.buildHud();
this.refreshHud(); this.refreshHud();
// A brand-new game (never a resumed/loaded one) opens with the guided
// tutorial. Runs every new game — there is no "seen" flag — and is also
// re-triggerable from the ☰ menu.
if (!savedState) this.startTutorial({ replay: false });
}
// ------------------------------------------------------------- tutorial
startTutorial({ replay = false } = {}) {
if (this.tutorial || !this.tutorialData || !this.map || !this.panel) return;
if (replay && !this.canReplayTutorial()) return;
const emp = this.state.empires[this.state.humanIndex];
const species = this.rules.species[emp?.speciesId]?.plural
?? this.rules.species[emp?.speciesId]?.name ?? 'your people';
this.tutorial = new VegaTutorial(this, {
data: this.tutorialData,
vars: { species },
onFinish: () => { this.tutorial = null; },
});
this.tutorial.start();
}
/** The tutorial's fleet callout needs the untouched starting fleet in orbit
* at the homeworld once it has moved or split there is nothing to point
* at, so the replay entry greys out. */
canReplayTutorial() {
if (!this.tutorialData || !this.map || !this.panel || !this.state) return false;
const emp = this.state.empires[this.state.humanIndex];
if (!emp) return false;
return this.state.fleets.some((f) => f.empireIdx === this.state.humanIndex
&& f.starIdx === emp.homeStar && f.toStar < 0);
} }
// ------------------------------------------------------------------ HUD // ------------------------------------------------------------------ HUD
@ -768,6 +823,7 @@ export default class MasterOfVegaGame extends Phaser.Scene {
['Return to Main Menu', () => this.returnToMainMenu()], ['Return to Main Menu', () => this.returnToMainMenu()],
['Save', () => this.openSaveMenu()], ['Save', () => this.openSaveMenu()],
['Load', () => this.openLoadMenu(), !this.hasAnySaveSlot()], ['Load', () => this.openLoadMenu(), !this.hasAnySaveSlot()],
['Replay tutorial', () => this.startTutorial({ replay: true }), !this.canReplayTutorial()],
['Quit to Arcade', () => this.quitToArcade()], ['Quit to Arcade', () => this.quitToArcade()],
]; ];
@ -1513,6 +1569,7 @@ export default class MasterOfVegaGame extends Phaser.Scene {
update(time, delta) { update(time, delta) {
this.map?.update(time, delta); this.map?.update(time, delta);
this.tutorial?.update?.(time, delta);
} }
// ------------------------------------------------------------ save/load // ------------------------------------------------------------ save/load

View File

@ -570,6 +570,7 @@ export const speciesSpeechClip = (speciesId) => `vega/char-${speciesId}`;
/** Non-species speech clips, addressed the same way. */ /** Non-species speech clips, addressed the same way. */
export const UI_SPEECH = { export const UI_SPEECH = {
chooseSpecies: 'vega/ui-choose-start', chooseSpecies: 'vega/ui-choose-start',
tutorialIntro: 'vega/tutorial-intro-01',
}; };
export function hasSpeciesVideo(scene, speciesId) { export function hasSpeciesVideo(scene, speciesId) {

View File

@ -30,9 +30,13 @@ export const FONT = '"Julius Sans One"';
// actually matters in practice; it sits next to gnn as the other full-screen // actually matters in practice; it sits next to gnn as the other full-screen
// takeover. `intro` is the colony-founding vignette, which opens over the // takeover. `intro` is the colony-founding vignette, which opens over the
// system view it was triggered from and must cover everything except the // system view it was triggered from and must cover everything except the
// end-of-game overlay. // end-of-game overlay. `tutorial` is the guided-tutorial darken overlay — it
// sits above the HUD, side panel and modals, but DELIBERATELY just below
// `detail` so a ship-detail pop-over the tutorial itself invites the player
// to open layers cleanly on top of it; it only runs on a fresh turn-0 game,
// so nothing from `detail` up ever competes with it in practice.
export const D = { export const D = {
map: 1, hud: 30, modal: 60, colony: 70, gnn: 72, council: 73, detail: 76, intro: 78, toast: 80, map: 1, hud: 30, modal: 60, colony: 70, gnn: 72, council: 73, tutorial: 75, detail: 76, intro: 78, toast: 80,
}; };
/** /**

View File

@ -323,6 +323,9 @@ export default class VegaSidePanel {
// The pool survives the wipe; claim what this pass actually uses and let // The pool survives the wipe; claim what this pass actually uses and let
// endFrame() hide and pause the rest. // endFrame() hide and pause the rest.
this.pool.beginFrame(); this.pool.beginFrame();
// Per-stack local-coord rects the guided tutorial points at (ship
// profiles vs. the /+/✕ cluster). Rebuilt every pass like the body.
this._tutorRows = [];
this.y = 90; this.y = 90;
if (this.mode === 'star') this.buildStar(); if (this.mode === 'star') this.buildStar();
else if (this.mode === 'fleet') this.buildFleet(); else if (this.mode === 'fleet') this.buildFleet();
@ -761,9 +764,57 @@ export default class VegaSidePanel {
}).setOrigin(0.5); }).setOrigin(0.5);
this.body.add(count); this.body.add(count);
// Tutorial anchors, in body-local coords (body sits at 0,0 in root).
const ctrlLeft = right - boxSize * 4.3 - boxSize / 2;
this._tutorRows.push({
profiles: {
x: PAD - 4,
y: rowY - 4,
w: Math.min(name.x + name.width, ctrlLeft - 6) - (PAD - 4),
h: rowH + 8,
},
counts: {
x: ctrlLeft - 4,
y: ctrlY - boxSize / 2 - 5,
w: (right + 4) - (ctrlLeft - 4),
h: boxSize + 10,
},
});
this.y = rowY + rowH + 10; this.y = rowY + rowH + 10;
} }
/**
* Screen-space bounding box of a named region of the panel, for the guided
* tutorial's spotlight. `name` is 'shipProfiles' or 'countControls' (union
* across every task-force stack in the fleet view), or 'panel' (the whole
* docked column, whatever mode star/fleet/order it is currently
* showing). Uses the panel's resting position (this.x0/this.y0), not
* this.root.x, so it is correct even while the panel is still sliding in.
*/
tutorialRegion(name) {
if (!this.root?.visible) return null;
if (name === 'panel') return { x: this.x0, y: this.y0, w: W, h: this.h };
if (this.mode !== 'fleet') return null;
const rows = this._tutorRows;
if (!rows || !rows.length) return null;
const key = name === 'shipProfiles' ? 'profiles'
: name === 'countControls' ? 'counts' : null;
if (!key) return null;
let x0 = Infinity;
let y0 = Infinity;
let x1 = -Infinity;
let y1 = -Infinity;
for (const r of rows) {
const b = r[key];
x0 = Math.min(x0, b.x);
y0 = Math.min(y0, b.y);
x1 = Math.max(x1, b.x + b.w);
y1 = Math.max(y1, b.y + b.h);
}
return { x: this.x0 + x0, y: this.y0 + y0, w: x1 - x0, h: y1 - y0 };
}
selectionSummary() { selectionSummary() {
const { rules, state } = this; const { rules, state } = this;
const ships = this.selectedShips(); const ships = this.selectedShips();

View File

@ -21,7 +21,7 @@ import {
coloniesAt, empireColonies, fleetEta, habitableForEmpire, coloniesAt, empireColonies, fleetEta, habitableForEmpire,
} from './VegaLogic.js'; } from './VegaLogic.js';
import { starFrame } from './VegaArt.js'; import { starFrame } from './VegaArt.js';
import { buildZoomLadder, DEFAULT_ZOOM_INDEX } from './VegaZoom.js'; import { buildZoomLadder, DEFAULT_ZOOM_INDEX, pickFitZoomIndex } from './VegaZoom.js';
import { delaunayTriangulate, triangulationEdges } from './VegaDelaunay.js'; import { delaunayTriangulate, triangulationEdges } from './VegaDelaunay.js';
import { describeStarTooltip } from './VegaTooltips.js'; import { describeStarTooltip } from './VegaTooltips.js';
import { ORBIT } from './VegaScreens.js'; import { ORBIT } from './VegaScreens.js';
@ -868,6 +868,34 @@ export default class VegaStarMap {
this.clampPan(); this.clampPan();
} }
/**
* Pick the ladder rung that frames a world-space box (`minX/minY/maxX/
* maxY`, plus `padding` on every side) without cropping it — via
* VegaZoom.pickFitZoomIndex, same math VegaCombatCamera.js's "frame the
* whole fleet" opening shot uses then pan so the box's center lands at
* `(focusX, focusY)` in screen space. `focusX`/`focusY` default to the
* viewport's own center, same as `viewW`/`viewH` default to the full
* screen; the guided tutorial narrows all four so the frame is biased left
* of the docked command panel instead of packing stars in behind it.
*/
fitToWorldBounds(minX, minY, maxX, maxY, {
padding = 0, viewW = GAME_WIDTH, viewH = GAME_HEIGHT,
focusX = GAME_WIDTH / 2, focusY = GAME_HEIGHT / 2,
} = {}) {
const idx = pickFitZoomIndex(this.zooms, maxX - minX, maxY - minY, padding, { viewW, viewH });
this.zoomIndex = idx;
this.zoom = this.zooms[idx];
this.root.setScale(this.zoom);
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
this.root.x = focusX - cx * this.zoom;
this.root.y = focusY - cy * this.zoom;
this.clampPan();
this.refreshLabels();
this.refreshStars();
this.refreshColonyInfo();
}
panToStar(starIdx, duration = 420) { panToStar(starIdx, duration = 420) {
const star = this.state.galaxy.stars[starIdx]; const star = this.state.galaxy.stars[starIdx];
if (!star) return; if (!star) return;

View File

@ -29,7 +29,14 @@ import {
} from './VegaLogic.js'; } from './VegaLogic.js';
export function openSystemView(scene, rules, state, starIdx, art, opts = {}) { export function openSystemView(scene, rules, state, starIdx, art, opts = {}) {
const { viewerIdx = state.humanIndex, onChanged = null, onClose = null } = opts; const {
viewerIdx = state.humanIndex, onChanged = null, onClose = null,
// Fired right when the "View Colony" button opens the colony screen over
// this one — nothing else in the game needs to know that
// (MasterOfVegaGame.js's openSystemViewFor never passes it), but the
// guided tutorial does, since it has no other hook into that click.
onColonyOpen = null,
} = opts;
const star = state.galaxy.stars[starIdx]; const star = state.galaxy.stars[starIdx];
const shell = modalShell(scene, star.name, onClose, { width: 1620, height: 900 }); const shell = modalShell(scene, star.name, onClose, { width: 1620, height: 900 });
@ -357,6 +364,7 @@ export function openSystemView(scene, rules, state, starIdx, art, opts = {}) {
rebuild(); rebuild();
}, },
}); });
onColonyOpen?.(colony);
}, { width: panelW, height: 50, fontSize: 21 })); }, { width: panelW, height: 50, fontSize: 21 }));
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,236 @@
// Master of Vega — tutorial data: schema validation, text interpolation, and
// the highlight-target id registry. Headless, no Phaser imports, so it runs in
// Node (tools/verifyMasterOfVega.js) exactly like VegaTurnReport.js.
//
// The tutorial SCRIPT lives in data/mastervega-tutorial.json — an ordered list
// of steps, each with body/callout text, button labels, a voice clip, and a
// list of highlight-target ids. This file knows nothing about Phaser or the
// scene: it validates the JSON shape, substitutes {token} placeholders, and
// pins the set of target ids the renderer (VegaTutorial.js) knows how to
// resolve to on-screen positions. Anything the renderer can point at has to be
// listed in TUTORIAL_TARGET_IDS here AND have a resolver case in VegaTutorial.
// Every id a step may name in `highlights` or `anchor`. VegaTutorial.js has a
// _resolveTarget() case for each. Adding a new highlightable thing later means
// adding its id here and a resolver there. `homeStar`/`homeFleet` are on the
// star map; `fleetShipProfiles`/`fleetCountControls` are regions of the side
// panel's fleet view, resolved through VegaSidePanel.tutorialRegion().
// `nearbyStars` resolves to an ARRAY of targets (every star in fuel range of
// home, one per star) rather than a single one — VegaTutorial.js flattens it
// when building the highlight/hole list. `mapArea` is a big invisible hole
// (no ring drawn) used only to uncover the map for the pan/zoom lesson.
// `panel` is the docked command panel's whole footprint, regardless of what
// mode (star/fleet/order) it is currently showing. `travelingFleet` is
// whichever of the human player's fleets is currently under way.
// `endTurnButton` is the fixed HUD button (MasterOfVegaGame's scene.endTurnBtn).
// `empireButton` is the fixed HUD "Empire" dropdown toggle (scene.empireBtn).
// The four `empireMenu*` ids are that dropdown's own item rows (Research/
// Diplomacy/Leaders/Colonies, in that fixed order) — each resolves to null
// unless the dropdown (scene.empireMenuLayer) is actually open.
export const TUTORIAL_TARGET_IDS = Object.freeze([
'homeStar', 'homeFleet', 'fleetShipProfiles', 'fleetCountControls',
'nearbyStars', 'mapArea', 'panel', 'travelingFleet', 'endTurnButton',
'empireButton', 'empireMenuResearch', 'empireMenuDiplomacy', 'empireMenuLeaders', 'empireMenuColonies',
]);
const STEP_KINDS = Object.freeze(['modal', 'callout']);
const BUTTON_ACTIONS = Object.freeze(['next', 'back', 'skip', 'finish']);
// Ways a step can progress WITHOUT a button. `hotspot` = a click on the lit
// anchor (what that click actually DOES is the step's own `hotspotAction`
// field, not this one — see HOTSPOT_ACTIONS); `shipDetailClosed` = the player
// opened and then closed a ship detail window; `starPick` = the player
// clicked one of the `nearbyStars` hotspots (see STAR_PICK_MODES — the
// step's own `starPick` field decides what that click does); `fleetInFlight`
// = the player accepted a REAL fleet order through the side panel's own
// Accept button (VegaTutorial polls state.fleets for one under way, since
// that button is not part of the tutorial overlay); `external` = something
// outside the polling/hotspot system calls advance() directly — a callback
// VegaTutorial wired into a real screen it opened itself (System View /
// Colony View), the same reason `starPick`/`hotspot` need no poll either. A
// step with no buttons must declare one of these or it is a dead end.
export const ADVANCE_MODES = Object.freeze([
'hotspot', 'shipDetailClosed', 'starPick', 'fleetInFlight', 'external',
]);
// What clicking a `nearbyStars` hotspot does, independent of `advanceOn`:
// `info` opens that star's read-only panel and immediately advances (paired
// with advanceOn: 'starPick'); `order` quotes a move order for the already-
// selected fleet to that star and does NOT advance — the player still has to
// press the panel's real Accept button (paired with advanceOn: 'fleetInFlight').
export const STAR_PICK_MODES = Object.freeze(['info', 'order']);
// What clicking the single `advanceOn: 'hotspot'` target does — VegaTutorial's
// _onHotspot() switches on this instead of pattern-matching the step's
// `anchor` id, so more than one step can point at the same anchor (e.g. two
// different steps both pointing at 'panel') without colliding.
export const HOTSPOT_ACTIONS = Object.freeze([
'selectHomeFleet', // ring+select the docked home fleet, open its panel
'showHomeStar', // ring+select the home star, open its read-only panel
'openSystemView', // open System View directly for the home star
'endTurn', // unfreeze modalOpen just long enough to fire the real End Turn
'openEmpireMenu', // open the Empire dropdown directly (bypasses its own modalOpen gate)
'openResearch', 'openDiplomacy', 'openLeaders', 'openColonies', // close the dropdown, open that screen directly
]);
// What a `kind:'modal'` step's Next button does before advancing, in
// addition to the button's own `action:'next'` — VegaTutorial's own state
// (which real screen it opened directly, and whether the Empire dropdown
// should reappear behind the next one), not anything the step's JSON needs
// to know the mechanics of.
export const ADVANCE_ACTIONS = Object.freeze([
'closeEmpireScreenReopenMenu', // close whichever Empire-menu screen is open, reopen the dropdown
'closeEmpireScreenAndMenu', // close it, and make sure the dropdown is closed too (the tour is over)
]);
const PLACEHOLDER_RE = /\{([a-zA-Z0-9_]+)\}/g;
/**
* Replace every `{token}` in `str` with `vars[token]`. Tokens with no matching
* key are left untouched (the verifier separately flags any token not declared
* in the file's top-level `vars` allow-list, so an unresolved placeholder is a
* build error, not a silent runtime gap).
*/
export function interpolate(str, vars = {}) {
if (typeof str !== 'string') return str;
return str.replace(PLACEHOLDER_RE, (whole, token) =>
(Object.prototype.hasOwnProperty.call(vars, token) ? String(vars[token]) : whole));
}
/** Every distinct `{token}` appearing anywhere in `str`. */
export function placeholdersIn(str) {
if (typeof str !== 'string') return [];
const out = new Set();
let m;
PLACEHOLDER_RE.lastIndex = 0;
// eslint-disable-next-line no-cond-assign
while ((m = PLACEHOLDER_RE.exec(str))) out.add(m[1]);
return [...out];
}
const isNonEmptyString = (v) => typeof v === 'string' && v.trim().length > 0;
/**
* Validate a parsed tutorial JSON. Returns `{ ok, errors }` `errors` is a
* list of human-readable strings, empty when `ok` is true. Deliberately
* permissive about unknown extra fields (forward-compatible) but strict about
* every field the renderer actually reads.
*/
export function validateTutorialData(json) {
const errors = [];
const fail = (msg) => errors.push(msg);
if (!json || typeof json !== 'object') {
return { ok: false, errors: ['tutorial JSON is not an object'] };
}
if (json.version !== 1) fail(`version must be 1 (got ${JSON.stringify(json.version)})`);
const vars = Array.isArray(json.vars) ? json.vars : [];
if (!Array.isArray(json.vars)) fail('`vars` must be an array of allowed placeholder names');
const cs = json.confirmSkip;
if (!cs || typeof cs !== 'object') {
fail('`confirmSkip` must be an object');
} else {
if (!isNonEmptyString(cs.body)) fail('`confirmSkip.body` must be a non-empty string');
if (!isNonEmptyString(cs.confirmLabel)) fail('`confirmSkip.confirmLabel` must be a non-empty string');
if (!isNonEmptyString(cs.cancelLabel)) fail('`confirmSkip.cancelLabel` must be a non-empty string');
}
if (!Array.isArray(json.steps) || json.steps.length === 0) {
fail('`steps` must be a non-empty array');
return { ok: errors.length === 0, errors };
}
const seenIds = new Set();
json.steps.forEach((step, i) => {
const at = `steps[${i}]`;
if (!step || typeof step !== 'object') { fail(`${at} is not an object`); return; }
if (!isNonEmptyString(step.id)) fail(`${at}.id must be a non-empty string`);
else if (seenIds.has(step.id)) fail(`${at}.id "${step.id}" is duplicated`);
else seenIds.add(step.id);
if (!STEP_KINDS.includes(step.kind)) {
fail(`${at}.kind must be one of ${STEP_KINDS.join('/')} (got ${JSON.stringify(step.kind)})`);
}
if (step.voice !== null && step.voice !== undefined && !isNonEmptyString(step.voice)) {
fail(`${at}.voice must be null or a non-empty string`);
}
if (step.kind === 'modal' && !isNonEmptyString(step.body)) {
fail(`${at} (modal) must have a non-empty body`);
}
if (step.kind === 'callout') {
if (!isNonEmptyString(step.calloutText)) fail(`${at} (callout) must have a non-empty calloutText`);
if (!TUTORIAL_TARGET_IDS.includes(step.anchor)) {
fail(`${at} (callout) anchor must be one of ${TUTORIAL_TARGET_IDS.join('/')} (got ${JSON.stringify(step.anchor)})`);
}
}
const highlights = step.highlights ?? [];
if (!Array.isArray(highlights)) {
fail(`${at}.highlights must be an array`);
} else {
highlights.forEach((h) => {
if (!TUTORIAL_TARGET_IDS.includes(h)) fail(`${at}.highlights has unknown target id ${JSON.stringify(h)}`);
});
}
if (step.advanceOn !== undefined && !ADVANCE_MODES.includes(step.advanceOn)) {
fail(`${at}.advanceOn, when set, must be one of ${ADVANCE_MODES.join('/')} (got ${JSON.stringify(step.advanceOn)})`);
}
if (step.advanceOn === 'hotspot' && !TUTORIAL_TARGET_IDS.includes(step.anchor)) {
fail(`${at}.advanceOn "hotspot" needs a valid anchor`);
}
if (step.advanceOn === 'hotspot' && !HOTSPOT_ACTIONS.includes(step.hotspotAction)) {
fail(`${at}.advanceOn "hotspot" needs a valid hotspotAction (one of ${HOTSPOT_ACTIONS.join('/')}, got ${JSON.stringify(step.hotspotAction)})`);
}
if (step.advanceAction !== undefined && !ADVANCE_ACTIONS.includes(step.advanceAction)) {
fail(`${at}.advanceAction, when set, must be one of ${ADVANCE_ACTIONS.join('/')} (got ${JSON.stringify(step.advanceAction)})`);
}
if (step.starPick !== undefined && !STAR_PICK_MODES.includes(step.starPick)) {
fail(`${at}.starPick, when set, must be one of ${STAR_PICK_MODES.join('/')} (got ${JSON.stringify(step.starPick)})`);
}
if (!Array.isArray(step.buttons)) {
fail(`${at}.buttons must be an array`);
} else if (step.buttons.length === 0 && !ADVANCE_MODES.includes(step.advanceOn)) {
// An empty button row is only legal when the step can be advanced some
// other way — otherwise the player is stuck with nowhere to click.
fail(`${at}.buttons is empty but the step has no advanceOn (${ADVANCE_MODES.join('/')}) to progress`);
} else {
step.buttons.forEach((b, bi) => {
if (!b || typeof b !== 'object') { fail(`${at}.buttons[${bi}] is not an object`); return; }
if (!BUTTON_ACTIONS.includes(b.action)) {
fail(`${at}.buttons[${bi}].action must be one of ${BUTTON_ACTIONS.join('/')} (got ${JSON.stringify(b.action)})`);
}
if (!isNonEmptyString(b.label)) fail(`${at}.buttons[${bi}].label must be a non-empty string`);
});
}
// Every {token} used in visible text must be declared in `vars`.
for (const field of ['title', 'body', 'calloutText']) {
for (const token of placeholdersIn(step[field])) {
if (!vars.includes(token)) fail(`${at}.${field} uses undeclared placeholder {${token}} (add it to top-level "vars")`);
}
}
});
return { ok: errors.length === 0, errors };
}
/**
* Produce the runtime step list: a shallow copy of `json.steps` with `title`,
* `body` and `calloutText` interpolated against `vars`, and `highlights`
* defaulted to `[]`. Assumes the data already passed validateTutorialData.
*/
export function resolveSteps(json, vars = {}) {
return (json.steps ?? []).map((step) => ({
...step,
title: interpolate(step.title, vars),
body: interpolate(step.body, vars),
calloutText: interpolate(step.calloutText, vars),
highlights: step.highlights ?? [],
}));
}

View File

@ -47,10 +47,14 @@ export function buildZoomLadder(worldW, worldH, { steps = ZOOM_STEPS, maxZoom =
* than the area needs VegaCombatCamera.js's "frame the whole fleet" * than the area needs VegaCombatCamera.js's "frame the whole fleet"
* feature is built on this. * feature is built on this.
*/ */
export function pickFitZoomIndex(zooms, boundsW, boundsH, padding = 0) { // `viewW`/`viewH` default to the full screen but can be narrowed to whatever
// area is actually free of docked chrome (the guided tutorial's fit-the-
// reachable-stars step passes the width left of the command panel, so the
// picked rung doesn't pack stars in behind it).
export function pickFitZoomIndex(zooms, boundsW, boundsH, padding = 0, { viewW = GAME_WIDTH, viewH = GAME_HEIGHT } = {}) {
const w = Math.max(1, boundsW + padding * 2); const w = Math.max(1, boundsW + padding * 2);
const h = Math.max(1, boundsH + padding * 2); const h = Math.max(1, boundsH + padding * 2);
const ideal = Math.min(GAME_WIDTH / w, GAME_HEIGHT / h); const ideal = Math.min(viewW / w, viewH / h);
let idx = 0; let idx = 0;
for (let i = 0; i < zooms.length; i += 1) { for (let i = 0; i < zooms.length; i += 1) {
if (zooms[i] <= ideal) idx = i; if (zooms[i] <= ideal) idx = i;

View File

@ -56,12 +56,19 @@ import * as Gnn from '../src/games/mastervega/VegaGnn.js';
import { shipVideoKey, hasShipVideo } from '../src/games/mastervega/VegaShipMedia.js'; import { shipVideoKey, hasShipVideo } from '../src/games/mastervega/VegaShipMedia.js';
// Dependency-free, so what the game room eagerly pulls is checkable here. // Dependency-free, so what the game room eagerly pulls is checkable here.
import { resolveGameAssets } from '../src/data/assetManifest.js'; import { resolveGameAssets } from '../src/data/assetManifest.js';
// Guided-tutorial data: schema/interpolation/target-id registry are Phaser-free
// (VegaTutorial.js is the Phaser half), so the script itself is checkable here.
import {
validateTutorialData, resolveSteps, interpolate, placeholdersIn,
TUTORIAL_TARGET_IDS, ADVANCE_MODES,
} from '../src/games/mastervega/VegaTutorialData.js';
const QUICK = process.argv.includes('--quick'); const QUICK = process.argv.includes('--quick');
const gamesArg = process.argv.find((a) => a.startsWith('--games=')); const gamesArg = process.argv.find((a) => a.startsWith('--games='));
const root = join(dirname(fileURLToPath(import.meta.url)), '..'); const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const rulesJson = JSON.parse(readFileSync(join(root, 'data/mastervega-rules.json'), 'utf8')); const rulesJson = JSON.parse(readFileSync(join(root, 'data/mastervega-rules.json'), 'utf8'));
const artJson = JSON.parse(readFileSync(join(root, 'data/mastervega-artwork.json'), 'utf8')); const artJson = JSON.parse(readFileSync(join(root, 'data/mastervega-artwork.json'), 'utf8'));
const tutorialJson = JSON.parse(readFileSync(join(root, 'data/mastervega-tutorial.json'), 'utf8'));
let failures = 0; let failures = 0;
let passes = 0; let passes = 0;
@ -5925,6 +5932,82 @@ section('11. Combat V2 (per-ship prototype)');
} }
} }
// ---------------------------------------------------------------------------
section('12. Tutorial data');
// ---------------------------------------------------------------------------
{
const { ok, errors } = validateTutorialData(tutorialJson);
check('mastervega-tutorial.json passes schema validation', ok, errors.join('; '));
check('tutorial version is 1', tutorialJson.version === 1, `${tutorialJson.version}`);
const steps = Array.isArray(tutorialJson.steps) ? tutorialJson.steps : [];
check('tutorial has at least one step', steps.length > 0);
check('tutorial step ids are unique and non-empty',
new Set(steps.map((s) => s.id)).size === steps.length && steps.every((s) => typeof s.id === 'string' && s.id.trim()));
check('every tutorial step kind is modal or callout',
steps.every((s) => s.kind === 'modal' || s.kind === 'callout'));
// A modal can advance without a button of its own — 'external' steps (a
// System View / Colony View the tutorial opened directly wires its own
// onClose/onColonyOpen straight to advance()) have none by design; the
// general "every buttonless step can still be advanced" check below still
// catches a modal that has neither.
check('every modal step has a non-empty body',
steps.filter((s) => s.kind === 'modal').every((s) => typeof s.body === 'string' && s.body.trim()));
check('every callout step has calloutText and a valid anchor',
steps.filter((s) => s.kind === 'callout').every((s) =>
typeof s.calloutText === 'string' && s.calloutText.trim() && TUTORIAL_TARGET_IDS.includes(s.anchor)));
check('every highlight id is a known tutorial target',
steps.every((s) => (s.highlights ?? []).every((h) => TUTORIAL_TARGET_IDS.includes(h))));
check('every button action is next/back/skip/finish',
steps.every((s) => (s.buttons ?? []).every((b) => ['next', 'back', 'skip', 'finish'].includes(b.action))));
check('every advanceOn (when set) is a known mode',
steps.every((s) => s.advanceOn === undefined || ADVANCE_MODES.includes(s.advanceOn)));
check('every buttonless step can still be advanced (advanceOn set)',
steps.every((s) => (s.buttons ?? []).length > 0 || ADVANCE_MODES.includes(s.advanceOn)),
steps.filter((s) => !(s.buttons ?? []).length && !ADVANCE_MODES.includes(s.advanceOn)).map((s) => s.id).join(','));
// Every non-null voice clip resolves on disk (same streamed-from-assets/speech
// contract as the species clips checked in section 2).
for (const s of steps) {
if (!s.voice) continue;
check(`tutorial step "${s.id}" voice clip exists`,
existsSync(join(root, 'assets/speech', `${s.voice}.mp3`)), `${s.voice}.mp3`);
}
check('a tutorial step uses the shipped intro clip vega/tutorial-intro-01',
steps.some((s) => s.voice === 'vega/tutorial-intro-01'));
// Every {token} in visible text is declared in the top-level vars allow-list.
const vars = tutorialJson.vars ?? [];
for (const s of steps) {
for (const field of ['title', 'body', 'calloutText']) {
for (const tok of placeholdersIn(s[field])) {
check(`tutorial step "${s.id}" ${field} placeholder {${tok}} is declared in vars`, vars.includes(tok));
}
}
}
// interpolate substitutes and leaves nothing behind.
const sample = interpolate('the {species} thrive', { species: 'Humans' });
check('interpolate substitutes a declared token', sample === 'the Humans thrive', sample);
const resolved = resolveSteps(tutorialJson, { species: 'Humans' });
check('resolveSteps leaves no {token} in any visible field',
resolved.every((s) => !['title', 'body', 'calloutText']
.some((f) => typeof s[f] === 'string' && /\{[a-zA-Z0-9_]+\}/.test(s[f]))));
// The lazy manifest exposes the file so scene.cache.json.get('mastervega-tutorial') works.
{
const stub = {
cache: { json: { get: (k) => (k === 'mastervega-tutorial' ? tutorialJson : null) } },
textures: { exists: () => false },
};
const eager = resolveGameAssets(stub, 'mastervega');
check('mastervega-tutorial.json is in the lazy asset manifest',
eager.some((d) => d.type === 'json' && d.key === 'mastervega-tutorial'));
}
check('UI_SPEECH declares the tutorial intro clip', UI_SPEECH.tutorialIntro === 'vega/tutorial-intro-01');
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
console.log(`\n${passes} passed, ${failures} failed`); console.log(`\n${passes} passed, ${failures} failed`);
if (failures > 0) process.exit(1); if (failures > 0) process.exit(1);