Integrate BGS real-time hosting and table-local careers

This commit is contained in:
coyotte508 2026-09-30 03:02:26 +02:00
parent 3f09a00d28
commit 5d986921b6
18 changed files with 2171 additions and 1162 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules/
.local/
.env
dist/

View file

@ -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.

371
bgs/engine.js Normal file
View file

@ -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);
}

249
bgs/gameinfo.json Normal file
View file

@ -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"
}
]
}
}

103
bgs/viewer.js Normal file
View file

@ -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("<body>")[1]
.split('<script type="module"')[0]
.split("</body>")[0];
target.prepend(style);
let seat, pending, lastState;
const ui = mountConsole(target, {
missions: missionSummaries,
command(command) {
if (pending)
return Promise.reject(Error("Waiting for the previous move"));
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending = null;
context.fetchState();
reject(
Error(
"No confirmation yet. Please check your connection and try again.",
),
);
}, 8000);
pending = { resolve, reject, timer, sequence: command.sequence };
if (!context.move(command)) {
clearTimeout(timer);
pending = null;
reject(Error("The game is not ready to accept moves"));
}
});
},
});
ui.setPlayer(undefined);
function render(state) {
lastState = state;
// Finished games can be opened without reinstalling an archived engine.
const view = Array.isArray(state.timeline) ? snapshot(state, seat) : state;
if (Array.isArray(state.timeline)) {
view.bgs = {
missionNumber: state.bgs.missionNumber,
settings: state.bgs.settings,
};
view.careerIds = state.bgs.playerIds;
view.explorers = Object.values(state.bgs.explorers).map((e) => ({
...e,
activeRun: !!e.activeRun,
eligible: [],
editable: false,
}));
}
ui.render(view);
if (pending && view.nextSequence > pending.sequence) {
clearTimeout(pending.timer);
const done = pending;
pending = null;
done.resolve(view);
}
}
return {
onState: render,
onMoveResult(result) {
if (result.ok || !pending || result.move?.sequence !== pending.sequence)
return;
const done = pending;
pending = null;
clearTimeout(done.timer);
context.fetchState();
done.reject(Error(result.error || "Move rejected"));
},
onPlayer(player) {
seat = player.index;
ui.setPlayer(seat);
if (lastState) render(lastState);
},
onPreferences: (preferences) => ui.setPreferences(preferences),
onError(error) {
const el = target.querySelector("#error");
if (el) el.textContent = String(error);
},
destroy() {
ui.destroy();
if (pending) {
clearTimeout(pending.timer);
pending.reject(Error("Viewer closed"));
pending = null;
}
},
};
});

View file

@ -58,4 +58,4 @@ The engine checks minimum levels before the run, successful completion, applicab
## Remaining validation and integration
The exact action decks and all standard threat faces are now available; no missing component is filled with a guessed deck distribution. Remaining work before an online release includes broader human playtesting of expansion combinations, BGS identity and career storage, real-time scheduling/transport and mobile multi-client testing on physical devices. Random mission generation and licensed official art/audio are separate optional work; fixed missions and generated browser speech already run locally.
The exact action decks and all standard threat faces are now available; no missing component is filled with a guessed deck distribution. Remaining work before an online release includes broader human playtesting of expansion combinations, mobile multi-client testing on physical devices and a decision about account-wide careers beyond the implemented table-local records. Random mission generation and licensed official art/audio are separate optional work; fixed missions and generated browser speech already run locally.

View file

@ -11,9 +11,9 @@ Use four separate components:
1. **Mission source:** produces a deterministic, versioned sequence of announcements. It can import fixed schedules first and later generate missions from a server-secret seed. Threat cards and trajectories are separate seeded decks.
2. **Game engine:** owns setup, cards, phase locks, transfers, androids, ship systems, threats, damage, resolution, scoring and expansion effects. It consumes ordered player commands and trusted time events. No `Date.now()`, client timer or audio playback position inside rule transitions.
3. **Viewer:** programs cards, displays public and private information, plays localized announcements and animates resolution. It may predict a clock display, but cannot extend a deadline or reveal a future threat.
4. **Host adapter:** binds the game to BGS authentication, durable ordering, deadlines, persistence, reconnect, cancellation and cooperative outcomes. The local host demonstrates this boundary without editing BGS.
4. **Host adapter:** binds the game to BGS authentication, durable ordering, deadlines, persistence, reconnect, cancellation and cooperative outcomes. The BGS adapter uses protocol 0.7 and durable platform wakeups.
The local implementation now contains all four layers, with the host adapter restricted to a localhost development server. Announcements deal cards, reveal threats and open transfers; programming resolves to a scored result. The BGS binding is deliberately deferred.
All four layers are implemented, with both a standalone local host and an authenticated BGS adapter. Announcements deal cards, reveal threats and open transfers; programming resolves to a scored result.
## Base game
@ -71,6 +71,6 @@ For the current audit of the complete standard inventory, see [components](compo
2. **Local play:** private physical cards, Android/solo rules, ship resolution, all threat cards, all specialization abilities, scoring, campaigns and local explorer persistence implemented.
3. **Teaching/viewer:** seven untimed guided exercises use the actual engine. FR/EN controls and effect descriptions, threat details, replay, native scrolling and journal available. Official names remain English; original visual symbols are placeholders for any later licensed artwork.
4. **Rules validation:** deterministic fixtures cover critical interactions, and every threat terminates and replays from serialized state. This is not exhaustive proof of all combinations; human playtests remain necessary before claiming release readiness.
5. **BGS release:** deferred as requested. Add authenticated identity, trusted wakeups, durable session/career commits, cooperative results, live transport and external/integrated voice decisions to the platform only when authorized.
5. **BGS release:** the private-playtest adapter is implemented; see [integration and deployment](realtime-host.md). Public release awaits human playtesting. Careers currently persist within a table, and voice remains external.
The fixed mission catalogue is playable. Porting the random mission generator and supplying official recordings/art are separate tasks, not silently emulated by invented components. Achievement criteria requiring group judgment remain explicit manual claims; the optional group-defined Hometown Hero entry is not automated.

View file

@ -1,81 +1,31 @@
# Proposed real-time boundary for BGS
# BGS integration
**Proposal only.** Nothing in the BGS platform or `@boardgamers/protocol` has been edited. The names below belong to this repository's prototype, not to the currently published BGS API.
The adapter is in `bgs/engine.js`; the hosted viewer is `bgs/viewer.js`. It uses BGS protocol 0.7 and the platform's durable engine wakeups. The standalone development server remains useful for rule tests, but is not the online host.
## What exists today
## Clock and commands
The [BGS engine API](https://docs.boardgamers.space/guide/engine-api) already has simultaneous `currentPlayer` values, `stripSecret`, live updates, cancellation and replay hooks. These are useful building blocks.
BGS supplies a trusted `context.now` after acquiring the game lock. The adapter never trusts browser timestamps. It exposes `advanceTime` and `nextWakeup`; BGS saves each semantic deadline and wakes the game even when everyone closes their browser. It also commits due events before accepting a player move. Late moves return HTTP 422.
The [current timing contract](https://docs.boardgamers.space/guide/timing) is per-player thinking time. Engines receive no trusted clock context, and expiration is not an autonomous engine callback. Consequently, readiness expiration and Space Alert announcements cannot be implemented faithfully by making browser clients send a timer move. A game with all browsers closed must still progress or cancel.
There is a fixed two-minute presence check after the host starts the game. Each human presses **I’m ready**; launch is shared, three seconds after the final confirmation. Missing readiness cancels without an inactivity or Elo penalty. Reconnecting does not restart or pause the flight.
## Suggested responsibility split
Commands carry a sequence number per seat. Repeated committed commands are harmless; gaps and stale edits are rejected. The viewer receives `move:result` acknowledgements and refreshes after rejection. Snapshots omit seeds, future announcements, decks and other players' hands. Server time accompanies snapshots so the browser can animate the countdown between updates.
| Host responsibility | Game responsibility |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
| Authenticated seat, ordered commands and trusted receipt timestamp | Decide whether the command is legal at that time |
| Durable wakeup scheduler, rescheduling after restart | Return the next meaningful deadline and consume all due events |
| Store state and command receipt atomically; publish per-viewer snapshots | Deterministic transitions, idempotent event cursor and secret filtering |
| Clock synchronization and full-state refresh after reconnect | Common mission start, individual phase locks and future-event secrecy |
| Apply cancellation and cooperative/no-rating semantics | Decide missing-presence cancellation versus mission success/failure |
| Persist cross-game explorer records when this becomes available | Validate progression, achievements and exactly-once career results |
After programming, resolution has no deadline. Campaign repairs and the decision to launch the next mission are untimed too. Only the next presence check and flight restart the clock. Campaigns contain three or five missions within one BGS game; their repairs and shared results stay in that game state.
The game owns the readiness rule; the host supplies the time and wakeup. A separate platform-wide “confirm presence” subsystem is not required just for Space Alert, though a generic capability may later be useful to other real-time games.
## Same table, new game
## Concrete prototype contract
BGS **Play again** creates a new game record with fresh randomness, the same reserved seats and optional setup changes. Other players confirm their seats; the host starts when they are ready. Reservations send no invitation emails. Old games remain available through the table's paginated history. This generic flow also works for asynchronous games such as Fuji.
```js
createSession({ players, crewSize, mission }, trustedNow);
nextWakeup(state); // absolute deadline, or null
advanceClock(state, trustedNow); // deterministic catch-up
submit(state, authenticatedSeat, command, trustedReceivedAt);
// -> { state, accepted, error?, duplicate? }
snapshot(state, authenticatedSeat); // undefined seat means spectator
```
At initialization, BGS supplies the previous completed game state only when it belongs to the same table, game and engine version. The adapter copies explorer careers by account ID, independently of seat order. Completed runs award experience once; cancellation releases the active run without awarding progress. Turning careers off preserves the records for later games at this table.
The local preview calls these directly. Future BGS integration may extend `init`/`move` with a host context and add time/deadline hooks, or adapt an equivalent generic scheduled-event interface. Settle names and types in the protocol change; do not ship a game-specific pseudo-hook that the current host silently ignores.
Careers are **table-local**, not account-wide profiles. Moving to another table starts a separate career. There is no global campaign directory or cross-table character synchronization. The game version is retained between games; retired versions ask players to create a new table.
### Presence and launch
## Results and limitations
- Finish mission selection/role setup before creating the timed session.
- Start one fixed 120-second presence deadline when the game session is created. Each human must explicitly confirm. Merely being connected, or an old scheduled-table confirmation, is not enough.
- The confirmation interaction should also prepare audio where possible, with an explicit visual/muted alternative. Spectators and androids do not confirm presence.
- Once all humans confirm, replace the presence deadline with a common start three seconds later. Do not restart or extend the clock on refresh, repeated confirmation or another tab opening.
- At `now >= presenceDeadline`, cancel if anyone is still missing, including if nobody sends another move. The game returns the reason and missing seats; the platform applies a penalty-free cancellation, not a ranked loss.
- After launch, disconnecting does not pause the mission or delete that crew member's committed program. Reconnect at the existing mission time. Policy for deliberate quitting after launch still needs a product decision; do not reuse preflight cancellation to erase a losing mission.
Configure `timeControl: "engine"` and `rating: "none"`. Players receive the shared mission/campaign score, without competitive Elo settlement. BGS individual clock rings and turn emails are disabled. Game-managed clocks do not yet support BGS analysis mode. The viewer retains its own resolution replay.
### Ordering and deadlines
Use external voice for cooperation. Speech synthesis is optional; no official recordings or publisher artwork are bundled. Players must honor communications blackouts in their external voice channel. Physical-device audio/background behavior and expansion combinations still need human playtesting before public release.
Serialize clock events and player requests per game. Assign timestamps at an authoritative, ordered ingress; do not trust `Date.now()` sent by a browser. Drain commands already accepted before a cutoff before processing that cutoff. Requests at the cutoff are late for the old phase. Define this ordering once in the host, including across processes.
## Verification
Call `advanceClock` before validating each request and persist its returned state **even if the request is rejected**. It may have crossed a deadline or cancelled the game. Also call it from autonomous wakeups. Late/repeated wakeups process all due semantic events exactly once via the persisted cursor. No per-second engine writes are needed.
Persist state, revision, timer target and command acknowledgement atomically. On restart reload the state, catch up, then schedule `nextWakeup`. Publishing occurs after the durable commit. The prototype demonstrates serialization and catch-up in pure functions; its local HTTP server is intentionally in-memory, not a production durable scheduler.
The prototype uses per-seat sequence numbers. The full card engine should add card/slot preconditions for shared android edits and transfers; one global expected revision would unnecessarily reject unrelated simultaneous human edits.
### Secrecy, reconnect and audio
Keep random seeds, future announcements, unopened packets and threat decks server-side. Snapshots and log slices need the same secret-filtering discipline. Do not preload the future randomly generated mission into the viewer just to schedule audio. Fixed, publicly known mission tracks are not a promise that their content is unknowable; hidden random missions require server-only generation.
Return a server timestamp and authoritative phase/state on reconnect. Browser timers animate a display between sync points; background throttling must not stop the mission. Audio is driven by semantic event IDs and a synchronized clock. Do not replay every missed recording in a burst after reconnect. If a clip runs long, the mission deadline still wins; localization must not change mission duration.
Semantic announcements in this prototype are not synchronized to recording waveforms. A transfer's imported 15-second event duration comes from the upstream model; verify the actual transfer beep/closing instant before enabling real card transfers.
### Cooperative results and experience
`rankings: [1,1,1,1]` alone would describe a competitive tie, not successful cooperative play. Confirm the platform's handling of shared outcomes and exclude ordinary competitive Elo updates. Cancellation should skip both outcome and experience writes.
Experience belongs to an explorer profile linked to a user, separate from seat numbers and game settings. Career writes require an idempotency key based on the completed game/mission and explorer. A failed request or replay cannot grant XP twice. Implement the career rules in the game behind a persistence interface while leaving the eventual BGS storage/API work deferred.
## Acceptance tests for the future host
- No connected clients: presence expires and cancels once.
- Last confirmation just before versus exactly at the deadline.
- Reconnect, second browser tab, duplicate request and reordered delivery.
- Server restart during countdown, blackout, transfer and phase transition.
- Simultaneous commands from distinct seats; competing android-slot writes.
- A slow client cannot backdate commands or expose future threats.
- Clock correction does not move a committed phase backward.
- Spectators receive only revealed information; replay preserves intended secrecy.
- Mobile background/resume and audio permission failure do not extend the mission.
- Final cooperative result and career updates are applied exactly once.
`npm test` covers trusted timestamps, deadline catch-up without clients, readiness cancellation, duplicate commands, late rejections, spectator secrecy, reordered-seat career inheritance, cancellation, and the underlying game rules. BGS tests cover durable wakeups, terminal notifications, atomic table creation, concurrent continuations, access checks and seat confirmation. The hosted viewer has also been exercised with two authenticated browser sessions, including a mobile viewport.

View file

@ -11,10 +11,26 @@
"scripts": {
"test": "node --test test/*.test.js",
"dev": "node preview/server.js",
"check": "npm test"
"check": "npm test",
"build": "node scripts/build.mjs"
},
"repository": {
"type": "git",
"url": "git+https://github.com/boardgamers/space-alert.git"
}
},
"devDependencies": {
"@boardgamers/protocol": "^0.7.0",
"esbuild": "^0.28.2"
},
"exports": {
"./engine": "./bgs/engine.js"
},
"files": [
"bgs/engine.js",
"src",
"mission-data",
"dist/viewer.js",
"README.md",
"LICENSE"
]
}

File diff suppressed because it is too large Load diff

View file

@ -188,6 +188,6 @@
</details>
<footer id="footer"></footer>
</main>
<script type="module" src="/app.js"></script>
<script type="module" src="/local.js"></script>
</body>
</html>

2
preview/local.js Normal file
View file

@ -0,0 +1,2 @@
import { mountConsole } from "./app.js";
mountConsole(document.body);

View file

@ -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];

View file

@ -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" ? "↑" : "↓"}`;
}

28
scripts/build.mjs Normal file
View file

@ -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`,
);

View file

@ -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";

26
src/view.js Normal file
View file

@ -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),
});
}

130
test/bgs.test.js Normal file
View file

@ -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),
);
});