diff --git a/.gitignore b/.gitignore index 6a98af7..d2b0060 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ .local/ .env +dist/ diff --git a/README.md b/README.md index 8baaf74..0b982f9 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ A playable local adaptation of **Space Alert** and **The New Frontier**, with a deterministic engine and a French/English browser viewer. Repository: [boardgamers/space-alert](https://github.com/boardgamers/space-alert). -**Status: local playtest, under rules review.** The game runs through programming, ship resolution and scoring. Nothing is connected or published to BGS; platform and protocol work remains deferred. +**Status: local playtest, under rules review.** The game runs through programming, ship resolution and scoring. The BGS adapter is implemented and tested against an isolated platform instance. Public release still needs human playtesting. ## Play locally -Node 24+, no dependencies: +Node 24+. The standalone playtest and engine tests need no installed packages: ```sh npm test @@ -41,7 +41,29 @@ The local host atomically saves the session, development clock offset and career - [Components and source verification](docs/components.md) - [Architecture and implementation status](docs/design.md) -- [Deferred BGS real-time host contract](docs/realtime-host.md) +- [BGS integration and deployment](docs/realtime-host.md) - [Third-party provenance and licenses](THIRD_PARTY.md) No publisher artwork, scanned cards, rulebook files or official voice recordings are bundled. The viewer uses original HTML/CSS symbols and its own explanatory text. Threat/achievement names remain in English. Code is AGPL-3.0-only; third-party materials retain their notices. + +## Build for BGS + +The viewer requires `@boardgamers/protocol` **0.7.0**, whose npm publication is separate from this repository. After it is published: + +```sh +npm install +npm run build +npm pack +``` + +Before publication, with the BGS monorepo beside this checkout, install the local package instead: + +```sh +cd ../boardgamers-mono +pnpm --filter @boardgamers/protocol build +cd ../space-alert +npm install --no-save --package-lock=false ../boardgamers-mono/packages/protocol +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. diff --git a/bgs/engine.js b/bgs/engine.js new file mode 100644 index 0000000..91ef33d --- /dev/null +++ b/bgs/engine.js @@ -0,0 +1,371 @@ +import { createHash } from "node:crypto"; +import { + createSession, + advanceClock, + nextWakeup as wakeup, + submit, + snapshot, +} from "../src/session.js"; +import { getMission } from "../src/missions.js"; +import { departCampaign } from "../src/game/campaign.js"; +import { + createExplorer, + startExplorer, + settleExplorer, + cancelExplorer, + learnSpecialization, + consentToCloning, + claimAchievement, + eligibleAchievements, +} from "../src/game/career.js"; + +const reject = (message) => { + throw Object.assign(new Error(message), { name: "InvalidMoveError" }); +}; +function trusted(context) { + if (!Number.isSafeInteger(context?.now) || context.now < 0) + throw Error("Space Alert needs the BGS server clock protocol"); + return context.now; +} +const result = (state) => + state.game?.campaign?.outcome ?? + (!state.game?.campaign ? state.game?.resolution?.outcome : null); +function settle(state) { + const g = state.game, + runId = g.campaign?.id ?? g.seed; + for (const [seat, id] of (state.bgs?.playerIds ?? []).entries()) { + const e = state.bgs.explorers?.[id]; + if (!e?.activeRun) continue; + if (state.stage === "cancelled") { + state.bgs.explorers[id] = cancelExplorer(e, runId); + continue; + } + const outcome = result(state); + if (!outcome) continue; + const metadata = { + mission: state.mission.id, + humans: state.players.length, + crew: state.crewSize, + doubleActions: state.mission.doubleActions, + difficulty: g.difficulty, + seriousDifficulty: g.seriousDifficulty, + penalties: outcome.penalties, + threatCount: state.timeline + .filter((e) => e.type === "threat") + .reduce((n, e) => n + (e.severity === "serious" ? 2 : 1), 0), + }; + state.bgs.explorers[id] = settleExplorer(e, { + id: runId, + ...outcome, + count: g.campaign?.missions.length ?? 1, + limit: g.campaign?.limit ?? 3, + training: !/^(realmission|double)/.test(state.mission.id), + humans: state.players.length, + at: state.observedAt, + missions: g.campaign + ? g.campaign.missions.map((m) => m.metadata) + : [metadata], + usedSpecializations: g.campaign + ? [ + ...new Set( + g.campaign.missions.flatMap( + (m) => m.metadata.usedSpecializations?.[seat] ?? [], + ), + ), + ] + : g.resolution.log + .filter((e) => e.type === "specialization" && e.crew === seat) + .map((e) => `${e.name}:${e.tier}`), + }); + } + return state; +} +function pool(value = "1,2") { + const values = String(value).split(",").map(Number); + if (!values.length || values.some((n) => ![1, 2, 3].includes(n))) + throw Error("Invalid threat difficulty"); + return [...new Set(values)]; +} +export function init(players, expansions, options, seed, creator, context) { + const now = trusted(context), + mission = getMission(options.mission ?? "realmission1"); + const campaignLimit = Number(options.campaign ?? 0); + if (![0, 3, 5].includes(campaignLimit)) + throw Error("Choose a single mission or a three/five mission campaign"); + if (campaignLimit && !/^(realmission|double)/.test(mission.id)) + throw Error("Campaigns require full missions"); + const crewSize = + players === 1 + ? 5 + : options.crewSize === "3" && players === 3 + ? 3 + : Math.max(4, players); + const playerIds = + context.playerIds ?? Array.from({ length: players }, (_, i) => String(i)); + const previous = context.previous?.state?.bgs?.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}`), + ]), + ); + 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) + ) + throw Error("Career explorers need level 2 before a campaign"); + const state = createSession( + { + players, + crewSize, + mission, + gameOptions: { + seed, + campaignLimit, + threatExpansion: expansions.includes("new-frontier"), + difficulty: pool(options.difficulty), + seriousDifficulty: pool( + options.seriousDifficulty ?? options.difficulty, + ), + ...(options.careers + ? { specializations: Array(crewSize).fill(null) } + : {}), + }, + }, + now, + ); + state.bgs = { + playerIds, + explorers, + gameId: context.gameId, + missionNumber: 1, + settings: options, + }; + return state; +} +export function advanceTime(state, context) { + return settle(advanceClock(state, trusted(context))); +} +export function nextWakeup(state) { + return ended(state) ? null : wakeup(state); +} +export function move(input, command, seat, context) { + const now = trusted(context); + if (!Number.isInteger(seat) || !input.players[seat]) reject("Unknown player"); + if (!command || typeof command !== "object" || Array.isArray(command)) + reject("Invalid command"); + let state = advanceTime(input, context); + if (!Number.isSafeInteger(command.sequence) || command.sequence < 1) + reject("Invalid sequence"); + if (command.sequence <= state.players[seat].lastSequence) return state; + if (command.sequence !== state.players[seat].lastSequence + 1) + reject("Refresh before trying again"); + if (ended(state)) reject("This game has finished"); + try { + if (command.type === "campaign-next") { + if ( + Object.keys(command).some( + (k) => + ![ + "type", + "sequence", + "mission", + "botStation", + "difficulty", + "seriousDifficulty", + ].includes(k), + ) + ) + reject("Unsupported command field"); + if (seat !== 0 || !state.game.campaign) + reject("Only the captain starts the next campaign mission"); + const mission = getMission(command.mission ?? state.mission.id); + if (!/^(realmission|double)/.test(mission.id)) + reject("Campaigns require full missions"); + const campaign = departCampaign(state.game.campaign, command.botStation); + const seed = createHash("sha256") + .update(state.game.seed + "/next-mission") + .digest("hex"); + const next = createSession( + { + players: state.players.length, + crewSize: state.crewSize, + mission, + gameOptions: { + seed, + campaign, + threatExpansion: state.game.threatExpansion, + difficulty: command.difficulty + ? pool(command.difficulty) + : state.game.difficulty, + seriousDifficulty: command.seriousDifficulty + ? pool(command.seriousDifficulty) + : state.game.seriousDifficulty, + specializations: state.game.specializations, + }, + }, + now, + ); + next.bgs = { ...state.bgs, missionNumber: state.bgs.missionNumber + 1 }; + next.players.forEach((p, i) => { + p.lastSequence = state.players[i].lastSequence; + p.name = state.players[i].name; + }); + next.revision = state.revision + 1; + state = next; + } else if (command.type === "career") { + if ( + Object.keys(command).some( + (k) => + ![ + "type", + "sequence", + "action", + "specialization", + "achievement", + "runId", + "agrees", + "crew", + ].includes(k), + ) + ) + reject("Unsupported career field"); + if (state.stage !== "presence" || state.players.some((p) => p.ready)) + reject("Choose careers before anyone confirms readiness"); + const id = state.bgs.playerIds[seat], + e = state.bgs.explorers[id]; + if (!e || !state.bgs.settings.careers) + reject("Careers are disabled for this table"); + if (command.action === "new" && e.dead) + state.bgs.explorers[id] = createExplorer(id, e.name); + else if (command.action === "learn") + state.bgs.explorers[id] = learnSpecialization( + e, + command.specialization, + ); + else if (command.action === "consent") + state.bgs.explorers[id] = consentToCloning(e); + else if (command.action === "claim") + state.bgs.explorers[id] = claimAchievement( + e, + command.runId, + command.achievement, + { crewAgrees: command.agrees === true }, + ); + else if (command.action === "specialization") { + const crew = command.crew ?? seat; + if ( + !Number.isInteger(crew) || + crew < 0 || + crew >= state.crewSize || + (state.players.length > 1 && + crew !== seat && + crew < state.players.length) + ) + reject("Choose your own specialization"); + const level = e.specializations[command.specialization]; + if (!level) reject("Learn this specialization first"); + if ( + state.game.specializations.some( + (s, i) => i !== crew && s?.name === command.specialization, + ) + ) + reject("Specialization is already assigned"); + state.game.specializations[crew] = { + name: command.specialization, + level, + }; + } else reject("Unknown career action"); + state.revision++; + } else { + if ( + command.type === "ready" && + state.bgs.settings.careers && + state.bgs.explorers[state.bgs.playerIds[seat]] + ) { + const id = state.bgs.playerIds[seat], + e = state.bgs.explorers[id]; + if (!e.activeRun) + state.bgs.explorers[id] = startExplorer( + e, + state.game.campaign?.id ?? state.game.seed, + ); + } + const response = submit(state, seat, command, now); + if (!response.accepted) reject(response.error); + return settle(response.state); + } + state.players[seat].lastSequence = command.sequence; + return settle(state); + } catch (error) { + if (error.name === "InvalidMoveError") throw error; + reject(error.message); + } +} +export function ended(state) { + return state.stage === "cancelled" || !!result(state); +} +export function cancelled(state) { + return state.stage === "cancelled"; +} +export function scores(state) { + return state.players.map(() => result(state)?.score ?? 0); +} +export function currentPlayer(state) { + return ended(state) ? [] : state.players.map((p) => p.seat); +} +export function isLiveUpdate() { + return true; +} +export function round(state) { + return state.bgs.missionNumber; +} +export function logLength(state) { + return state.revision; +} +export function logSlice() { + return { log: [] }; +} +export function stripSecret(state, seat, context) { + const view = snapshot(state, seat); + view.serverNow = Math.max(state.observedAt, context?.now ?? state.observedAt); + view.bgs = { + missionNumber: state.bgs.missionNumber, + settings: state.bgs.settings, + }; + const id = state.bgs.playerIds[seat]; + view.careerIds = state.bgs.playerIds; + view.explorers = ( + state.bgs.settings.careers ? Object.values(state.bgs.explorers) : [] + ).map((e) => ({ + ...e, + activeRun: !!e.activeRun, + eligible: + e.id === id && e.runs.length + ? eligibleAchievements(e, e.runs.at(-1).id) + : [], + editable: e.id === id, + })); + return view; +} +export function setPlayerMetaData(state, seat, { name }) { + const next = structuredClone(state); + next.players[seat].name = name; + const e = next.bgs.explorers[next.bgs.playerIds[seat]]; + if (e) e.name = name; + return next; +} +export function dropPlayer(state) { + const next = structuredClone(state); + next.stage = "cancelled"; + next.cancellation = { reason: "player-left" }; + next.revision++; + return settle(next); +} diff --git a/bgs/gameinfo.json b/bgs/gameinfo.json new file mode 100644 index 0000000..0927a22 --- /dev/null +++ b/bgs/gameinfo.json @@ -0,0 +1,249 @@ +{ + "version": { + "_id": { + "game": "space-alert", + "version": 1 + }, + "public": false, + "timeControl": "engine", + "rating": "none", + "meta": {}, + "engine": { + "package": { + "name": "@boardgamers/space-alert", + "version": "0.1.0" + }, + "entryPoint": "bgs/engine.js" + }, + "viewer": { + "topLevelVariable": "SpaceAlert" + }, + "preferences": [ + { + "name": "sound", + "type": "checkbox", + "label": "Spoken announcements", + "default": false + } + ] + }, + "metadata": { + "_id": "space-alert", + "slug": "space-alert", + "label": "Space Alert", + "emoji": "\ud83d\ude80", + "players": [1, 2, 3, 4, 5], + "releaseYear": 2008, + "tags": ["cooperative"], + "options": [ + { + "name": "mission", + "type": "select", + "label": "Mission", + "default": "realmission1", + "items": [ + { + "name": "firstTestRun", + "label": "Test run 1" + }, + { + "name": "secondTestRun", + "label": "Test run 2" + }, + { + "name": "simulation1", + "label": "Simulation 1" + }, + { + "name": "simulation2", + "label": "Simulation 2" + }, + { + "name": "simulation3", + "label": "Simulation 3" + }, + { + "name": "advancedsimulation1", + "label": "Advanced simulation 1" + }, + { + "name": "advancedsimulation2", + "label": "Advanced simulation 2" + }, + { + "name": "advancedsimulation3", + "label": "Advanced simulation 3" + }, + { + "name": "realmission1", + "label": "Mission 1" + }, + { + "name": "realmission2", + "label": "Mission 2" + }, + { + "name": "realmission3", + "label": "Mission 3" + }, + { + "name": "realmission4", + "label": "Mission 4" + }, + { + "name": "realmission5", + "label": "Mission 5" + }, + { + "name": "realmission6", + "label": "Mission 6" + }, + { + "name": "realmission7", + "label": "Mission 7" + }, + { + "name": "realmission8", + "label": "Mission 8" + }, + { + "name": "doubleActionEasierMission1", + "label": "Double-action easy mission 1" + }, + { + "name": "doubleActionEasierMission2", + "label": "Double-action easy mission 2" + }, + { + "name": "doubleActionEasierMission3", + "label": "Double-action easy mission 3" + }, + { + "name": "doubleActionEasierMission4", + "label": "Double-action easy mission 4" + }, + { + "name": "doubleActionEasierMission5", + "label": "Double-action easy mission 5" + }, + { + "name": "doubleActionEasierMission6", + "label": "Double-action easy mission 6" + }, + { + "name": "doubleActionMission1", + "label": "Double-action mission 1" + }, + { + "name": "doubleActionMission2", + "label": "Double-action mission 2" + }, + { + "name": "doubleActionMission3", + "label": "Double-action mission 3" + }, + { + "name": "doubleActionMission4", + "label": "Double-action mission 4" + }, + { + "name": "doubleActionMission5", + "label": "Double-action mission 5" + }, + { + "name": "doubleActionMission6", + "label": "Double-action mission 6" + }, + { + "name": "doubleActionMission7", + "label": "Double-action mission 7" + }, + { + "name": "doubleActionMission8", + "label": "Double-action mission 8" + }, + { + "name": "doubleActionMission9", + "label": "Double-action mission 9" + }, + { + "name": "doubleActionMission10", + "label": "Double-action mission 10" + }, + { + "name": "doubleActionMission11", + "label": "Double-action mission 11" + }, + { + "name": "doubleActionMission12", + "label": "Double-action mission 12" + } + ] + }, + { + "name": "campaign", + "type": "select", + "label": "Campaign", + "default": "0", + "items": [ + { + "name": "0", + "label": "Single mission" + }, + { + "name": "3", + "label": "Three missions" + }, + { + "name": "5", + "label": "Five missions" + } + ] + }, + { + "name": "difficulty", + "type": "select", + "label": "Threats", + "default": "1,2", + "items": [ + { + "name": "1", + "label": "White" + }, + { + "name": "1,2", + "label": "White / yellow" + }, + { + "name": "2", + "label": "Yellow" + }, + { + "name": "2,3", + "label": "Yellow / red" + }, + { + "name": "3", + "label": "Red" + }, + { + "name": "1,2,3", + "label": "All" + } + ] + }, + { + "name": "careers", + "type": "checkbox", + "label": "Explorer careers at this table", + "default": false + } + ], + "expansions": [ + { + "name": "new-frontier", + "label": "The New Frontier" + } + ] + } +} diff --git a/bgs/viewer.js b/bgs/viewer.js new file mode 100644 index 0000000..f88809b --- /dev/null +++ b/bgs/viewer.js @@ -0,0 +1,103 @@ +import { registerViewer } from "@boardgamers/protocol/viewer"; +import { mountConsole } from "../preview/app.js"; +import html from "../preview/index.html"; +import css from "../preview/style.css"; +import { snapshot } from "../src/view.js"; +const missionSummaries = BGS_MISSIONS; + +registerViewer("SpaceAlert", (context) => { + const { target } = context; + const style = document.createElement("style"); + style.textContent = + css + + ` + .bgs-hosted #setup,.bgs-hosted #lessons,.bgs-hosted #create-explorer,.bgs-hosted #seat,.bgs-hosted #ready-all,.bgs-hosted #next-event,.bgs-hosted #footer,.bgs-hosted #open-setup {display:none!important} + .bgs-hosted #career-manager:has(#explorers:empty) {display:none} + `; + target.innerHTML = html + .split("")[1] + .split(' + diff --git a/preview/local.js b/preview/local.js new file mode 100644 index 0000000..108471a --- /dev/null +++ b/preview/local.js @@ -0,0 +1,2 @@ +import { mountConsole } from "./app.js"; +mountConsole(document.body); diff --git a/preview/server.js b/preview/server.js index ffaa47b..c8b99e8 100644 --- a/preview/server.js +++ b/preview/server.js @@ -400,6 +400,7 @@ export function createPreviewServer({ clock = Date.now, storagePath } = {}) { const file = { "/": "index.html", "/app.js": "app.js", + "/local.js": "local.js", "/text.js": "text.js", "/style.css": "style.css", }[url.pathname]; diff --git a/preview/text.js b/preview/text.js index 67a06d3..2feec1d 100644 --- a/preview/text.js +++ b/preview/text.js @@ -443,7 +443,9 @@ function word(x, locale) { return choose(dictionary[x], locale) ?? String(x ?? ""); } function station(x, locale) { - if (!x) return ""; + if (x && typeof x === "object" && x.zone && x.deck) x = `${x.zone}-${x.deck}`; + if (typeof x !== "string" || !/^(red|white|blue)-(upper|lower)$/.test(x)) + return ""; const [z, d] = x.split("-"); return `${word(z, locale)} ${d === "upper" ? "↑" : "↓"}`; } diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..9c37d95 --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,28 @@ +import { build } from "esbuild"; +import { mkdir, writeFile } from "node:fs/promises"; +import { gzipSync } from "node:zlib"; +import { readFileSync } from "node:fs"; +import { missionSummaries } from "../src/missions.js"; +await mkdir("dist", { recursive: true }); +const result = await build({ + entryPoints: ["bgs/viewer.js"], + bundle: true, + minify: process.env.BGS_DEBUG !== "1", + format: "iife", + target: ["chrome109", "firefox115", "safari15.4"], + outfile: "dist/viewer.js", + loader: { ".html": "text", ".css": "text" }, + define: { + BGS_MISSIONS: JSON.stringify( + missionSummaries.map(({ id, title }) => ({ id, title })), + ), + }, + metafile: true, +}); +await writeFile( + "dist/viewer-meta.json", + JSON.stringify(result.metafile, null, 2), +); +console.log( + `Viewer: ${readFileSync("dist/viewer.js").length} bytes; ${gzipSync(readFileSync("dist/viewer.js")).length} bytes gzip`, +); diff --git a/src/session.js b/src/session.js index ff1d60f..30e353a 100644 --- a/src/session.js +++ b/src/session.js @@ -5,7 +5,6 @@ import { finishGamePlanning, GAME_COMMAND_FIELDS, gameCommand, - gameView, } from "./game/planning.js"; import { compileTimeline } from "./missions.js"; @@ -229,27 +228,4 @@ export function canEditTurn(state, seat, turn) { return Boolean(range && turn >= range[0] && turn <= range[1]); } -export function snapshot(state, seat) { - // An allowlist keeps the unannounced schedule out of every player/spectator view. - return structuredClone({ - game: gameView(state, seat), - version: state.version, - revision: state.revision, - stage: state.stage, - serverNow: state.observedAt, - presenceDeadline: state.presenceDeadline, - missionStartAt: state.missionStartAt, - mission: state.mission, - crewSize: state.crewSize, - players: state.players.map(({ lastSequence, ...player }) => player), - nextSequence: Number.isInteger(seat) - ? (state.players[seat]?.lastSequence ?? 0) + 1 - : null, - phase: state.phase, - communicationsAvailable: state.communicationsAvailable, - transferClosesAt: state.transferClosesAt, - log: state.log, - cancellation: state.cancellation, - clockRunning: active.has(state.stage), - }); -} +export { snapshot } from "./view.js"; diff --git a/src/view.js b/src/view.js new file mode 100644 index 0000000..8697f24 --- /dev/null +++ b/src/view.js @@ -0,0 +1,26 @@ +import { gameView } from "./game/planning.js"; +const active = new Set(["presence", "countdown", "programming"]); +export function snapshot(state, seat) { + // An allowlist keeps the unannounced schedule out of every player/spectator view. + return structuredClone({ + game: gameView(state, seat), + version: state.version, + revision: state.revision, + stage: state.stage, + serverNow: state.observedAt, + presenceDeadline: state.presenceDeadline, + missionStartAt: state.missionStartAt, + mission: state.mission, + crewSize: state.crewSize, + players: state.players.map(({ lastSequence, ...player }) => player), + nextSequence: Number.isInteger(seat) + ? (state.players[seat]?.lastSequence ?? 0) + 1 + : null, + phase: state.phase, + communicationsAvailable: state.communicationsAvailable, + transferClosesAt: state.transferClosesAt, + log: state.log, + cancellation: state.cancellation, + clockRunning: active.has(state.stage), + }); +} diff --git a/test/bgs.test.js b/test/bgs.test.js new file mode 100644 index 0000000..1056904 --- /dev/null +++ b/test/bgs.test.js @@ -0,0 +1,130 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as e from "../bgs/engine.js"; +import { eventDescription } from "../preview/text.js"; +const ctx = (now, extra = {}) => ({ + now, + gameId: "bgs-test", + playerIds: ["alice", "bob"], + ...extra, +}); +const initial = (options = {}) => + e.init(2, [], options, "private-seed", 0, ctx(1000)); +const launch = (s = initial()) => + e.move( + e.move(s, { type: "ready", sequence: 1 }, 0, ctx(1001)), + { type: "ready", sequence: 1 }, + 1, + ctx(1002), + ); +test("requires a trusted server timestamp and ignores client clock claims", () => { + assert.throws(() => e.init(2, [], {}, "seed", 0), /server clock/); + assert.throws( + () => + e.move(initial(), { type: "ready", sequence: 1, now: 500 }, 0, ctx(1001)), + { name: "InvalidMoveError" }, + ); + assert.throws( + () => e.move(initial(), { type: "ready", sequence: 1 }, 7, ctx(1001)), + { name: "InvalidMoveError" }, + ); +}); +test("catches up while disconnected, leaves resolution untimed, and repeats safely", () => { + const launched = launch(); + const closed = e.advanceTime(launched, ctx(900000)); + assert.equal(closed.stage, "resolution"); + assert.equal(e.nextWakeup(closed), null); + assert.equal(e.ended(closed), false); + assert.deepEqual(e.advanceTime(closed, ctx(900000)), closed); + assert.throws( + () => + e.move( + closed, + { type: "place", sequence: 2, crew: 0, turn: 1, cards: [] }, + 0, + ctx(900000), + ), + { name: "InvalidMoveError" }, + ); + const resolved = e.move( + closed, + { type: "resolve", sequence: 2, all: true }, + 0, + ctx(900001), + ); + for (const event of resolved.game.resolution.log) + for (const lang of ["fr", "en"]) + assert.doesNotThrow(() => + eventDescription(event, lang, resolved.game.resolution.threats), + ); + assert.equal(e.ended(resolved), true); + assert.equal(e.scores(resolved)[0], e.scores(resolved)[1]); +}); +test("missing readiness cancels without inventing player timeouts", () => { + const s = e.advanceTime(initial(), ctx(121000)); + assert.equal(e.ended(s), true); + assert.equal(e.cancelled(s), true); + assert.equal(e.nextWakeup(s), null); + assert.deepEqual(e.currentPlayer(s), []); +}); +test("snapshots hide deck, future announcements and other hands from players and spectators", () => { + const s = e.advanceTime(launch(), ctx(4010)); + for (const seat of [undefined, 0, 1]) { + const view = e.stripSecret(s, seat, ctx(4100)); + assert.equal(view.serverNow, 4100); + assert.equal(view.timeline, undefined); + assert.equal(view.bgs.playerIds, undefined); + assert.equal(view.game.seed, undefined); + assert.ok(!JSON.stringify(view).includes("private-seed")); + if (seat === undefined) assert.equal(view.nextSequence, null); + } +}); +test("careers carry by account across reordered seats, and only their owner can change them", () => { + const old = initial({ careers: true }); + old.bgs.explorers.alice.level = 1; + old.bgs.explorers.alice.xp = 8; + const next = e.init( + 2, + [], + { careers: true }, + "new-seed", + 1, + ctx(2000, { + playerIds: ["bob", "alice"], + previous: { state: old, gameId: "old", playerIds: ["alice", "bob"] }, + }), + ); + const learned = e.move( + next, + { type: "career", action: "learn", specialization: "medic", sequence: 1 }, + 1, + ctx(2001), + ); + assert.equal(learned.bgs.explorers.alice.specializations.medic, 1); + assert.deepEqual(learned.bgs.explorers.bob.specializations, {}); + assert.throws( + () => + e.move( + next, + { + type: "career", + action: "learn", + specialization: "medic", + id: "alice", + sequence: 1, + }, + 0, + ctx(2001), + ), + { name: "InvalidMoveError" }, + ); + assert.equal(old.bgs.explorers.alice.specializations.medic, undefined); +}); +test("a dropped player ends the cooperative session and unlocks explorer records", () => { + const s = launch(initial({ careers: true })); + const cancelled = e.dropPlayer(s); + assert.equal(e.cancelled(cancelled), true); + assert.ok( + Object.values(cancelled.bgs.explorers).every((p) => p.activeRun === null), + ); +});