Implement playable Space Alert and New Frontier local engine

This commit is contained in:
coyotte508 2026-09-30 01:37:37 +02:00
commit 3f09a00d28
28 changed files with 9112 additions and 494 deletions

View file

@ -1,10 +1,10 @@
# Space Alert — Boardgamers # Space Alert — Boardgamers
Preparation for a BGS adaptation of **Space Alert**, including **The New Frontier**. Canonical repository: [boardgamers/space-alert on GitHub](https://github.com/boardgamers/space-alert). 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).
**Current status: an integration study and executable mission-timing prototype. This is not yet a playable adaptation.** No BGS platform or protocol package changes have been made, and nothing is published to the BGS game catalogue. **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.
## Run the prototype ## Play locally
Node 24+, no dependencies: Node 24+, no dependencies:
@ -13,33 +13,35 @@ npm test
npm run dev npm run dev
``` ```
Open http://127.0.0.1:5250. The local mission console can check readiness across tabs, start a shared mission clock, announce events, move a player to a later planning phase, and finish programming. It stops at resolution; it does not yet deal action cards, draw threats or simulate the ship. Seat selection and the “Ready all” control are development tools, not authentication. Open <http://127.0.0.1:5250>. Start with **Flight school / École de vol**: seven untimed exercises use the real engine, with editable programs and a teammate already maintaining the computer. The examples cover firing, energy, malfunctions, battlebots/interceptors, double actions, phasing and specializations.
For a full mission, expand **Local session / Session locale**. Select 1–5 humans, the crew, mission, threat pools and optional modules. In solo, you control four androids and have access to the full action deck. In multiplayer testing, open another tab with `?seat=1`, etc. Confirm presence within two minutes; the shared mission starts three seconds after everyone is ready. Select a card half, then a turn. Advance individual phases to lock previous turns, or let the shared clock do so. After programming, the captain can resolve one step at a time or finish the mission; everyone can inspect the replay and log.
The local seat selector, “Ready all” and “Next announcement” buttons are development tools. This host has **no authentication** and deliberately listens only on `127.0.0.1`. It is not an online multiplayer deployment. Use external voice for cooperation; browser speech synthesis is optional and communications-blackout silence relies on the players.
## Implemented ## Implemented
- A fixed two-minute presence check. Missing confirmations cancel the session; they are not a team defeat. Everyone ready starts a shared three-second launch countdown. - Trusted host clock, autonomous deadlines, presence cancellation, reconnection, atomic game commands and idempotent command sequences.
- Server-driven mission events and phase deadlines, independent of browser timers and further player input. - 34 imported fixed mission schedules, including 18 double-action missions. The randomized mission generator has not been ported.
- Individually advancing planning phases, including the irreversible lock on earlier turns. - Private hands and permitted card backs; phase packets, incoming data, transfers, android donations, solo programming and shared-slot conflict checks.
- Idempotent commands, exact deadline handling, reconnect/catch-up from serialized state, and views without the unannounced event list. - Exact 90-card base and 90-card double-action decks, 6 heroic cards and all 10 specializations at levels 1–3.
- 34 fixed mission schedules imported from a pinned version of [SpaceAlertMissionGenerator](https://github.com/nibuen/SpaceAlertMissionGenerator): 2 test runs, 3 simulations, 3 advanced simulations, 8 missions, 6 easier double-action missions and 12 double-action missions. - Six-station ship, energy, lifts, weapons, battlebots, interceptors, internal repairs, damage, delayed programs and deterministic resolution/replay.
- Local development host and tests. These test timing and integration assumptions; they are not a rules-completeness claim. - 103 threats: 55 base cards and 48 expansion cards, with seven trajectories. Includes called reinforcements, phasing, carriers, polarization, inaccessibility and the special intruder effects.
- Campaigns of three or five missions: collective continuation, ordered repairs, carried damage, robot placement and final campaign score.
- Local explorer careers: experience, specialization points, cloning/hardcore death and achievement recording. Verifiable mission constraints are checked; achievements requiring human judgment use an explicit attestation and a link to the official criteria. The group-defined **Hometown Hero** house achievement is not automated.
- Responsive FR/EN UI, readable threat effects, grouped cards and hand filters; native page scrolling and a scrollable journal with normal boundary chaining.
## Design and remaining work ## Persistence and tests
- [Implementation scope and rules findings](docs/design.md): base game, all four New Frontier modules, mobile interface, content and release criteria. The local host atomically saves the session, development clock offset and careers to `.local/session.json` (gitignored). Restarting resumes the same mission; experience completion is applied once by run ID. A saved prototype state from the older schema is backed up as `.legacy-backup` before a fresh session is created.
- [Future BGS host contract](docs/realtime-host.md): the assumptions needed for real-time play, and how the prototype maps to them. These are proposed integration points, not existing protocol exports.
- [Sources and third-party notices](THIRD_PARTY.md): upstream revisions, licenses and content provenance.
The next game implementation layers are private card programming and the deterministic resolution engine, followed by the complete threat catalogue, all specialization effects and campaign/experience persistence. The upstream project generates announcements; it does not provide those rules. `npm test` covers timing and secrecy, physical card ownership, action/resolution rules, every threat's termination and serializable replay, expansion interactions, campaign repairs, career progression, host restart, and the tutorial examples. Passing tests do not replace a complete human rules audit, especially for combinations of expansion effects.
## Mission data ## References and integration
`mission-data/catalog.json` contains structured schedules, not audio files. The import script accepts only the audited source file and verifies its SHA-256 before parsing a small, explicit subset of Java syntax; it never executes Java source: - [Components and source verification](docs/components.md)
- [Architecture and implementation status](docs/design.md)
- [Deferred BGS real-time host contract](docs/realtime-host.md)
- [Third-party provenance and licenses](THIRD_PARTY.md)
```sh 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.
python3 scripts/import-missions.py /path/to/ConstructedMissions.java
```
`src/missions.js` normalizes those schedules into semantic deadlines and announcements. Warning timestamps are semantic countdown points, not sample-accurate cue points for official recordings. Audio synchronization must be validated separately before release. The random generator has not been ported.
Code is AGPL-3.0-only, with third-party material retaining its notices. Space Alert is designed by Vlaada Chvátil and published by Czech Games Edition. No publisher artwork or voice recordings are included in this repository.

View file

@ -30,3 +30,13 @@ No publisher artwork, scans, rulebook PDFs or voice recordings are bundled. Code
## BGS references ## BGS references
The integration study used the current public [engine contract](https://docs.boardgamers.space/guide/engine-api), [viewer contract](https://docs.boardgamers.space/guide/viewer-api) and [timing documentation](https://docs.boardgamers.space/guide/timing), checked 2026-09-29. Neither the BGS platform nor the protocol package was modified. The integration study used the current public [engine contract](https://docs.boardgamers.space/guide/engine-api), [viewer contract](https://docs.boardgamers.space/guide/viewer-api) and [timing documentation](https://docs.boardgamers.space/guide/timing), checked 2026-09-29. Neither the BGS platform nor the protocol package was modified.
## Component data verification (2026-09-30)
- Base action counts: public [SpaceAlertWeb inventory](https://github.com/Theophile-Varnier/SpaceAlertWeb), cross-checked with community component counts and the official rules. Factual counts were used; no source implementation was ported.
- Double-action counts: [mandark, List of double-action cards](https://boardgamegeek.com/filepage/89436/list-of-double-action-cards), 2013-04-01. Exact workbook hash and standard-library import procedure are in [components.md](docs/components.md). The copyrighted XLSX is not bundled; `double-deck.json` contains symbol pairs and counts.
- Threat component inspection: [Russian external threat faces](https://boardgamegeek.com/filepage/108685/russian-external-threats-cards), `external_rus_1.03_web.pdf`, and [Russian internal threat faces](https://boardgamegeek.com/filepage/108686/russian-internal-threats-cards), `internal_rus_1.05_web.pdf`, community translation/layout credited to Jay, uploaded by Igiigi. No scans or translated prose are redistributed. The rules DSL and viewer descriptions were written independently from factual card effects and official rules.
- Independent factual catalogue/trajectory cross-check: [ecm85/space-alert-resolver](https://github.com/ecm85/space-alert-resolver). No license was found; no source code or artwork from this repository is included.
- Career values and criteria: CGE's [official achievements sheet](https://filemanager.czechgames.com/storage/files/space-alert-the-new-frontier/other-downloads/achievements/space-alert-2-achievements-en.pdf) and [explorer log](https://filemanager.czechgames.com/storage/files/space-alert-the-new-frontier/other-downloads/explorers-log-sheets/space-alert-2-explorers-log-en.pdf). The viewer links to the official English/French criteria; it does not redistribute those PDFs.
These references identify the evidence used, not a claim of publisher endorsement. Local research PDFs/XLSX files and login information are outside the repository.

61
docs/components.md Normal file
View file

@ -0,0 +1,61 @@
# Component audit
Checked 2026-09-30. Rules are implemented in original code; component faces were transcribed as factual values and effects, not copied artwork or prose. This is a completeness inventory, not certification of every rule interaction.
| Component | Implemented inventory | Evidence |
| --------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| Base actions | 90 physical cards: for each of red, blue and lift, 10 × A, 8 × B, 7 × C, 5 × battlebots | Base rulebook total; independently matching SpaceAlertWeb component inventory and BGG community inventory |
| Double actions | 90 physical cards, 78 distinct ordered face pairs | BGG _List of double-action cards_ workbook, counts imported reproducibly |
| Heroic actions | 6 cards, each with the fixed action/movement pairing | Component references and base rules |
| Threats | 55 base + 48 expansion; expansion replacement Fighter/Stealth Fighter are corrected base entries, not additional draws | Component faces, expansion appendix and reference inventory |
| Trajectories | 7 boards, 10–16 spaces; distances 1–5, 6–10, 11–16 | Component reference and rules |
| Ship damage | 6 different tiles per zone | Base rules |
| Specializations | 10 types, basic/advanced cards, levels 1–3 | Official expansion rules |
| Careers | 30 level transitions, dotted hardcore boxes, official fixed achievements | Official explorer log and achievement sheets |
## Exact action decks
The base multiset was cross-checked with the `ActionCards` inventory in [Theophile-Varnier/SpaceAlertWeb](https://github.com/Theophile-Varnier/SpaceAlertWeb). The six heroic movement destinations are not interchangeable with their printed heroic actions. The code calls those card faces `teleport:*` for serialization compatibility, but executes **heroic movement**: sealed doors and destination effects still apply. Teleporter specialization actions use actual teleportation rules.
The double deck comes from [mandark’s BGG workbook](https://boardgamegeek.com/filepage/89436/list-of-double-action-cards), uploaded 2013-04-01, `SATNF_-_Double_Actions.xlsx`:
```
SHA-256 3fb17351f46fd278962d4d02c3ade38e0a39c72c83f8951118dc8ee441d2e86c
```
The importer reads the worksheet's ordered symbol columns and physical counts, combining only identical face pairs. The workbook has 79 data rows; the repeated left / B / A row combines to produce 78 distinct pairs. Both face ordering and counts are retained in `src/game/double-deck.json`.
```sh
python3 scripts/import-action-deck.py /path/to/SATNF_-_Double_Actions.xlsx
```
The script verifies the source hash and uses only Python's standard library. The workbook is not redistributed.
## Threat verification
The expansion component audit used [external threat faces](https://boardgamegeek.com/filepage/108685/russian-external-threats-cards) and [internal threat faces](https://boardgamegeek.com/filepage/108686/russian-internal-threats-cards), read alongside the official English expansion appendix. The public [ecm85/space-alert-resolver](https://github.com/ecm85/space-alert-resolver) inventory provided an independent factual cross-check of identifiers, statistics and trajectories. That repository has no license notice: no implementation code or art was copied from it.
Corrections and interpretation points retained in code/tests:
- The corrected base Stealth Fighter has speed 3.
- Polarized Fighter is `E3-108`; one translated face duplicates the Phasing Pulser's `E3-102` ID.
- A trajectory's sixteenth space is still range 3.
- Pulse targets all external zones in range; a spanning threat is only hit once by a single pulse/rocket/interceptor attack.
- A carrier's reduction depends on interceptors being in the applicable range, not on the carrier being their selected target.
- Called threat cards are public recursively; a Vortex's surprise internal draw stays private until revealed by resolution.
- Ninja/Rabid Beast aftermath can persist after destruction; a discarded Vortex draw must not become a permanent malfunction.
- Campaign missions prepare new threat decks. A previous mission's used cards are not excluded from the next mission's deck.
## Experience and achievements
Primary sources: CGE's [English explorer sheet](https://filemanager.czechgames.com/storage/files/space-alert-the-new-frontier/other-downloads/explorers-log-sheets/space-alert-2-explorers-log-en.pdf) and [achievement sheet](https://filemanager.czechgames.com/storage/files/space-alert-the-new-frontier/other-downloads/achievements/space-alert-2-achievements-en.pdf), checked against the expansion rules. Blank XP boxes per level are `8 + 4 × level`; dotted prefixes are 0 for levels 0–1, then 4/7/10/13/16 for levels 2–6, then `4 + 2 × level`. Dotted boxes are skipped only when marking the following blank box; later consent to cloning does not revoke previously skipped boxes.
The engine checks minimum levels before the run, successful completion, applicable mission difficulty/crew constraints, and once-per-career / once-per-category limits. Social, personal close-call, hot-shot and specialization-use achievements may require observation or group judgment; the local viewer records the players' attestation, rather than pretending to infer it from the move log. The optional group-defined Hometown Hero achievement remains a paper/house-rule entry.
## Source discrepancy to resolve before online release
**Ninja poison timing:** the official English and French appendix activates drones when Ninja appears, whereas the translated card face places their release in action X. This implementation follows the official appendix (poison starts at appearance), with its X effect idempotently reasserting the state. The original English printed card or publisher errata should settle this discrepancy before BGS publication; it is not presented as verified agreement between all sources.
## 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.

View file

@ -1,6 +1,6 @@
# Game design and implementation scope # Game design and implementation scope
Research baseline: 2026-09-29. The requested scope is the base game **and The New Frontier**. This document distinguishes decisions, tested timing behavior and work still to implement. Updated: 2026-09-30. The requested scope is the base game **and The New Frontier**. This document records the architecture, implemented local rules and online release gates.
## Architecture ## Architecture
@ -13,7 +13,7 @@ Use four separate components:
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. 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 local host demonstrates this boundary without editing BGS.
The current code implements the **timing/session part** of this design. Mission announcements are recorded; their future gameplay effects (drawing a card, activating a threat, exchanging a card) are not yet implemented. 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.
## Base game ## Base game
@ -34,7 +34,7 @@ Sources: [base rules](https://filemanager.czechgames.com/storage/files/space-ale
## The New Frontier — all four modules in scope ## The New Frontier — all four modules in scope
Modules should be selectable independently where the rules permit, with validated dependencies. They are **planned**, not implemented by merely importing the expansion mission schedules. Modules should be selectable independently where the rules permit, with validated dependencies. All four modules now have local engine and viewer support. Detailed component evidence and limitations are in [the component audit](components.md).
| Module | Engine and UI work | | Module | Engine and UI work |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@ -63,14 +63,14 @@ The supplied Android application is useful for **mission schedules, generator lo
The root is MIT-licensed, but multiple generator files have GPL-3.0-or-later headers. Preserve per-file notices when porting; see [THIRD_PARTY.md](../THIRD_PARTY.md). Audio is separate from the timeline. Do not infer publisher-artwork or voice-pack distribution rights from a repository code license. The prototype uses text, with no copied game art or recordings. The root is MIT-licensed, but multiple generator files have GPL-3.0-or-later headers. Preserve per-file notices when porting; see [THIRD_PARTY.md](../THIRD_PARTY.md). Audio is separate from the timeline. Do not infer publisher-artwork or voice-pack distribution rights from a repository code license. The prototype uses text, with no copied game art or recordings.
Before claiming a complete adaptation, audit the exact action-card multiset, all threat values/effects, seven trajectories, damage tiles, heroic cards, specialization cards and experience tables against verified components. The rulebooks do not enumerate every component face. Missing data must remain explicit; do not fill gaps with plausible-looking values. For the current audit of the complete standard inventory, see [components](components.md). Continue cross-checking the exact action-card multiset, all threat values/effects, seven trajectories, damage tiles, heroic cards, specialization cards and experience tables against verified components. The rulebooks do not enumerate every component face. Missing data must remain explicit; do not fill gaps with plausible-looking values.
## Implementation order and release gates ## Implementation status and release gates
1. **Timing boundary — implemented prototype:** presence cancellation, common start, autonomous announcements, per-player phase advancement, deadlines and reconnect. Connect this to the eventual host contract later. 1. **Timing:** readiness, shared start, autonomous deadlines, reconnect and per-player phase locks implemented and tested. Untimed tutorials use explicit host clock advances without changing normal mission timing.
2. **Playable training mission:** correct action deck, private programming, six-station ship and deterministic resolution for a documented fixed scenario. Exercise it with multiple independently viewed seats. 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. **Complete base game:** all threats/trajectories, remaining systems, android/solo variants, score, campaigns, replay, localization and tutorials. 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. **New Frontier:** all four modules above, with coverage per rule interaction and a character-persistence adapter. Double-action schedules alone do not satisfy this milestone. 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 integration and release:** implement the agreed platform/protocol support only when authorized, verify real multi-client timing and reconnect, inspect mobile behavior, confirm content provenance and publish after rules review. 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.
Required regression cases include two simultaneous edits to one android slot; a transfer racing its closing beep; a move received at a phase cutoff; several missed deadlines during restart; a player independently entering phase 3 during global phase 1; delayed double actions; Medic ordering; simultaneous external/internal T+ threats; campaign repairs; and duplicate career-completion writes. 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,9 +1,9 @@
{ {
"name": "@boardgamers/space-alert", "name": "@boardgamers/space-alert",
"version": "0.0.1", "version": "0.1.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Space Alert and The New Frontier: BGS integration research and mission timing prototype", "description": "Space Alert and The New Frontier: deterministic game engine and local playtest",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"engines": { "engines": {
"node": ">=24" "node": ">=24"

File diff suppressed because it is too large Load diff

View file

@ -1,79 +1,192 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="fr">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Space Alert · Mission timing prototype</title> <title>Space Alert · Sitting Duck</title>
<link rel="stylesheet" href="/style.css" /> <link rel="stylesheet" href="/style.css" />
</head> </head>
<body> <body>
<header>
<a class="brand" href="/"
>✦
<span>SPACE ALERT<small>SITTING DUCK · FLIGHT CONSOLE</small></span></a
>
<div class="header-tools">
<select id="locale" aria-label="Langue">
<option value="fr">FR</option>
<option value="en">EN</option></select
><select id="seat" aria-label="Joueur"></select
><button
id="sound"
class="quiet"
aria-pressed="false"
title="Annonces vocales"
>
♫
</button>
</div>
</header>
<main> <main>
<header> <div class="mission-line">
<span class="eyebrow">BOARDGAMERS / FLIGHT SYSTEMS</span> <div>
<h1>Space Alert<span>Mission console</span></h1> <span id="connection">LOCAL</span>
<p class="scope">Timing prototype · Base game + The New Frontier</p> <h1 id="status">Space Alert</h1>
</header>
<section class="clock-panel" aria-labelledby="status">
<div class="clock-top">
<span id="status">Connecting…</span
><span id="connection">LOCAL HOST</span>
</div> </div>
<div id="clock">02:00</div> <div class="timer">
<p id="clock-caption">Checking crew presence</p> <strong id="clock">02:00</strong><small id="clock-caption"></small>
<div class="phase-track" aria-label="Mission phases">
<span data-phase="1">01 <small>Turns 1–3</small></span
><span data-phase="2">02 <small>Turns 4–7</small></span
><span data-phase="3">03 <small>Turns 8–12</small></span>
</div> </div>
</section> </div>
<div class="columns"> <div id="crew" class="crew"></div>
<section class="panel"> <div id="error" role="alert"></div>
<div id="notice" class="notice"></div>
<section id="lesson-guide" hidden></section>
<div class="flight-layout">
<section class="tactical">
<div class="section-heading"> <div class="section-heading">
<h2>Crew</h2> <h2 id="ship-title"></h2>
<label class="seat-label" <span id="comms"></span>
>Viewing
<select id="seat" aria-label="Player seat"></select
></label>
</div> </div>
<div id="crew"></div> <div id="ship" class="ship"></div>
<div id="controls"></div> <div id="resources" class="resources"></div>
<p id="player-help" class="muted"></p> <div class="section-heading">
<p id="error" role="alert"></p> <h2 id="threat-title"></h2>
<span id="phase"></span>
</div>
<div id="threats"></div>
<div id="latest" class="latest" aria-live="polite"></div>
</section> </section>
<section class="panel"> <section id="planning">
<div class="section-heading"> <div class="section-heading">
<h2>Computer</h2> <h2 id="program-title"></h2>
<span id="comms" class="tag">ONLINE</span> <select
id="program-crew"
aria-label="Équipier à programmer"
></select>
</div> </div>
<p id="latest" aria-live="polite">Awaiting crew confirmation.</p> <div id="program" class="program"></div>
<ol id="announcements"></ol> <p id="player-help"></p>
<div id="controls" class="controls"></div>
<div id="selection-tools"></div>
<p id="card-help" aria-live="polite"></p>
<div id="hand-filter"></div>
<div id="hand" class="hand"></div>
<div id="teleport"></div>
<div id="transfer"></div>
<div id="replay"></div>
<div id="campaign"></div>
</section> </section>
</div> </div>
<details class="setup" open> <details id="journal">
<summary>Local test controls</summary> <summary id="journal-title"></summary>
<div class="setup-fields"> <ol id="announcements"></ol>
<label>Mission<select id="mission"></select></label
><label
>Humans<select id="players">
<option>1</option>
<option>2</option>
<option>3</option>
<option selected>4</option>
<option>5</option>
</select></label
><button id="new">New session</button
><button id="ready-all" class="secondary">Ready all · demo</button>
</div>
<p class="muted">
Open another tab to inspect another seat. These controls operate one
shared, local session.
</p>
</details> </details>
<footer> <details id="lessons">
This prototype validates presence, timing and phase locks. Cards, ship <summary id="lessons-title">École de vol · exercices libres</summary>
combat, specialization effects and experience are not implemented yet. <div id="lesson-list"></div>
No BGS game is created. </details>
</footer> <details id="setup">
<summary id="setup-title"></summary>
<form id="new-session">
<label id="players-label"
>Joueurs
<select id="players">
<option value="1">Solo · 4 androïdes</option>
<option value="2">2 + 2 androïdes</option>
<option value="3">3 + 1 androïde</option>
<option value="4" selected>4</option>
<option value="5">5</option>
</select></label
><label
>Équipage<select id="crew-size">
<option value="0">Standard</option>
<option value="5">5 équipiers (androïde supplémentaire)</option>
<option value="3">3 joueurs sans androïde</option>
</select></label
><label
>Mission
<select id="mission"></select></label
><label id="special-label"
>Spécialisations
<select id="specialization">
<option value="">Aucune</option>
<option value="1">Niveau 1</option>
<option value="2">Niveau 2</option>
<option value="3">Niveau 3</option>
</select></label
><label
>Menaces<select id="threat-expansion">
<option value="0">Jeu de base</option>
<option value="1">+ The New Frontier</option>
</select></label
>
<label
>Menaces communes<select id="difficulty">
<option value="1">Blanches</option>
<option value="1,2">Blanches + jaunes</option>
<option value="2">Jaunes</option>
<option value="1,2,3">Toutes</option>
<option value="2,3">Jaunes + rouges</option>
<option value="3">Rouges</option>
</select></label
>
<label
>Menaces sérieuses<select id="serious-difficulty">
<option value="1">Blanches</option>
<option value="1,2">Blanches + jaunes</option>
<option value="2">Jaunes</option>
<option value="1,2,3">Toutes</option>
<option value="2,3">Jaunes + rouges</option>
<option value="3">Rouges</option>
</select></label
>
<label
>Format<select id="campaign-limit">
<option value="0">Mission unique</option>
<option value="3">Campagne · 3 missions</option>
<option value="5">Campagne · 5 missions</option>
</select></label
>
<label
>Expérience<select id="careers-enabled">
<option value="0">Partie libre</option>
<option value="1">Carrières enregistrées</option>
</select></label
>
<div id="career-seats" class="token-controls"></div>
<div id="specialists" class="token-controls"></div>
<button type="submit" id="new-button">Nouvelle session locale</button>
</form>
<p id="scope"></p>
<button id="ready-all" class="quiet">
Confirmer tous les joueurs · test local</button
><button id="next-event" class="quiet">
Prochaine annonce · test local
</button>
</details>
<details id="career-manager">
<summary id="career-title">Explorateurs · carrières locales</summary>
<form id="create-explorer">
<label
>Nom<input
id="explorer-name"
required
maxlength="80"
autocomplete="off" /></label
><label
>Clonage<select id="explorer-cloning">
<option value="1">Autorisé</option>
<option value="0">Hardcore · mort définitive</option>
</select></label
><button id="create-explorer-button">Créer un explorateur</button>
</form>
<div id="explorers"></div>
</details>
<details>
<summary id="help-title"></summary>
<div id="help"></div>
</details>
<footer id="footer"></footer>
</main> </main>
<script type="module" src="/app.js"></script> <script type="module" src="/app.js"></script>
</body> </body>

View file

@ -1,6 +1,28 @@
import { LESSONS, createLesson } from "../src/tutorials.js";
import { departCampaign } from "../src/game/campaign.js";
import {
createExplorer,
startExplorer,
settleExplorer,
cancelExplorer,
consentToCloning,
learnSpecialization,
claimAchievement,
eligibleAchievements,
} from "../src/game/career.js";
import { createServer } from "node:http"; import { createServer } from "node:http";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import {
readFileSync,
writeFileSync,
mkdirSync,
renameSync,
existsSync,
} from "node:fs";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { SPECIALIZATIONS } from "../src/game/cards.js";
import { missionSummaries, getMission } from "../src/missions.js"; import { missionSummaries, getMission } from "../src/missions.js";
import { import {
createSession, createSession,
@ -10,22 +32,124 @@ import {
snapshot, snapshot,
} from "../src/session.js"; } from "../src/session.js";
export function createPreviewServer({ clock = Date.now } = {}) { export function createPreviewServer({ clock = Date.now, storagePath } = {}) {
let offset = 0,
explorers = {},
careerIds = [];
const trustedClock = () =>
state?.tutorial && state.stage === "programming"
? state.observedAt
: clock() + offset;
let state = createSession( let state = createSession(
{ players: 4, mission: getMission("realmission1") }, {
players: 4,
mission: getMission("realmission1"),
gameOptions: { seed: randomUUID() },
},
clock(), clock(),
); );
if (storagePath && existsSync(storagePath)) {
const saved = JSON.parse(readFileSync(storagePath, "utf8"));
if (saved.schema === 2) {
state = saved.state;
offset = saved.offset ?? 0;
explorers = saved.explorers ?? {};
careerIds = saved.careerIds ?? [];
state = advanceClock(state, trustedClock());
} else
writeFileSync(storagePath + ".legacy-backup", JSON.stringify(saved), {
mode: 0o600,
});
}
let persisted = -1;
function persist() {
if (!storagePath || persisted === state.revision) return;
mkdirSync(dirname(storagePath), { recursive: true });
writeFileSync(
storagePath + ".tmp",
JSON.stringify({ schema: 2, state, offset, explorers, careerIds }),
{
mode: 0o600,
},
);
renameSync(storagePath + ".tmp", storagePath);
persisted = state.revision;
}
function settleCareers() {
if (!careerIds.length) return;
const g = state.game,
result =
g.campaign?.outcome ?? (!g.campaign ? g.resolution?.outcome : null),
runId = g.campaign?.id ?? g.seed;
if (state.stage === "cancelled") {
for (const id of careerIds)
if (explorers[id].activeRun === runId)
explorers[id] = cancelExplorer(explorers[id], runId);
return;
}
if (!result) return;
const metadata = {
mission: state.mission.id,
humans: state.players.length,
crew: state.crewSize,
doubleActions: state.mission.doubleActions,
difficulty: g.difficulty,
seriousDifficulty: g.seriousDifficulty,
penalties: result.penalties,
threatCount: state.timeline
.filter((e) => e.type === "threat")
.reduce((n, e) => n + (e.severity === "serious" ? 2 : 1), 0),
};
for (const [seat, id] of careerIds.entries())
explorers[id] = settleExplorer(explorers[id], {
id: runId,
...result,
count: g.campaign?.missions.length ?? 1,
limit: g.campaign?.limit ?? 3,
training: !/^(realmission|double)/.test(state.mission.id),
humans: state.players.length,
at: trustedClock(),
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}`),
});
}
function viewFor(seat) {
const view = snapshot(state, seat);
view.tutorial = state.tutorial;
view.careerIds = careerIds;
view.explorers = Object.values(explorers).map((e) => ({
...e,
activeRun: !!e.activeRun,
eligible: e.runs.length ? eligibleAchievements(e, e.runs.at(-1).id) : [],
}));
return view;
}
let timer; let timer;
function schedule() { function schedule() {
clearTimeout(timer); clearTimeout(timer);
settleCareers();
persist();
if (state.tutorial && state.stage === "programming") return;
const at = nextWakeup(state); const at = nextWakeup(state);
if (at === null) return; if (at === null) return;
timer = setTimeout( timer = setTimeout(
() => { () => {
state = advanceClock(state, clock()); state = advanceClock(state, trustedClock());
schedule(); schedule();
}, },
Math.max(1, at - clock()), Math.max(1, at - trustedClock()),
); );
timer.unref(); timer.unref();
} }
@ -44,16 +168,29 @@ export function createPreviewServer({ clock = Date.now } = {}) {
seatValue !== null && /^\d$/.test(seatValue) seatValue !== null && /^\d$/.test(seatValue)
? Number(seatValue) ? Number(seatValue)
: undefined; : undefined;
if (req.method === "GET" && url.pathname === "/api/lessons")
return json(
200,
LESSONS.map(({ id, title }) => ({ id, title })),
);
if (req.method === "GET" && url.pathname === "/api/missions") if (req.method === "GET" && url.pathname === "/api/missions")
return json(200, missionSummaries); return json(200, missionSummaries);
if (req.method === "GET" && url.pathname === "/api/state") { if (req.method === "GET" && url.pathname === "/api/state") {
state = advanceClock(state, clock()); state = advanceClock(state, trustedClock());
schedule(); schedule();
return json(200, snapshot(state, seat)); return json(200, viewFor(seat));
} }
if ( if (
req.method === "POST" && req.method === "POST" &&
["/api/command", "/api/new"].includes(url.pathname) [
"/api/command",
"/api/new",
"/api/advance",
"/api/career",
"/api/lesson",
"/api/lesson-next",
"/api/campaign-next",
].includes(url.pathname)
) { ) {
const origin = req.headers.origin; const origin = req.headers.origin;
const localOrigin = `http://${req.headers.host}`; const localOrigin = `http://${req.headers.host}`;
@ -71,27 +208,199 @@ export function createPreviewServer({ clock = Date.now } = {}) {
return json(413, { error: "Request too large" }); return json(413, { error: "Request too large" });
} }
const command = JSON.parse(body); const command = JSON.parse(body);
if (url.pathname === "/api/new") { if (url.pathname === "/api/lesson") {
state = createSession( if (careerIds.some((id) => explorers[id].activeRun))
{ players: command.players, mission: getMission(command.mission) }, throw Error("Finish the current career mission first");
clock(), state = createLesson(command.lesson, clock() + offset);
careerIds = [];
persisted = -1;
schedule();
return json(200, viewFor(0));
}
if (url.pathname === "/api/lesson-next") {
if (!state.tutorial || state.stage !== "programming")
throw Error("No active lesson");
state = advanceClock(
state,
state.missionStartAt + state.mission.phaseEndsMs[state.phase - 1],
); );
schedule(); schedule();
return json(200, snapshot(state, seat)); return json(200, viewFor(0));
} }
const result = submit(state, seat, command, clock()); if (url.pathname === "/api/career") {
const next = { ...explorers };
if (command.type === "create") {
const id = randomUUID();
next[id] = createExplorer(id, command.name, command.cloning);
} else {
if (!next[command.id]) throw Error("Unknown explorer");
if (command.type === "consent")
next[command.id] = consentToCloning(next[command.id]);
else if (command.type === "learn")
next[command.id] = learnSpecialization(
next[command.id],
command.specialization,
);
else if (command.type === "claim")
next[command.id] = claimAchievement(
next[command.id],
command.runId,
command.achievement,
{ crewAgrees: command.crewAgrees === true },
);
else throw Error("Unknown career command");
}
explorers = next;
persisted = -1;
schedule();
return json(200, viewFor(seat));
}
if (url.pathname === "/api/campaign-next") {
if (seat !== 0 || !state.game.campaign)
throw Error("Only the captain starts the next campaign mission");
const mission = getMission(command.mission ?? state.mission.id);
if (!/^(realmission|double)/.test(mission.id))
throw Error("Campaigns require full missions");
const campaign = departCampaign(
state.game.campaign,
command.botStation,
);
const g = state.game;
const next = createSession(
{
players: state.players.length,
crewSize: state.crewSize,
mission,
gameOptions: {
seed: randomUUID(),
campaign,
threatExpansion: g.threatExpansion,
difficulty: command.difficulty ?? g.difficulty,
seriousDifficulty:
command.seriousDifficulty ?? g.seriousDifficulty,
specializations: g.specializations,
},
},
trustedClock(),
);
state = next;
persisted = -1;
schedule();
return json(200, viewFor(seat));
}
if (url.pathname === "/api/advance") {
const wake = nextWakeup(state);
if (
["programming", "countdown"].includes(state.stage) &&
wake !== null
) {
offset = Math.max(offset, wake - clock());
state = advanceClock(state, trustedClock());
schedule();
}
return json(200, viewFor(seat));
}
if (url.pathname === "/api/new") {
const options = command.gameOptions ?? {};
if (
Object.keys(options).some(
(k) =>
![
"specializations",
"threatExpansion",
"difficulty",
"seriousDifficulty",
"campaignLimit",
].includes(k),
)
)
throw Error("Unsupported setup option");
if (
options.specializations?.some(
(s) =>
s &&
(!SPECIALIZATIONS.includes(s.name) ||
![1, 2, 3].includes(s.level)),
)
)
throw Error("Invalid specialization");
if (
options.campaignLimit &&
!/^(realmission|double)/.test(command.mission)
)
throw Error("Campaigns require full missions");
const nextState = createSession(
{
players: command.players,
crewSize: command.crewSize,
mission: getMission(command.mission),
gameOptions: { ...options, seed: randomUUID() },
},
trustedClock(),
);
const ids = command.careerIds ?? [];
if (careerIds.some((id) => explorers[id].activeRun))
throw Error(
"Finish the current career mission before replacing it",
);
const nextExplorers = structuredClone(explorers);
if (ids.length) {
if (
ids.length !== command.players ||
new Set(ids).size !== ids.length ||
ids.some((id) => !nextExplorers[id])
)
throw Error("Choose a different explorer for every player");
const specs = options.specializations ?? [];
if (specs.length !== nextState.crewSize)
throw Error(
"Career games use specialization rules, including level-zero crew",
);
for (let i = 0; i < specs.length; i++) {
const s = specs[i];
if (!s) continue;
const owners =
command.players === 1 || i >= command.players ? ids : [ids[i]];
if (
!owners.some(
(id) =>
(nextExplorers[id].specializations[s.name] ?? 0) >= s.level,
)
)
throw Error("This crew has not learned that specialization");
}
if (
options.campaignLimit &&
ids.some((id) => nextExplorers[id].level < 2)
)
throw Error("Explorers need level 2 for campaigns");
for (const id of ids)
nextExplorers[id] = startExplorer(
nextExplorers[id],
nextState.game.campaign?.id ?? nextState.game.seed,
);
}
state = nextState;
explorers = nextExplorers;
careerIds = ids;
persisted = -1;
schedule();
return json(200, viewFor(seat));
}
const result = submit(state, seat, command, trustedClock());
state = result.state; state = result.state;
schedule(); schedule();
return json(result.accepted ? 200 : 409, { return json(result.accepted ? 200 : 409, {
accepted: result.accepted, accepted: result.accepted,
duplicate: result.duplicate, duplicate: result.duplicate,
error: result.error, error: result.error,
view: snapshot(state, seat), view: viewFor(seat),
}); });
} }
const file = { const file = {
"/": "index.html", "/": "index.html",
"/app.js": "app.js", "/app.js": "app.js",
"/text.js": "text.js",
"/style.css": "style.css", "/style.css": "style.css",
}[url.pathname]; }[url.pathname];
if (req.method === "GET" && file) { if (req.method === "GET" && file) {
@ -115,7 +424,9 @@ export function createPreviewServer({ clock = Date.now } = {}) {
} }
if (process.argv[1] === fileURLToPath(import.meta.url)) { if (process.argv[1] === fileURLToPath(import.meta.url)) {
const port = Number(process.env.PORT ?? 5250); const port = Number(process.env.PORT ?? 5250);
createPreviewServer().listen(port, "127.0.0.1", () => createPreviewServer({
console.log(`Space Alert timing prototype: http://127.0.0.1:${port}`), storagePath: new URL("../.local/session.json", import.meta.url).pathname,
}).listen(port, "127.0.0.1", () =>
console.log(`Space Alert local playtest: http://127.0.0.1:${port}`),
); );
} }

View file

@ -1,341 +1,697 @@
:root { :root {
color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif;
font-family: color: #d4e1e6;
system-ui, background: #0b141c;
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
color: #dbe6eb;
background: #0b131d;
font-synthesis: none; font-synthesis: none;
--muted: #95aab6;
--line: #2b3c48;
--gold: #e8c984;
--panel: #12232f;
--cyan: #78cecf;
--red: #e2968d;
--blue: #8ab4ec;
--white: #d6d4b9;
color-scheme: dark;
} }
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
margin: 0; margin: 0;
background: radial-gradient(ellipse at 10% 0, #20344450, transparent 60%);
min-height: 100vh;
} }
main { button,
width: min(960px, 100%); select,
margin: auto; input {
padding: 32px 24px 24px; font: inherit;
} }
button, button,
select { select {
font: inherit;
color: inherit; color: inherit;
min-height: 42px; background: #1a303e;
border: 1px solid #415864;
border-radius: 7px; border-radius: 7px;
border: 1px solid #3b505e; min-height: 40px;
background: #172733;
padding: 8px 12px; padding: 8px 12px;
touch-action: manipulation; touch-action: manipulation;
} }
button { button {
cursor: pointer; cursor: pointer;
background: #9de8da;
color: #09202b;
border-color: #9de8da;
font-weight: 650;
} }
button:hover { button:hover {
filter: brightness(1.08); border-color: var(--gold);
}
button:disabled {
opacity: 0.45;
cursor: default;
}
.secondary {
background: #172733;
color: #c6d7e0;
border-color: #3b505e;
} }
button:focus-visible, button:focus-visible,
select:focus-visible, select:focus-visible,
summary:focus-visible { summary:focus-visible {
outline: 2px solid #e8bf78; outline: 2px solid var(--gold);
outline-offset: 3px; outline-offset: 3px;
} }
h1, button:disabled {
h2, opacity: 0.4;
p { cursor: default;
margin: 0;
} }
.eyebrow { button.quiet {
font: background: transparent;
11px ui-monospace, border-color: var(--line);
monospace; font-size: 12px;
letter-spacing: 0.15em;
color: #9de8da;
} }
h1 { a {
font-size: 34px; color: inherit;
font-weight: 600;
margin: 10px 0;
} }
h1 span { header {
font-size: 16px;
font-weight: 400;
color: #9dafba;
margin-left: 16px;
}
.scope,
.muted,
footer {
font-size: 13px;
line-height: 1.5;
color: #94a9b6;
}
.clock-panel {
margin: 24px 0 16px;
padding: 20px 24px 0;
border: 1px solid #334954;
border-radius: 12px;
background: linear-gradient(120deg, #1a3340, #13232f);
overflow: hidden;
}
.clock-top {
display: flex; display: flex;
align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
font: max-width: 1260px;
12px ui-monospace, margin: auto;
monospace; padding: 22px 28px;
text-transform: uppercase; border-bottom: 1px solid var(--line);
color: #c5e6e7; }
.brand {
display: flex;
gap: 12px;
text-decoration: none;
color: var(--gold);
font-size: 22px;
letter-spacing: 3px;
font-weight: 800;
}
.brand small {
display: block;
font-size: 8px;
letter-spacing: 2px;
color: var(--muted);
margin-top: 4px;
}
.header-tools {
display: flex;
gap: 7px;
}
main {
max-width: 1260px;
margin: auto;
padding: 22px 28px;
}
.mission-line {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
}
h1 {
font-size: 22px;
font-weight: 600;
margin: 4px 0 12px;
} }
#connection { #connection {
color: #86a1ad; font-size: 9px;
font-size: 10px; letter-spacing: 2px;
color: var(--cyan);
} }
#clock { .timer {
font: text-align: right;
64px ui-monospace,
monospace;
letter-spacing: -0.04em;
margin: 12px 0 2px;
color: #b9f3e4;
} }
#clock-caption { .timer strong {
font-size: 13px; font-size: 32px;
color: #b2c5ce; letter-spacing: 2px;
min-height: 20px; font-variant-numeric: tabular-nums;
color: var(--gold);
} }
.phase-track { .timer small {
display: flex;
gap: 8px;
margin-top: 22px;
border-top: 1px solid #3b505e;
}
.phase-track > span {
flex: 1;
padding: 14px 0;
font:
15px ui-monospace,
monospace;
color: #77909d;
}
.phase-track small {
font:
11px system-ui,
sans-serif;
display: block; display: block;
margin-top: 5px; color: var(--muted);
font-size: 11px;
} }
.phase-track .active { .crew {
color: #b9f3e4; display: flex;
border-top: 2px solid #9de8da; flex-wrap: wrap;
margin-top: -1px; gap: 5px;
margin: 8px 0 16px;
} }
.columns { .crew-member {
font-size: 12px;
border: 1px solid var(--line);
padding: 5px 9px;
border-radius: 30px;
}
.crew-member.own {
border-color: var(--gold);
}
.crew-member.ready::before {
content: "● ";
color: var(--cyan);
}
.notice {
font-size: 12px;
color: var(--muted);
border-left: 2px solid #67737b;
padding: 4px 12px;
margin-bottom: 20px;
line-height: 1.5;
}
.flight-layout {
display: grid; display: grid;
grid-template-columns: 1fr 1fr; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);
gap: 16px; gap: 30px;
}
.panel {
background: #111e29;
border: 1px solid #293d4a;
border-radius: 10px;
padding: 18px;
} }
.section-heading { .section-heading {
display: flex; display: flex;
justify-content: space-between;
align-items: center; align-items: center;
gap: 8px; justify-content: space-between;
margin-bottom: 16px; gap: 10px;
margin: 0 0 10px;
} }
h2 { h2 {
font-size: 16px;
font-weight: 600;
}
.seat-label {
font-size: 11px; font-size: 11px;
color: #94a9b6; letter-spacing: 1.5px;
display: flex; text-transform: uppercase;
align-items: center; margin: 0;
gap: 6px; color: var(--muted);
} }
.seat-label select { #comms,
min-height: 36px; #phase {
padding: 4px 8px; font-size: 10px;
letter-spacing: 1px;
color: var(--cyan);
}
#comms.offline {
color: var(--red);
}
.ship {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
padding: 12px 10px;
background: linear-gradient(130deg, #1d3444, #11202b);
border: 1px solid #3a5260;
border-radius: 50% 50% 14px 14px/12% 12% 10px 10px;
}
.station {
border: 1px solid #405864;
border-top: 3px solid var(--zone);
background: #0d1c28ce;
padding: 10px 7px;
border-radius: 6px;
min-width: 0;
position: relative;
}
.station-title {
font-size: 10px;
color: var(--zone);
text-transform: uppercase;
font-weight: 700;
letter-spacing: 0.4px;
}
.station .weapon {
font-size: 20px;
margin: 9px 0 5px;
color: var(--zone);
}
.systems {
font-size: 10px;
line-height: 1.8;
color: #b1c4cf;
}
.systems b {
display: inline-block;
color: var(--gold);
min-width: 15px;
}
.occupants {
min-height: 23px;
display: flex;
gap: 2px;
flex-wrap: wrap;
margin-top: 6px;
}
.pawn {
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid var(--gold);
background: #e8c98420;
color: var(--gold);
border-radius: 50%;
width: 21px;
height: 21px;
font-size: 11px;
font-weight: 700;
}
.pawn.out {
opacity: 0.5;
text-decoration: line-through;
}
.damage {
color: var(--red);
font-size: 10px;
}
.resources {
display: flex;
justify-content: space-between;
gap: 4px;
flex-wrap: wrap;
font-size: 11px;
padding: 10px 0 18px;
color: var(--muted);
}
.resources b {
color: var(--gold);
}
.threat {
border: 1px solid var(--line);
border-left: 3px solid var(--zone);
border-radius: 5px;
margin: 7px 0;
padding: 9px 11px;
background: #101f2b;
}
.threat summary {
display: flex;
gap: 7px;
align-items: center;
cursor: pointer;
font-size: 12px; font-size: 12px;
} }
.crew-member { .threat summary strong {
display: flex; flex: 1;
align-items: center;
gap: 10px;
padding: 9px 0;
border-top: 1px solid #243744;
font-size: 13px;
} }
.crew-member .indicator { .threat .stats {
width: 8px; color: var(--muted);
height: 8px;
border-radius: 50%;
background: #53626d;
flex-shrink: 0;
}
.crew-member .indicator.ready {
background: #9de8da;
}
.crew-member strong {
font-weight: 500;
}
.crew-member small {
margin-left: auto;
color: #95aeb9;
font-size: 11px; font-size: 11px;
} }
#controls { .threat p {
margin-top: 14px; font-size: 12px;
line-height: 1.6;
}
.track {
display: flex; display: flex;
gap: 8px; gap: 2px;
align-items: center;
margin: 8px 0;
}
.track span {
height: 12px;
flex: 1;
background: #344453;
font-size: 8px;
text-align: center;
}
.track .current {
background: var(--gold);
color: #0d1c28;
}
.track .mark {
border-bottom: 2px solid var(--red);
}
.latest {
font-size: 12px;
color: var(--gold);
border-top: 1px solid var(--line);
padding: 12px 0;
line-height: 1.5;
}
.program {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 5px;
}
.slot {
min-width: 0;
min-height: 64px;
padding: 5px 3px;
background: #101f2b;
border-color: #344553;
}
.slot .turn {
font-size: 9px;
color: var(--muted);
display: block;
}
.slot .action {
font-size: 18px;
display: block;
min-height: 22px;
}
.slot.future {
opacity: 0.4;
}
.slot.locked {
background: #25323a;
opacity: 0.75;
}
.slot.selected {
outline: 2px solid var(--gold);
}
.controls {
display: flex;
gap: 6px;
flex-wrap: wrap; flex-wrap: wrap;
margin: 10px 0;
}
.controls button {
font-size: 12px;
}
.controls .primary {
background: var(--gold);
border-color: var(--gold);
color: #15242c;
font-weight: 700;
} }
#player-help { #player-help {
margin-top: 10px;
}
#error {
font-size: 13px;
color: #ffd6a1;
margin-top: 8px;
}
.tag {
font:
10px ui-monospace,
monospace;
color: #9de8da;
border: 1px solid #35534f;
border-radius: 4px;
padding: 5px;
}
.tag.offline {
color: #ffd6a1;
border-color: #765d3c;
}
#latest {
font-size: 17px;
line-height: 1.4;
min-height: 48px;
color: #e9f3f5;
}
#announcements {
list-style: none;
margin: 14px 0 0;
padding: 0;
}
#announcements li {
font-size: 12px; font-size: 12px;
line-height: 1.45; color: var(--muted);
color: #a6b8c2; min-height: 18px;
border-top: 1px solid #243744; line-height: 1.5;
padding: 9px 0; }
.hand {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 6px;
}
.card {
border: 1px solid #62787d;
background: #192d36;
border-radius: 8px;
overflow: clip;
position: relative;
}
.card.special,
.card.heroic {
border-color: var(--gold);
}
.card button {
border: 0;
border-radius: 0;
width: 100%;
min-height: 42px;
padding: 4px;
font-size: 20px;
background: transparent;
}
.card button + button {
border-top: 1px solid var(--line);
}
.card button.selected {
background: var(--gold);
color: #132430;
}
.card .tiny {
font-size: 10px;
line-height: 1.2;
display: block;
}
.card .copies {
position: absolute;
top: 3px;
right: 3px;
font-size: 8px;
color: var(--muted);
pointer-events: none;
}
.empty {
font-size: 13px;
color: var(--muted);
padding: 16px 0;
line-height: 1.5;
}
#transfer {
display: flex; display: flex;
gap: 10px; gap: 6px;
flex-wrap: wrap;
margin: 12px 0;
} }
#announcements time { #transfer button {
color: #7e9aa9; font-size: 11px;
font:
11px ui-monospace,
monospace;
flex-shrink: 0;
padding-top: 2px;
} }
.setup { #replay input {
margin-top: 16px; width: 100%;
background: #0f1b26;
border: 1px solid #293d4a;
border-radius: 10px;
padding: 15px 18px;
} }
.setup summary { #replay p {
font-size: 12px;
line-height: 1.6;
}
main > details {
border-top: 1px solid var(--line);
margin-top: 24px;
padding-top: 12px;
}
summary {
cursor: pointer; cursor: pointer;
font-size: 13px; font-size: 13px;
min-height: 24px; min-height: 36px;
line-height: 1.5;
} }
.setup-fields { ol {
padding-left: 24px;
}
li {
font-size: 12px;
line-height: 1.6;
padding: 4px 0;
color: var(--muted);
}
#announcements {
max-height: 330px;
overflow: auto;
overscroll-behavior: auto;
touch-action: auto;
}
form {
display: flex; display: flex;
gap: 12px;
align-items: end; align-items: end;
gap: 10px;
margin: 14px 0 10px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.setup-fields label { label {
font-size: 12px;
color: var(--muted);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
font-size: 12px;
color: #9db2bd;
} }
.setup-fields label:first-child { form button {
flex: 1; background: var(--gold);
min-width: 180px; color: #10202a;
} }
.setup-fields select { #scope,
width: 100%; #help {
font-size: 13px;
line-height: 1.7;
color: var(--muted);
} }
footer { footer {
margin-top: 18px; margin-top: 30px;
max-width: 760px; color: #78929f;
font-size: 12px; font-size: 11px;
line-height: 1.6;
} }
@media (max-width: 650px) { #error {
color: #ffc6b7;
font-size: 13px;
padding: 8px 0;
}
#error:empty {
padding: 0;
}
[hidden] {
display: none !important;
}
@media (max-width: 760px) {
header {
padding: 12px;
}
.brand {
font-size: 15px;
letter-spacing: 1px;
gap: 6px;
}
.brand small {
font-size: 6px;
letter-spacing: 1px;
}
.header-tools select {
padding: 5px;
font-size: 11px;
}
main { main {
padding: 20px 12px; padding: 12px;
} }
.columns { .flight-layout {
grid-template-columns: 1fr; grid-template-columns: minmax(0, 1fr);
} gap: 20px;
.clock-panel {
padding: 16px 18px 0;
margin-top: 18px;
} }
h1 { h1 {
font-size: 29px; font-size: 18px;
} }
h1 span { .timer strong {
display: block; font-size: 26px;
margin: 5px 0 0;
font-size: 14px;
} }
#clock { .notice {
font-size: 56px; margin-bottom: 14px;
font-size: 11px;
} }
.panel { .station {
padding: 15px; padding: 8px 6px;
} }
.scope { .ship {
font-size: 12px; padding: 10px 7px;
} }
.setup-fields { .program {
align-items: stretch; grid-template-columns: repeat(6, minmax(0, 1fr));
} }
.setup-fields button { .slot {
flex: 1; min-height: 58px;
} }
.phase-track small { .slot .action {
font-size: 16px;
}
.hand {
grid-template-columns: repeat(6, minmax(0, 1fr));
}
.card button {
min-height: 44px;
}
.crew-member {
font-size: 10px; font-size: 10px;
} }
.crew {
gap: 4px;
margin-bottom: 10px;
}
.resources {
font-size: 10px;
}
.header-tools {
gap: 4px;
}
#sound {
padding: 5px 9px;
}
.section-heading select {
max-width: 180px;
font-size: 12px;
}
.systems {
font-size: 9px;
}
}
@media (prefers-reduced-motion: reduce) {
* {
scroll-behavior: auto !important;
}
}
.token-controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: end;
margin: 10px 0;
}
#teleport small,
#card-help {
font-size: 12px;
color: var(--muted);
line-height: 1.5;
}
#card-help:empty {
display: none;
}
.trait {
color: var(--gold);
}
#combine[aria-pressed="true"] {
border-color: var(--gold);
color: var(--gold);
}
@media (max-width: 380px) {
.hand {
grid-template-columns: repeat(5, minmax(0, 1fr));
}
.header-tools {
gap: 2px;
}
header {
gap: 4px;
}
.brand small {
display: none;
}
}
#hand-filter {
display: flex;
flex-wrap: wrap;
gap: 0.3rem;
margin: 0.4rem 0;
}
#hand-filter [aria-pressed="true"] {
border-color: var(--gold);
}
#campaign button,
#explorers button {
margin: 0.2rem 0.1rem;
}
#explorers details {
margin: 0.6rem 0;
padding: 0.7rem;
border: 1px solid #34434d;
border-radius: 0.6rem;
}
#explorers select {
max-width: 100%;
}
#explorers label {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0.6rem 0;
}
#create-explorer {
display: flex;
flex-wrap: wrap;
gap: 0.7rem;
align-items: end;
margin: 0.8rem 0;
}
#create-explorer label {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
input:not([type="checkbox"]):not([type="range"]) {
padding: 0.6rem;
background: #13212b;
color: inherit;
border: 1px solid #43525c;
border-radius: 0.4rem;
max-width: 100%;
}
.called-threat {
border-left: 2px solid var(--gold);
margin: 0.7rem 0;
padding-left: 0.7rem;
}
.called-threat h4 {
margin: 0.5rem 0;
}
#lesson-guide {
border: 1px solid #465c65;
border-radius: 0.7rem;
padding: 1rem;
margin-bottom: 1rem;
background: #102530;
}
#lesson-guide li {
margin: 0.6rem 0;
line-height: 1.5;
}
#lesson-guide h2 {
font-size: 1rem;
}
#lesson-list button {
margin: 0.3rem 0.1rem;
} }

814
preview/text.js Normal file
View file

@ -0,0 +1,814 @@
const choose = (pair, locale) => pair?.[locale === "fr" ? 0 : 1];
const specials = {
rocketeer: [
[
"Lance une roquette depuis toute station. À distance, une réparation ne peut pas achever une panne.",
"Launch a rocket from any station. A remote repair cannot finish a malfunction.",
],
[
"En bas à droite : lance deux roquettes en un tir de force 5. Ailleurs : effectue C.",
"Lower blue: launch two rockets as a strength-5 shot. Elsewhere: perform C.",
],
],
"data-analyst": [
[
"Entretient l’ordinateur à distance et rapporte 1 point.",
"Maintain the computer remotely and gain 1 point.",
],
[
"Observation : compte comme trois équipiers. Ailleurs : effectue C.",
"Visual confirmation counts as three crew members. Elsewhere: perform C.",
],
],
"energy-technician": [
[
"Recharge le réacteur central avec une capsule, depuis toute station.",
"Refuel the central reactor with one capsule from any station.",
],
[
"Sur le pont supérieur : bouclier temporaire de 2 dans votre zone, 1 dans les autres, pour ce tour.",
"Upper deck: temporary shields of 2 in your zone and 1 elsewhere, for this turn.",
],
],
"pulse-gunner": [
[
"Tire avec le laser local et l’impulsion, si les deux peuvent fonctionner. Au canon à impulsion : tir normal.",
"Fire the local laser and pulse cannon if both can operate. At the pulse station: normal fire.",
],
[
"Impulsion : force 2 dans sa portée normale, force 1 une portée plus loin. Ailleurs : effectue A.",
"Pulse: strength 2 in normal range, strength 1 one range farther. Elsewhere: perform A.",
],
],
medic: [
[
"Avant le capitaine : rend héroïque le premier A, B ou combat de chacun dans votre station ce tour. Peut accompagner un déplacement simple.",
"Before the captain: enhance the first A, B or battlebot action of crew in your station this turn. May accompany one movement.",
],
[
"Avant le capitaine : personne avec vous ne peut être assommé ce tour ; −1 point. La protection vous suit. Peut accompagner un déplacement simple.",
"Before the captain: nobody with you can be knocked out this turn; −1 point. Protection follows you. May accompany one movement.",
],
],
teleporter: [
[
"Téléporte l’équipier au jeton départ auprès de celui au jeton arrivée. Choisissez les jetons pendant un transfert de données.",
"Teleport the departure-token crew member to the arrival-token crew member. Assign tokens during data transfer.",
],
[
"Depuis une zone latérale : téléporte vers la zone opposée, sur l’autre pont.",
"From a side zone: teleport to the opposite zone on the other deck.",
],
],
hypernavigator: [
[
"Sur le pont inférieur : toutes les menaces avancent d’une case de moins ce tour.",
"Lower deck: all threats move one fewer space this turn.",
],
[
"En bas au centre, au tour 10 ou 11 : termine ce tour puis passe au dernier tour sans actions d’équipage.",
"Lower white on turn 10 or 11: finish this turn, then skip to the final turn without crew actions.",
],
],
"special-ops": [
[
"Prépare votre prochain A, B ou combat : il sera héroïque.",
"Prepare your next A, B or battlebot action: it becomes heroic.",
],
[
"À combiner avec une autre carte : protège son exécution contre les retards directs, obstacles et effets subis pendant l’action.",
"Combine with another card: protect its execution from direct delays, obstacles and effects against you during the action.",
],
],
"squad-leader": [
[
"Robots actifs : répare un dégât dans votre zone, priorité aux armes. Robots désactivés : les réactive.",
"Active battlebots repair one damage in your zone, prioritizing weapons. Disabled battlebots are reactivated.",
],
[
"Avec des robots actifs, sauf en bas à droite : rejoint les intercepteurs et décolle. Déjà en vol : attaque héroïque.",
"With active battlebots, except in lower blue: reach the interceptors and launch. Already in space: heroic attack.",
],
],
mechanic: [
[
"Prépare l’arme locale : +1 force au prochain tir de laser, ou +1 portée pour l’impulsion.",
"Prepare the local weapon: +1 strength on its next laser shot, or +1 range for pulse.",
],
[
"Répare une panne A, B ou C de votre station de 2 points, priorité au plus petit numéro de menace.",
"Repair a local A, B or C malfunction by 2, prioritizing the lowest threat number.",
],
],
};
export function specialDescription(action, locale) {
const [, name, tier] = action.split(":");
return (
choose(specials[name]?.[tier === "advanced" ? 1 : 0], locale) ?? action
);
}
const traits = {
stealth: [
"Invisible jusqu’à X : les armes l’ignorent.",
"Untargetable until X: weapons ignore it.",
],
cryo: [
"Le cryobouclier absorbe la première salve, quelle que soit sa force.",
"Cryoshield absorbs the first volley regardless of strength.",
],
pulseBreaksShield: [
"Ignore ses boucliers si l’impulsion le touche ce tour.",
"Ignore its shields when pulse targets it this turn.",
],
noRockets: [
"Les roquettes ignorent cette menace.",
"Rockets ignore this threat.",
],
rocketImmune: [
"Attire les roquettes mais ne subit pas leurs dégâts.",
"Rockets can target it but deal no damage.",
],
noHeavy: [
"Les lasers lourds ignorent cette menace.",
"Heavy lasers ignore this threat.",
],
rocketMagnet: [
"Attire toutes les roquettes, même hors portée ; +1 bouclier après une roquette.",
"All rockets target it, even outside range; +1 shield after a rocket.",
],
behemoth: [
"Seule cible des intercepteurs : force 9, mais pilote assommé et robots désactivés.",
"Lone interceptor target: strength 9, but the pilot is knocked out and battlebots disabled.",
],
retaliates: [
"Après avoir reçu un dégât, attaque 1 sur chaque zone à la fin du calcul des dégâts.",
"After receiving damage, attack 1 on each zone at the end of damage calculation.",
],
deathSplash: [
"Détruite : inflige 1 dégât à toutes les autres menaces externes, sans bouclier.",
"Destroyed: deals 1 damage to every other external threat, ignoring shields.",
],
returnsFire: [
"Riposte : désactive les robots qui l’attaquent, sauf attaque héroïque.",
"Returns fire: disables attacking battlebots unless their attack is heroic.",
],
grows: [
"Après X, désactive les robots qui l’attaquent, sauf attaque héroïque.",
"After X, disables attacking battlebots unless their attack is heroic.",
],
rocketHp: [
"Autant de points de vie que de roquettes restantes à son apparition.",
"Hit points equal the rockets remaining when it appears.",
],
deathKnockout: [
"Réparation terminée : assomme les équipiers en bas dans les zones latérales.",
"Final repair knocks out crew in lower red and lower blue.",
],
deathKnocksAttacker: [
"Détruite : assomme son attaquant et désactive ses robots, même avec une attaque héroïque.",
"Destroyed: knocks out its attacker and disables battlebots, even after a heroic attack.",
],
removeTokenOnHit: [
"Chaque combat nettoie une station. La troisième station nettoyée nettoie aussi la dernière.",
"Each battlebot attack clears a station. Clearing the third also clears the last.",
],
slime: [
"Entrer retarde l’action suivante. Original : 2 vies ; chaque rejeton : 1 vie.",
"Entering delays the next action. Original: 2 hit points; each progeny: 1.",
],
rocketDeflects: [
"Une roquette la dévie : elle ne fera pas son attaque Z.",
"A rocket sends it off course: it will not perform its Z attack.",
],
megashield: [
"Chaque tour où elle est ciblée, perd 1 bouclier après les tirs.",
"Each turn it is targeted, loses 1 shield after damage.",
],
};
Object.assign(traits, {
phasing: [
"Alterne visible / déphasée. Déphasée : ne peut être touchée et utilise les effets entre crochets.",
"Alternates visible / phased out. While phased out, cannot be hit and uses bracketed effects.",
],
polarized: [
"Additionne les lasers, divise leur force par deux (arrondi supérieur), puis ajoute les autres armes avant les boucliers.",
"Add laser strength and halve it, rounding up; add other weapons before shields.",
],
spans: [
"Les lasers des trois zones peuvent la cibler. Une arme ne la touche qu’une fois par tour.",
"Lasers in all three zones can target it. Each weapon only hits it once per turn.",
],
web: [
"Ne dépasse pas Z. Si elle existe encore au saut, exécute son attaque Z.",
"Stops at Z. If still present at the jump, performs its Z attack.",
],
accelerates: [
"Gagne 1 vitesse après chaque étape d’action des menaces.",
"Gains 1 speed after each Threat Actions step.",
],
slowsWhenHit: [
"Vitesse 2 pour ce tour si les tirs lui infligent des dégâts ; sinon vitesse 4.",
"Speed 2 this turn if weapon fire deals damage; otherwise speed 4.",
],
energyHeal: [
"L’énergie absorbée par les boucliers du vaisseau pendant ses attaques lui rend autant de vies.",
"Energy absorbed by ship shields during its attacks heals it by that amount.",
],
finishEnergy: [
"La dernière réparation consomme 1 énergie du réacteur local ; impossible si ce réacteur est vide.",
"The final repair consumes 1 local reactor energy; it cannot finish with an empty reactor.",
],
parityStation: [
"Station initiale : rouge supérieur sur un numéro impair, bleu supérieur sur un numéro pair.",
"Starts in upper red on an odd threat number, upper blue on an even number.",
],
shortCircuit: [
"Bloque l’impulsion. Chaque tir du laser lourd central provoque une attaque 1 sur chaque zone.",
"Blocks pulse. Every central heavy-laser shot triggers an attack 1 on every zone.",
],
poison: [
"Dès son apparition, le Ninja empoisonne les mouvements commençant ou finissant en bleu supérieur ou blanc inférieur. Après sa destruction, seuls les déjà empoisonnés restent menacés jusqu’à Z.",
"From appearance, Ninja poisons movements starting or ending in upper blue or lower white. After destruction, only already-poisoned crew remain threatened until Z.",
],
infection: [
"Les infections déjà transmises restent actives jusqu’à Z, même après sa destruction.",
"Existing infections persist until Z, even after its destruction.",
],
swapDeckOnHit: [
"Chaque action qui l’endommage échange le pont des équipiers à bord.",
"Whenever damaged, all crew aboard change decks.",
],
vortex: [
"À Z, une menace interne commune surprise résout toutes ses actions.",
"At Z, a surprise common internal threat resolves all its actions.",
],
teleportsOnHit: [
"Après un dégât, se téléporte en rouge supérieur.",
"After taking damage, teleports to upper red.",
],
gremlin: [
"Si non détruit avant le saut, assomme tout l’équipage. Les systèmes sabotés se réparent séparément.",
"If not destroyed before the jump, knocks out all crew. Sabotaged systems are repaired separately.",
],
parasite: [
"S’attache au premier équipier qui se déplace, puis le suit. Seul un autre équipier peut le combattre. L’hôte est assommé à sa destruction ; s’il est assommé avant, la menace survit.",
"Attaches to the first crew member who moves, then follows them. Only another crew member can attack it. Destroying it knocks out its host; if the host is knocked out earlier, the threat survives.",
],
});
export function traitDescriptions(th, locale) {
const result = Object.entries(traits)
.filter(([key]) => th[key])
.map(([, v]) => choose(v, locale));
const t = (fr, en) => (locale === "fr" ? fr : en);
if (th.maxTargetRange)
result.push(
t(
`Ciblable uniquement à portée ${th.maxTargetRange} ou moins.`,
`Targetable only at range ${th.maxTargetRange} or less.`,
),
);
if (th.damageCap)
result.push(
t(
`Au plus ${th.damageCap} dégât(s) de tirs par tour.`,
`At most ${th.damageCap} weapon damage per turn.`,
),
);
if (th.asteroid)
result.push(
t(
`Détruit : attaque de force ${th.asteroid} par X/Y déjà franchi.`,
`Destroyed: attack strength ${th.asteroid} per X/Y already crossed.`,
),
);
if (th.simultaneousRepairs)
result.push(
t(
`Nécessite ${th.simultaneousRepairs} réparateurs différents au même tour.`,
`Requires ${th.simultaneousRepairs} different repairers in the same turn.`,
),
);
if (th.multiRepairBonus)
result.push(
t(
`+${th.multiRepairBonus} réparation si toutes ses stations sont réparées au même tour.`,
`+${th.multiRepairBonus} repair if all its stations are repaired in the same turn.`,
),
);
if (th.carrier)
result.push(
t(
`Intercepteurs à sa portée ou plus près : ses attaques perdent ${th.carrier} force.`,
`Interceptors in its range or closer reduce its attacks by ${th.carrier}.`,
),
);
if (th.inaccessibility)
result.push(
t(
`Absorbe les ${th.inaccessibility} premiers dégâts de chaque tour.`,
`Absorbs the first ${th.inaccessibility} damage each turn.`,
),
);
if (th.loneRepair)
result.push(
t(
`Un seul réparateur ce tour : +${th.loneRepair} réparation.`,
`Exactly one repairer this turn: +${th.loneRepair} repair.`,
),
);
if (th.botsRepairBonus)
result.push(
t(
`Avec des robots actifs : +${th.botsRepairBonus} réparation.`,
`With active battlebots: +${th.botsRepairBonus} repair.`,
),
);
return result;
}
const dictionary = {
red: ["rouge", "red"],
white: ["blanc", "white"],
blue: ["bleu", "blue"],
shield: ["bouclier", "shield"],
reactor: ["réacteur", "reactor"],
speed: ["vitesse", "speed"],
fragments: ["fragments", "fragments"],
half: [
"la moitié des dégâts, arrondie vers le bas",
"half the damage, rounded down",
],
hp: ["vies restantes", "remaining hit points"],
"double-hp": ["2 × vies restantes", "2 × remaining hit points"],
"triple-hp": ["3 × vies restantes", "3 × remaining hit points"],
crew: ["équipiers présents", "crew present"],
all: ["toutes zones", "all zones"],
other: ["autres zones", "other zones"],
lateral: ["zones latérales", "side zones"],
occupied: ["chaque zone occupée", "each occupied zone"],
stations: ["chaque station occupée", "each occupied station"],
station: ["dans ses stations", "in its stations"],
zone: ["dans sa zone", "in its zone"],
"active-bots": ["menant des robots actifs", "leading active battlebots"],
"without-bots": [
"dans sa station sans robots actifs",
"in its station without active battlebots",
],
"except-bridge": ["hors de la passerelle", "outside the bridge"],
lift: ["change de pont", "change deck"],
double: ["dégâts doublés après bouclier", "double damage after shields"],
plasma: [
"plasma : assomme si aucun dégât absorbé",
"plasma: knockout if no damage absorbed",
],
"ignore-shield": ["ignore les boucliers", "ignore shields"],
revealed: ["devient ciblable", "becomes targetable"],
grown: ["croît : riposte activée", "grows: returns fire"],
"attack-aura": [
"+1 attaque aux autres menaces externes jusqu’à sa destruction",
"+1 attack to other external threats until destroyed",
],
"shield-aura": [
"+1 bouclier à toutes les menaces externes jusqu’à sa destruction",
"+1 shield to all external threats until destroyed",
],
"double-red": [
"double les dégâts à la zone rouge",
"double damage to red zone",
],
"double-all": [
"double les dégâts à toutes les zones",
"double damage to all zones",
],
"lethal-entry": [
"entrer dans une station contaminée assomme",
"entering a contaminated station causes knockout",
],
"already-fired": ["arme déjà utilisée", "weapon already fired"],
"no-energy": ["réacteur vide", "empty reactor"],
"no-fuel": ["plus de combustible", "no fuel"],
"irreparable-system": [
"système irréparable ou dernière réparation à distance impossible",
"system irreparable or remote final repair prohibited",
],
"rocket-unavailable": [
"roquette indisponible ou déjà lancée ce tour",
"no rocket available or already launched this turn",
],
"linked-weapons-unavailable": [
"les deux armes ne peuvent pas tirer ensemble",
"both linked weapons cannot fire",
],
"ultrafast-return": ["retour ultrarapide", "ultrafast return"],
"upper-weapon": ["arme supérieure", "upper weapon"],
"lower-weapon": ["arme inférieure", "lower weapon"],
structure: ["structure", "structure"],
};
Object.assign(dictionary, {
inaccessibility: ["inaccessibilité", "inaccessibility"],
direct: ["dégâts directs", "direct damage"],
shielded: ["boucliers applicables", "shields apply"],
"reactor+1": ["énergie du réacteur + 1", "reactor energy + 1"],
alone: ["seuls dans leur station", "alone in their station"],
group: [
"au moins deux dans leur station",
"sharing their station with another crew member",
],
"reverse-shields": [
"les prochains tirs absorbent l’énergie des boucliers et l’ajoutent aux dégâts",
"subsequent attacks drain shields and add that energy to damage",
],
"ignore-shields": [
"les prochains tirs ignorent les boucliers",
"subsequent attacks ignore shields",
],
"poison-entry": [
"empoisonne ceux qui commencent ou terminent un déplacement en bleu supérieur ou blanc inférieur",
"poisons crew starting or ending a movement in upper blue or lower white",
],
"sealed-red": [
"portes vers la zone rouge scellées",
"doors to red zone sealed",
],
"sealed-blue": [
"portes vers la zone bleue scellées",
"doors to blue zone sealed",
],
"sealed-door": ["porte scellée", "sealed door"],
"cyber-gremlin": [
"Cyber Gremlin encore présent au saut",
"Cyber Gremlin still present at jump",
],
});
function word(x, locale) {
return choose(dictionary[x], locale) ?? String(x ?? "");
}
function station(x, locale) {
if (!x) return "";
const [z, d] = x.split("-");
return `${word(z, locale)} ${d === "upper" ? "↑" : "↓"}`;
}
export function effectDescription(e, locale) {
const t = (fr, en) => (locale === "fr" ? fr : en),
w = (x) => word(x, locale);
let text;
switch (e.type) {
case "attack":
text = `${t("Attaque", "Attack")} ${w(e.amount)}${e.zones && e.zones !== "own" ? " · " + w(e.zones) : ""}${e.mode && e.mode !== "normal" ? " · " + w(e.mode) : ""}`;
break;
case "heal":
text = `${t("Répare", "Heal")} ${w(e.amount)}`;
break;
case "change":
text = `${w(e.stat)} ${e.amount >= 0 ? "+" : ""}${e.amount}`;
break;
case "set":
text = `${w(e.stat)} = ${e.amount}`;
break;
case "flag":
text = w(e.name);
break;
case "drain":
text = `${t("Retire", "Drain")} ${e.amount ?? t("toute l’énergie", "all energy")} · ${w(e.system)}${e.zones ? " · " + w(e.zones) : ""}`;
break;
case "move":
text = `${t("Se déplace", "Move")} ${w(e.direction)}`;
break;
case "drain-or-damage":
text = t(
"Retire 1 énergie du réacteur, ou inflige 1 dégât s’il est vide.",
"Drain 1 reactor energy, or deal 1 damage if it is empty.",
);
break;
case "knockout":
text = `${t("Assomme les équipiers", "Knock out crew")} ${w(e.scope)}`;
break;
case "delay":
text = `${t("Retarde les équipiers", "Delay crew")} ${w(e.scope)}`;
break;
case "slime-spread":
text = t(
"Chaque Slime se propage d’une station vers le côté opposé.",
"Each Slime spreads one station toward the opposite side.",
);
break;
case "remove-rocket":
text = t(
"Détruit une roquette en réserve.",
"Destroy one stored rocket.",
);
break;
case "disable-stored-bots":
text = t(
"Désactive les robots en réserve en bas à gauche.",
"Disable stored battlebots in lower red.",
);
break;
case "fuel-lost":
text = t(
"Détruit une capsule de combustible.",
"Destroy one fuel capsule.",
);
break;
case "self-damage":
text = t(`Reçoit ${e.amount} dégât(s).`, `Take ${e.amount} damage.`);
break;
case "seek":
text = t(
"Va dans la station adjacente avec le plus d’équipiers ; ne bouge pas en cas d’égalité.",
"Move to the adjacent station with most crew; stay on a tie.",
);
break;
case "advance-others":
if (e.position === "internal") {
text = t(
"Avance les autres menaces internes d’une case, avec les effets franchis.",
"Advance other internal threats one space, executing crossed effects.",
);
break;
}
text = t(
"Avance les autres menaces externes d’une case, en exécutant les effets franchis.",
"Advance other external threats one space, executing crossed effects.",
);
break;
case "destroy-ship":
text = t("Détruit le vaisseau.", "Destroy the ship.");
break;
case "fill-shield":
text = t(
"Remplit son bouclier depuis son réacteur.",
"Fill its shield from its reactor.",
);
break;
case "leak":
text = t(
`Vide ${w(e.system)} et inflige autant de dégâts${e.zones ? " · " + w(e.zones) : ""}.`,
`Empty ${w(e.system)} and deal that much damage${e.zones ? " · " + w(e.zones) : ""}.`,
);
break;
case "jump":
text = t(
`Saute vers la trajectoire à ${e.direction === "left" ? "gauche" : "droite"}, à distance égale (sans place : reste).`,
`Jump to the ${e.direction} trajectory at the same distance, if space exists.`,
);
break;
case "call":
text = t(
`Fait apparaître son renfort ${e.position === "internal" ? "interne" : "externe"}${e.zone && e.zone !== "internal" ? " · " + (e.zone === "own" ? "même zone" : w(e.zone)) : ""}.`,
`Spawn the assigned ${e.position} reinforcement${e.zone && e.zone !== "internal" ? " · " + (e.zone === "own" ? "same zone" : w(e.zone)) : ""}.`,
);
if (e.undamagedSpeed)
text += t(
" Moins de 2 dégâts : vitesse du renfort +1.",
"If fewer than 2 damage: reinforcement speed +1.",
);
break;
case "heal-others":
text = t(
`Répare ${e.amount} dégât de toutes les menaces ${e.position === "internal" ? "internes" : "externes"}.`,
`Heal ${e.amount} damage from all ${e.position} threats.`,
);
break;
case "knockout-delay":
text = t(
"Assomme les équipiers menant des robots actifs ; retarde les autres.",
"Knock out crew leading active battlebots; delay the rest.",
);
break;
case "advance-zone":
text = t(
`Avance les menaces de la zone ${w(e.zone)} de ${e.amount} cases, avec les effets franchis.`,
`Advance ${w(e.zone)} zone threats by ${e.amount}, executing crossed effects.`,
);
break;
case "opposite-damage":
text = t(
`Inflige ${e.amount} dégât à l’autre zone latérale.`,
`Deal ${e.amount} damage to the opposite side zone.`,
);
break;
case "short-circuit":
text = t(
`Consomme 1 ${e.resource === "fuel" ? "capsule" : "énergie centrale"} pour attaquer chaque zone de force 1.`,
`Consume 1 ${e.resource === "fuel" ? "fuel capsule" : "central reactor energy"} to attack each zone for 1.`,
);
break;
case "drill-move":
text = t(
"Avance d’une station vers la zone la plus endommagée ; égalité : vers le blanc.",
"Move one station toward the most damaged zone; ties: toward white.",
);
break;
case "shambler":
text = t(
"Avec un équipier : 2 dégâts à la zone. Sinon : récupère 1 vie.",
"Crew present: deal 2 zone damage. Otherwise heal 1.",
);
break;
case "blind":
text = t(
`Obstrue la visée ${e.zone === "lateral" ? "d’une zone latérale" : "du blanc"}. Observation ou intercepteurs requis pour y tirer au laser.`,
`Obscure ${e.zone === "lateral" ? "a side zone" : "white"} targeting. Visual confirmation or interceptors are required for laser fire there.`,
);
break;
case "mine":
text = t(
"Pose une mine dans sa station.",
"Place a mine in its station.",
);
break;
case "detonate-mines":
text = t(
"Chaque mine inflige 2 dégâts à sa zone.",
"Each mine deals 2 damage to its zone.",
);
break;
case "infect":
text = t(
"Infecte tous les équipiers de sa station.",
"Infect all crew in its station.",
);
break;
case "infection-detonate":
text = t(
"Chaque infecté conscient à bord inflige 2 dégâts à sa zone.",
"Each conscious infected crew member aboard deals 2 damage to their zone.",
);
break;
case "poison-detonate":
text = t(
"Assomme les empoisonnés. Si le Ninja vit encore : chaque roquette restante provoque une attaque 2 en rouge, puis est détruite.",
"Knock out poisoned crew. If Ninja is still alive, each remaining rocket causes an attack 2 on red, then is destroyed.",
);
break;
case "repeat-action":
text = t(
"Répète les actions du tour courant au prochain tour, en décalant les programmes.",
"Repeat this turn’s actions next turn, delaying the programs.",
);
break;
case "swap-zones":
text = t(
"Les équipiers en zones latérales échangent rouge / bleu, sans changer de pont.",
"Crew in side zones swap red / blue without changing deck.",
);
break;
case "vortex-draw":
text = t(
"Révèle la menace surprise ; résout son apparition puis X, Y et Z.",
"Reveal the surprise threat; resolve its appearance, X, Y and Z.",
);
break;
case "absorb-reactor":
text = t(
"Vide le réacteur local et gagne autant de vitesse.",
"Empty the local reactor and gain that much speed.",
);
break;
case "sabotage":
text = t(
"Sabote les systèmes A, B et C de sa station ; chacun nécessite une réparation.",
"Sabotage A, B and C in its station; each needs one repair.",
);
break;
case "parasite-drain":
text = t(
"Retire 1 énergie du système B de la station de l’hôte.",
"Drain 1 energy from the host station’s B system.",
);
break;
case "parasite-knockout":
text = t(
"Assomme les autres équipiers avec l’hôte.",
"Knock out other crew sharing the host’s station.",
);
break;
case "parasite-attack":
text = t(
"5 dégâts directs dans la zone de l’hôte ; hôte en vol : attaque 5 en blanc.",
"5 direct damage to the host’s zone; host in space: attack 5 on white.",
);
break;
default:
text = e.type;
}
if (e.phasedAmount !== undefined)
text += t(
` [déphasée : ${e.phasedAmount}]`,
` [phased out: ${e.phasedAmount}]`,
);
if (e.phasedDirection)
text += t(
` [déphasée : ${w(e.phasedDirection)}]`,
` [phased out: ${w(e.phasedDirection)}]`,
);
if (e.onlyPhasedIn)
text += t(" (uniquement visible)", " (only when visible)");
if (e.ifCrew)
text += t(" (si un équipier est présent)", " (if crew is present)");
if (e.ifDamaged) text += t(" (si endommagée)", " (if damaged)");
if (e.ifUndamaged) text += t(" (si intacte)", " (if undamaged)");
if (e.belowDamage !== undefined)
text += t(
` (si moins de ${e.belowDamage} dégâts)`,
` (if fewer than ${e.belowDamage} damage)`,
);
if (e.unlessFlag) text += t(" (sauf si déviée)", " (unless off course)");
return text;
}
export function eventDescription(e, locale, threats) {
const t = (fr, en) => (locale === "fr" ? fr : en),
w = (x) => word(x, locale);
const prefix =
e.crew !== undefined ? `${t("Équipier", "Crew")} ${e.crew + 1} · ` : "";
const found = threats.find((t) => t.instance === e.threat);
const threat = found?.card?.name ?? found?.name ?? e.threat;
const messages = {
"threat-called": t("Renfort appelé", "Reinforcement called"),
"threat-jump": t(
`Change de trajectoire → ${w(e.zone)}`,
`Change trajectory → ${w(e.zone)}`,
),
"parasite-attached": t("Parasite attaché", "Parasite attached"),
"threat-appears": t("Menace détectée", "Threat appears"),
"threat-destroyed": t("Menace détruite", "Threat destroyed"),
"threat-survived": t("Menace échappée", "Threat survived"),
"threat-action": t(`Action ${e.mark}`, `Action ${e.mark}`),
"threat-hit": t(
`${e.damage} dégât(s), après ${e.shield} bouclier(s)`,
`${e.damage} damage after ${e.shield} shields`,
),
"cryoshield-broken": t("Cryobouclier détruit", "Cryoshield broken"),
move: t(
`${station(e.from, locale)} → ${station(e.to, locale)}`,
`${station(e.from, locale)} → ${station(e.to, locale)}`,
),
teleport: t(
`Téléportation → ${station(e.to, locale)}`,
`Teleport → ${station(e.to, locale)}`,
),
fire: t(
`Tir ${station(e.station, locale)}, force ${e.strength}, portée ${e.range}`,
`Fire ${station(e.station, locale)}, strength ${e.strength}, range ${e.range}`,
),
energy: t(
`Transfert de ${e.amount} énergie · ${station(e.station, locale)} · ${w(e.system)}`,
`Transfer ${e.amount} energy · ${station(e.station, locale)} · ${w(e.system)}`,
),
computer: t(
`Ordinateur entretenu · phase ${e.phase}`,
`Computer maintained · phase ${e.phase}`,
),
"computer-missed": t(
`Ordinateur oublié · phase ${e.phase}`,
`Computer missed · phase ${e.phase}`,
),
"rocket-launched": t(
`${e.count} roquette(s) lancée(s)`,
`${e.count} rocket(s) launched`,
),
"launch-interceptors": t(
"Décollage des intercepteurs",
"Interceptor launch",
),
"bots-activated": t("Robots activés", "Battlebots activated"),
"bots-reactivated": t("Robots réactivés", "Battlebots reactivated"),
"battlebots-hit": t(
`Attaque des robots : ${e.amount ?? 1} dégât(s)`,
`Battlebot attack: ${e.amount ?? 1} damage`,
),
repair: t(`Répare ${e.amount} dégât(s)`, `Repair ${e.amount} damage`),
"repair-attempt": t(
"Réparation simultanée tentée",
"Simultaneous repair attempted",
),
"hull-repaired": t(
`Répare ${w(e.tile)} · ${w(e.zone)}`,
`Repair ${w(e.tile)} · ${w(e.zone)}`,
),
delay: t(
`Programme décalé à partir de T+${e.from}${e.dropped ? " ; dernière action perdue" : ""}`,
`Program delayed from T+${e.from}${e.dropped ? "; final action lost" : ""}`,
),
"knocked-out": t(
`Assommé · ${w(e.reason)}`,
`Knocked out · ${w(e.reason)}`,
),
ineffective: t(`Sans effet · ${w(e.reason)}`, `No effect · ${w(e.reason)}`),
"ship-damage": t(
`Dégât ${w(e.zone)} · ${w(e.tile)}`,
`Damage ${w(e.zone)} · ${w(e.tile)}`,
),
"ship-destroyed": t("Vaisseau détruit", "Ship destroyed"),
attack: t(
`Attaque ${w(e.zone)} : ${e.absorbed} absorbé(s), ${e.damage} restant(s)`,
`Attack ${w(e.zone)}: ${e.absorbed} absorbed, ${e.damage} remaining`,
),
specialization: specialDescription(`special:${e.name}:${e.tier}`, locale),
};
return (
prefix +
(messages[e.type] ?? e.type) +
(threat !== undefined ? " · " + threat : "")
);
}

View file

@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Extract factual component counts from the audited BGG workbook; no macros execute."""
import collections
import hashlib
import json
from pathlib import Path
import sys
import xml.etree.ElementTree as ET
from zipfile import ZipFile
source = Path(sys.argv[1])
assert hashlib.sha256(source.read_bytes()).hexdigest() == '3fb17351f46fd278962d4d02c3ade38e0a39c72c83f8951118dc8ee441d2e86c', 'Unknown workbook revision'
ns = {'x': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
symbols = {'A':'A','B':'B','C':'C','Battlebots':'bots','Left':'red','Right':'blue','Gravolift':'lift'}
counts = collections.Counter()
with ZipFile(source) as z:
strings = [''.join(s.itertext()) for s in ET.fromstring(z.read('xl/sharedStrings.xml'))]
rows = ET.fromstring(z.read('xl/worksheets/sheet1.xml')).findall('x:sheetData/x:row', ns)
for row in rows[1:]:
cells = []
for c in row.findall('x:c',ns):
v = c.findtext('x:v',namespaces=ns)
cells.append(strings[int(v)] if c.get('t')=='s' else int(v))
a,b,c,n = cells
assert n in (1,2)
counts[(symbols[a],symbols[b],symbols[c])] += n
assert sum(counts.values()) == 90
result = [{'sides':[[a,b],[c]],'count':n} for (a,b,c),n in counts.items()]
target = Path(__file__).resolve().parents[1] / 'src/game/double-deck.json'
target.write_text(json.dumps(result,indent=2)+'\n')
print(f'{len(result)} distinct cards, {sum(counts.values())} physical cards')

148
src/game/campaign.js Normal file
View file

@ -0,0 +1,148 @@
// Base rules §6. All transitions are pure; the host persists the returned state.
const check = (condition, message) => {
if (!condition) throw Error(message);
};
export function createCampaign(id, limit = 3) {
check(typeof id === "string" && id.length > 0, "Campaign ID required");
check(
Number.isInteger(limit) && limit >= 1 && limit <= 5,
"Choose one to five missions",
);
return {
id,
limit,
missions: [],
stage: "flying",
votes: [],
repairs: [],
repairCursor: 0,
carried: null,
usedThreats: [],
outcome: null,
};
}
export function recordMission(campaign, resolution, metadata = {}) {
const c = structuredClone(campaign);
if (c.stage !== "flying") return c;
check(resolution.outcome, "Resolve the mission first");
const { ship, outcome } = resolution;
c.missions.push({
result: structuredClone(outcome),
metadata: structuredClone(metadata),
});
c.lastShip = structuredClone(ship);
c.usedThreats = [
...new Set([
...c.usedThreats,
...resolution.threats
.filter(
(t) => ["destroyed", "survived"].includes(t.status) && !t.sabotage,
)
.map((t) => t.id),
]),
];
if (!outcome.survived || c.missions.length === c.limit) finish(c);
else {
c.stage = "decision";
c.votes = [];
}
return c;
}
function finish(c) {
const survived = c.missions.every((m) => m.result.survived),
last = c.missions.at(-1).result;
const threats = c.missions.reduce((n, m) => n + m.result.threatPoints, 0),
visual = Math.floor(
c.missions.reduce((n, m) => n + m.result.visual, 0) / c.missions.length,
),
bonus = c.missions.reduce((n, m) => n + m.result.bonus, 0);
c.outcome = {
survived,
score: survived ? threats + visual + bonus - last.penalties : 0,
threatPoints: threats,
visual,
bonus,
penalties: last.penalties,
};
c.stage = "complete";
}
export function voteCampaign(campaign, seat, continueCampaign, humans) {
const c = structuredClone(campaign);
check(c.stage === "decision", "Campaign is not awaiting a decision");
check(Number.isInteger(seat) && seat >= 0 && seat < humans, "Unknown player");
check(typeof continueCampaign === "boolean", "Choose continue or return");
if (!continueCampaign) {
finish(c);
return c;
}
if (!c.votes.includes(seat)) c.votes.push(seat);
if (c.votes.length === humans) {
c.stage = "repairs";
c.repairs = [];
c.repairCursor = 0;
c.repairedZones = { red: 0, white: 0, blue: 0 };
c.carried = {
zones: Object.fromEntries(
Object.entries(c.lastShip.zones).map(([z, s]) => [z, [...s.damage]]),
),
disabledBots: c.lastShip.bots.map((b) => !!b.disabled),
botStation: null,
};
skipUnconscious(c);
}
return c;
}
function skipUnconscious(c) {
while (c.lastShip.crew[c.repairCursor]?.knockedOut) {
c.repairs.push({ crew: c.repairCursor, type: "recover" });
c.repairCursor++;
}
if (c.repairCursor === c.lastShip.crew.length) c.stage = "ready";
}
export function repairCampaign(campaign, choice) {
const c = structuredClone(campaign);
check(c.stage === "repairs", "Campaign is not awaiting repairs");
check(
choice.crew === c.repairCursor,
"Repair in crew order, starting with the captain",
);
const { zone, tile, bot, skip } = choice;
if (skip)
check(
zone === undefined && tile === undefined && bot === undefined,
"Choose a single repair",
);
else if (bot !== undefined) {
check(
zone === undefined &&
tile === undefined &&
Number.isInteger(bot) &&
c.carried.disabledBots[bot] === true,
"Choose a disabled squad",
);
c.carried.disabledBots[bot] = false;
} else {
check(
c.carried.zones[zone]?.includes(tile),
"Choose an existing damage tile",
);
check(c.repairedZones[zone] < 2, "At most two hull repairs per zone");
c.carried.zones[zone] = c.carried.zones[zone].filter((t) => t !== tile);
c.repairedZones[zone]++;
}
c.repairs.push(structuredClone(choice));
c.repairCursor++;
skipUnconscious(c);
return c;
}
export function departCampaign(campaign, botStation = "red-lower") {
const c = structuredClone(campaign);
check(c.stage === "ready", "Finish all repairs before departure");
check(
["red-lower", "blue-upper"].includes(botStation),
"Invalid battlebot station",
);
c.carried.botStation = botStation;
c.stage = "flying";
return c;
}

79
src/game/cards.js Normal file
View file

@ -0,0 +1,79 @@
import doubleCounts from "./double-deck.json" with { type: "json" };
export function doubleDeck() {
return doubleCounts.flatMap(({ sides, count }, index) =>
Array.from({ length: count }, (_, copy) => ({
id: `double-${index}-${copy}`,
kind: "normal",
sides: structuredClone(sides),
})),
);
}
export const PHASE_TURNS = [
[1, 3],
[4, 7],
[8, 12],
];
export const phaseForTurn = (turn) => (turn <= 3 ? 1 : turn <= 7 ? 2 : 3);
export const SPECIALIZATIONS = [
"rocketeer",
"data-analyst",
"energy-technician",
"pulse-gunner",
"medic",
"teleporter",
"hypernavigator",
"special-ops",
"squad-leader",
"mechanic",
];
// Component counts independently agree in the BGG component inventory and the
// original SpaceAlertWeb inventory. See docs/components.md for provenance.
export function baseDeck() {
return ["red", "blue", "lift"].flatMap((movement) =>
Object.entries({ A: 10, B: 8, C: 7, bots: 5 }).flatMap(([action, count]) =>
Array.from({ length: count }, (_, n) => ({
id: `${action}-${movement}-${n}`,
kind: "normal",
sides: [[action], [movement]],
})),
),
);
}
export function heroicDeck() {
return [
["A", "blue-lower"],
["A", "red-lower"],
["B", "blue-upper"],
["B", "red-upper"],
["bots", "white-lower"],
["bots", "white-upper"],
].map(([action, station], n) => ({
id: `hero-${n}`,
kind: "heroic",
sides: [[`hero:${action}`], [`teleport:${station}`]],
}));
}
export function specializationCards(name, level, owner) {
if (!SPECIALIZATIONS.includes(name) || ![1, 2, 3].includes(level))
throw Error("Invalid specialization");
const card = (tier) => ({
id: `special-${owner}-${tier}`,
owner,
kind: "special",
sides:
tier === 1
? [[`special:${name}:basic`]]
: [[`special:${name}:advanced`], [`special:${name}:basic`]],
});
return level === 1 ? [card(1)] : level === 2 ? [card(2)] : [card(1), card(2)];
}
export function cardBack(card, side) {
const actions = card.sides[side];
return {
kind: card.kind,
category: /^(red|blue|lift|teleport:)/.test(actions[0])
? "movement"
: "action",
double: actions.length === 2,
};
}

506
src/game/career.js Normal file
View file

@ -0,0 +1,506 @@
// New Frontier experience rules and official explorer sheet. See docs/components.md.
import { SPECIALIZATIONS } from "./cards.js";
const check = (condition, message) => {
if (!condition) throw Error(message);
};
export const LEVEL_BOXES = Array.from(
{ length: 30 },
(_, level) => 8 + 4 * level,
);
export const HARDCORE_SKIPS = Array.from({ length: 30 }, (_, level) =>
level < 2 ? 0 : level < 7 ? 3 * level - 2 : 4 + 2 * level,
);
export function createExplorer(id, name, cloning = true) {
check(
typeof id === "string" &&
id &&
typeof name === "string" &&
name.trim() &&
name.length <= 80,
"Invalid explorer",
);
return {
id,
name: name.trim(),
cloning: !!cloning,
dead: false,
level: 0,
boxes: 0,
xp: 0,
clones: 0,
specializations: {},
achievements: [],
runs: [],
activeRun: null,
};
}
export function experienceFor(score, count = 1, limit = 3) {
check(
Number.isFinite(score) &&
Number.isInteger(count) &&
count >= 1 &&
count <= limit,
"Invalid mission result",
);
return (
(count === 1 ? 2 : count === limit ? 4 * count : 4 * count - 2) +
Math.floor(Math.max(0, score) / 10)
);
}
function gain(e, amount) {
e.xp += amount;
while (amount > 0 && e.level < 30) {
// Dotted boxes count as skipped only when a following blank is actually filled.
const skip = e.cloning ? 0 : Math.max(0, HARDCORE_SKIPS[e.level] - e.boxes);
e.boxes += skip + 1;
amount--;
if (e.boxes === LEVEL_BOXES[e.level]) {
e.level++;
e.boxes = 0;
}
}
}
export function startExplorer(input, runId) {
const e = structuredClone(input);
check(!e.dead, "This explorer died");
check(!e.activeRun, "Explorer is already on a mission");
check(
e.runs.every((r) => r.id !== runId),
"Run already recorded",
);
check(
Object.values(e.specializations).reduce((a, b) => a + b, 0) === e.level,
"Choose earned specialization levels before departure",
);
e.activeRun = runId;
return e;
}
export function settleExplorer(input, result) {
const e = structuredClone(input);
if (e.runs.some((r) => r.id === result.id)) return e;
check(e.activeRun === result.id, "Result does not match the active mission");
e.activeRun = null;
const r = structuredClone(result);
r.startLevel = e.level;
r.achievements = [];
r.xp = 0;
if (!r.training) {
if (r.survived) {
r.xp = experienceFor(r.score, r.count ?? 1, r.limit ?? 3);
gain(e, r.xp);
} else if (e.cloning) e.clones++;
else e.dead = true;
}
e.runs.push(r);
return e;
}
export function cancelExplorer(input, runId) {
const e = structuredClone(input);
check(e.activeRun === runId, "Wrong active run");
e.activeRun = null;
return e;
}
export function consentToCloning(input) {
const e = structuredClone(input);
check(
!e.activeRun && !e.dead,
"Change cloning consent between missions or campaigns",
);
e.cloning = true;
return e;
}
export function learnSpecialization(input, name) {
const e = structuredClone(input);
check(!e.activeRun && !e.dead, "Learn between missions");
check(SPECIALIZATIONS.includes(name), "Unknown specialization");
const spent = Object.values(e.specializations).reduce((a, b) => a + b, 0),
level = (e.specializations[name] ?? 0) + 1;
check(spent < e.level, "No unspent specialization level");
const earnedAt = spent + 1;
check(
level <= 3 && (level < 2 || earnedAt >= 3) && (level < 3 || earnedAt >= 6),
"This specialization level is not available yet",
);
e.specializations[name] = level;
return e;
}
export const ACHIEVEMENTS = [];
const slug = (s) =>
s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
function add(category, name, xp, minLevel = 0, requirements = {}) {
ACHIEVEMENTS.push({
id: slug(name),
name,
category,
xp,
minLevel,
...requirements,
});
}
const pools = ["white-yellow", "yellow", "yellow-red", "red", "all"];
for (const [i, name] of [
"Lone Wolf",
"Dynamic Duo",
"Three Musketeers",
"Fantastic Four",
"Take Five",
].entries())
add("missions", name, 3, 0, { humans: i + 1 });
add("missions", "Fifth Wheel", 3, 0, { humans: 4, crew: 5 });
add("missions", "D’Artagnan Missing", 5, 0, { humans: 3, crew: 3 });
for (const [i, name] of [
"Scrambled Alert",
"Yellow Alert",
"Orange Alert",
"Red Alert",
"Random Alert",
].entries())
add("missions", name, [3, 5, 7, 9, 6][i], [0, 0, 0, 2, 2][i], {
pool: pools[i],
});
add("missions", "Double Trouble", 2, 0, { double: true, easyAllowed: true });
for (const [i, name] of [
"Double Solo",
"Double Duo",
"Double Trio",
"Double Quartet",
"Double Quintet",
].entries())
add("missions", name, 4, 0, { double: true, humans: i + 1 });
for (const [i, name] of [
"Double Scramble",
"Double Yellow",
"Double Orange",
"Double Red",
"Double Random",
].entries())
add("missions", name, [5, 7, 9, 11, 8][i], [0, 2, 2, 5, 2][i], {
double: true,
pool: pools[i],
});
for (const [i, name] of [
"Not Even a Scratch",
"Clean as a Whistle",
"Spotless",
"Flawless",
"Peerless",
"Favored by Fortune",
].entries())
add("missions", name, [3, 6, 9, 12, 15, 10][i], [0, 2, 2, 2, 5, 5][i], {
perfect: true,
...(i ? { pool: pools[i - 1] } : {}),
});
for (const [i, name] of [
"Perfect Double",
"Clean as Two Whistles",
"Doubly Spotless",
"Doubly Flawless",
"Doubly Peerless",
"Doubly Fortunate",
].entries())
add("missions", name, [4, 8, 12, 16, 20, 13][i], [2, 2, 5, 5, 5, 5][i], {
perfect: true,
double: true,
...(i ? { pool: pools[i - 1] } : {}),
});
for (const [name, requirements] of [
["Robinson Crusoe", { humans: 1 }],
["... and Friday", { humans: 2 }],
["Honeymoon", { humans: 2, judged: true }],
["Tour", { minimumHumans: 3 }],
["Transgalactic Tour", { minimumMissions: 5 }],
])
add(
"campaigns",
name,
6,
name === "Transgalactic Tour" ? 5 : 2,
requirements,
);
for (const [name, requirements] of [
["Double Crusoe", { humans: 1 }],
["Double Friday", { humans: 2 }],
["Double Tour", { minimumHumans: 3 }],
])
add("campaigns", name, 9, 2, { double: true, ...requirements });
for (const [i, name] of [
"Cracked",
"Loony",
"Crazy",
"Insane",
"Psychedelic",
].entries())
add(
"campaigns",
name,
[8, 12, 16, 20, 13][i],
[2, 2, 5, 5, 5][i],
i === 4 ? { differentPools: true } : { pool: pools[i] },
);
for (const [i, name] of [
"Scramble Challenge",
"Rainbow Challenge",
"Orange Challenge",
].entries())
add("campaigns", name, [10, 15, 20][i], [2, 5, 5][i], {
double: true,
pool: ["white-yellow", "all", "yellow-red"][i],
});
for (const [i, name] of [
"Not Going to Happen",
"Forget This",
"Not Possible",
"Beyond Impossible",
"Are you serious?",
].entries())
add("campaigns", name, 7 * (i + 1), [2, 2, 5, 5, 5][i], {
perfect: true,
...(i ? { pool: pools[i - 1] } : {}),
});
for (const [i, name] of [
"Doubly Difficult",
"Doubly Impossible",
"No Comment",
].entries())
add("campaigns", name, 20 + 10 * i, 5, {
perfect: true,
double: true,
pool: ["white-yellow", "all", "yellow-red"][i],
});
for (const [name, xp, min] of [
["Aye, captain!", 5, 2],
["Loud and clear!", 4, 2],
["All zones secure!", 3, 2],
["Lucky Charm", 2, 2],
["Lead Weight", 1, 2],
["Superstar", 0, 2],
["Lunch Money", 2, 0],
["Children of the Night", 3, 0],
["Devotion", 4, 0],
["Promiscuity", 5, 0],
["Chronicler", 6, 0],
["Master Chronicler", 12, 0],
["Wolf Pack", 2, 0],
["Supertemporality", 3, 0],
["Family Business", 4, 0],
["Integration", 5, 0],
["Pangalactic", 6, 0],
["Respected", 6, 2],
["Flight Instructor", 6, 5],
])
add("social", name, xp, min, { judged: true });
for (const [name, xp] of [
["Banged Up", 2],
["A Thorough Beating", 4],
["Bruised and Broken", 6],
["Duck!", 1],
["Ghost Ship", 3],
["Bad Luck", 5],
["Survivor", 7],
])
add("close-calls", name, xp, 0, { judged: true });
for (const [name, xp, min] of [
["Doombringer", 7, 2],
["Troubleshooter", 6, 2],
["Ace Pilot", 5, 2],
["Blaster Master", 4, 2],
["Rocket Star", 3, 2],
["Transfer Technician", 2, 2],
["Observer", 1, 2],
["Lazy Bum", 2, 2],
["Inspector", 3, 2],
["Take One for the Team", 4, 2],
["Extra Special Specialist", 5, 5],
["Busy Bee", 6, 2],
["Grand Finale", 7, 2],
])
add("hot-shots", name, xp, min, { judged: true });
for (const specialization of SPECIALIZATIONS)
for (const [tier, xp] of [
["basic", 3],
["advanced", 5],
])
add("expert", `${specialization} ${tier}`, xp, 0, {
specialization,
tier,
judged: true,
});
for (const [name, xp, requirements] of [
["Out of this World", 5, { runs: 10 }],
["Out of this Reality", 10, { runs: 25 }],
["Out of this Log Sheet", 20, { runs: 50 }],
["Trucker", 15, { campaigns: 5 }],
["Galaxy Trucker", 25, { campaigns: 15 }],
["Is it still me?", 3, { clones: 15 }],
["Veteran Explorer", 6, { days: 182, minLevel: 2 }],
["Senior Explorer", 12, { days: 365, minLevel: 5 }],
["Jack of Some Trades", 5, { basic: 3 }],
["Jack of Many Trades", 10, { basic: 6 }],
["Jack of All Trades", 15, { basic: 9 }],
["Master of Arts", 10, { advanced: 3 }],
["Master of Many Arts", 20, { advanced: 6 }],
["Master of All Arts", 30, { advanced: 9 }],
["Achievement Collector", 4, { collector: true, minLevel: 2 }],
["Achievement Addict", 42, { addict: true, minLevel: 5 }],
])
add("addiction", name, xp, requirements.minLevel ?? 0, requirements);
function poolMeets(value, required) {
const key = [...(Array.isArray(value) ? value : [value])].sort().join("");
return (
{
"white-yellow": ["12", "2", "123", "23", "3"],
yellow: ["2", "23", "3"],
"yellow-red": ["23", "3"],
red: ["3"],
all: ["123", "23", "3"],
}[required]?.includes(key) ?? false
);
}
export function eligibleAchievements(explorer, runId) {
const r = explorer.runs.find((r) => r.id === runId);
if (!r || r.training) return [];
return ACHIEVEMENTS.filter((a) => {
if (
explorer.achievements.includes(a.id) ||
a.minLevel > (a.category === "addiction" ? explorer.level : r.startLevel)
)
return false;
if (
a.category !== "addiction" &&
(!r.survived ||
r.achievements.some(
(id) =>
ACHIEVEMENTS.find((x) => x.id === id)?.category === a.category,
))
)
return false;
const missions = r.missions ?? [];
const fits = (m) =>
(!a.humans || m.humans === a.humans) &&
(!a.minimumHumans || m.humans >= a.minimumHumans) &&
(!a.crew || m.crew === a.crew) &&
(!a.double || m.doubleActions) &&
(!a.pool ||
(poolMeets(m.difficulty, a.pool) &&
poolMeets(m.seriousDifficulty, a.pool)));
if (a.category === "missions")
return missions.some(
(m) =>
fits(m) &&
(a.easyAllowed ||
m.threatCount >=
(m.doubleActions
? m.crew === 5
? 12
: 10
: m.crew === 5
? 8
: 7)) &&
(!a.perfect || m.penalties === 0),
);
if (a.category === "campaigns")
return (
r.count === r.limit &&
r.count >= 3 &&
(!a.minimumMissions || r.count >= a.minimumMissions) &&
missions.every(
(m) =>
fits(m) &&
m.threatCount >=
(m.doubleActions
? m.crew === 5
? 12
: 10
: m.crew === 5
? 8
: 7),
) &&
(!a.perfect || r.penalties === 0) &&
(!a.differentPools ||
new Set(
missions.map((m) =>
JSON.stringify([m.difficulty, m.seriousDifficulty]),
),
).size === missions.length)
);
if (a.category === "expert")
return (
(r.usedSpecializations ?? []).includes(
`${a.specialization}:${a.tier}`,
) && r.humans > 1
);
if (a.category === "social")
return (
r.humans > 1 ||
[
"superstar",
"lunch-money",
"children-of-the-night",
"chronicler",
"master-chronicler",
].includes(a.id)
);
if (a.category !== "addiction") return true;
const completed = explorer.runs.filter((x) => x.survived && !x.training),
earned = ACHIEVEMENTS.filter((x) => explorer.achievements.includes(x.id));
if (a.runs && completed.length < a.runs) return false;
if (
a.campaigns &&
completed.filter((x) => x.count >= 3 && x.count === x.limit).length <
a.campaigns
)
return false;
if (a.clones && explorer.clones < a.clones) return false;
if (
a.days &&
(!completed.length || r.at - completed[0].at < a.days * 86400000)
)
return false;
for (const tier of ["basic", "advanced"])
if (
a[tier] &&
earned.filter((x) => x.category === "expert" && x.tier === tier)
.length < a[tier]
)
return false;
if (a.collector || a.addict)
for (const cat of [
"missions",
"campaigns",
"social",
"close-calls",
"hot-shots",
"expert",
]) {
const n = earned.filter((x) => x.category === cat).length,
total = ACHIEVEMENTS.filter((x) => x.category === cat).length;
if (
n <
(a.collector ? 1 : cat === "close-calls" ? 2 : Math.ceil(total / 2))
)
return false;
}
return true;
});
}
export function claimAchievement(
input,
runId,
id,
{ crewAgrees = false } = {},
) {
const e = structuredClone(input);
check(!e.activeRun && !e.dead, "Record achievements between missions");
const a = eligibleAchievements(e, runId).find((a) => a.id === id);
check(a, "Achievement is unavailable or already recorded");
check(!a.judged || crewAgrees, "This achievement requires crew judgment");
const r = e.runs.find((r) => r.id === runId);
r.achievements.push(id);
r.xp += a.xp;
e.achievements.push(id);
gain(e, a.xp);
return e;
}

1210
src/game/catalog.js Normal file

File diff suppressed because it is too large Load diff

314
src/game/double-deck.json Normal file
View file

@ -0,0 +1,314 @@
[
{
"sides": [["A", "B"], ["lift"]],
"count": 1
},
{
"sides": [["A", "B"], ["red"]],
"count": 1
},
{
"sides": [["A", "B"], ["blue"]],
"count": 1
},
{
"sides": [["A", "C"], ["lift"]],
"count": 1
},
{
"sides": [["A", "C"], ["red"]],
"count": 1
},
{
"sides": [["A", "C"], ["blue"]],
"count": 1
},
{
"sides": [["A", "lift"], ["red"]],
"count": 1
},
{
"sides": [["A", "lift"], ["blue"]],
"count": 1
},
{
"sides": [["A", "red"], ["lift"]],
"count": 2
},
{
"sides": [["A", "red"], ["blue"]],
"count": 1
},
{
"sides": [["A", "blue"], ["lift"]],
"count": 2
},
{
"sides": [["A", "blue"], ["red"]],
"count": 1
},
{
"sides": [["B", "A"], ["lift"]],
"count": 1
},
{
"sides": [["B", "A"], ["red"]],
"count": 1
},
{
"sides": [["B", "A"], ["blue"]],
"count": 1
},
{
"sides": [["B", "C"], ["lift"]],
"count": 1
},
{
"sides": [["B", "C"], ["red"]],
"count": 1
},
{
"sides": [["B", "C"], ["blue"]],
"count": 1
},
{
"sides": [["B", "lift"], ["red"]],
"count": 2
},
{
"sides": [["B", "lift"], ["blue"]],
"count": 1
},
{
"sides": [["B", "red"], ["lift"]],
"count": 1
},
{
"sides": [["B", "red"], ["blue"]],
"count": 2
},
{
"sides": [["B", "blue"], ["lift"]],
"count": 2
},
{
"sides": [["B", "blue"], ["red"]],
"count": 1
},
{
"sides": [["bots", "A"], ["lift"]],
"count": 1
},
{
"sides": [["bots", "A"], ["red"]],
"count": 1
},
{
"sides": [["bots", "A"], ["blue"]],
"count": 1
},
{
"sides": [["bots", "B"], ["lift"]],
"count": 1
},
{
"sides": [["bots", "B"], ["blue"]],
"count": 1
},
{
"sides": [["bots", "C"], ["lift"]],
"count": 1
},
{
"sides": [["bots", "C"], ["red"]],
"count": 1
},
{
"sides": [["bots", "lift"], ["blue"]],
"count": 1
},
{
"sides": [["bots", "red"], ["lift"]],
"count": 1
},
{
"sides": [["bots", "blue"], ["red"]],
"count": 1
},
{
"sides": [["C", "A"], ["lift"]],
"count": 1
},
{
"sides": [["C", "A"], ["red"]],
"count": 1
},
{
"sides": [["C", "A"], ["blue"]],
"count": 1
},
{
"sides": [["C", "lift"], ["red"]],
"count": 1
},
{
"sides": [["C", "red"], ["blue"]],
"count": 1
},
{
"sides": [["C", "blue"], ["lift"]],
"count": 1
},
{
"sides": [["lift", "A"], ["B"]],
"count": 1
},
{
"sides": [["lift", "A"], ["bots"]],
"count": 1
},
{
"sides": [["lift", "A"], ["C"]],
"count": 1
},
{
"sides": [["lift", "B"], ["A"]],
"count": 1
},
{
"sides": [["lift", "B"], ["C"]],
"count": 1
},
{
"sides": [["lift", "bots"], ["A"]],
"count": 1
},
{
"sides": [["lift", "C"], ["B"]],
"count": 1
},
{
"sides": [["red", "A"], ["B"]],
"count": 1
},
{
"sides": [["red", "A"], ["bots"]],
"count": 1
},
{
"sides": [["red", "A"], ["C"]],
"count": 1
},
{
"sides": [["red", "B"], ["A"]],
"count": 2
},
{
"sides": [["red", "B"], ["C"]],
"count": 1
},
{
"sides": [["red", "bots"], ["A"]],
"count": 1
},
{
"sides": [["red", "C"], ["A"]],
"count": 1
},
{
"sides": [["red", "C"], ["B"]],
"count": 1
},
{
"sides": [["red", "lift"], ["A"]],
"count": 2
},
{
"sides": [["red", "lift"], ["B"]],
"count": 1
},
{
"sides": [["red", "lift"], ["bots"]],
"count": 2
},
{
"sides": [["red", "lift"], ["C"]],
"count": 2
},
{
"sides": [["red", "red"], ["A"]],
"count": 1
},
{
"sides": [["red", "red"], ["B"]],
"count": 1
},
{
"sides": [["red", "red"], ["bots"]],
"count": 1
},
{
"sides": [["red", "red"], ["C"]],
"count": 1
},
{
"sides": [["blue", "A"], ["B"]],
"count": 1
},
{
"sides": [["blue", "A"], ["bots"]],
"count": 1
},
{
"sides": [["blue", "A"], ["C"]],
"count": 1
},
{
"sides": [["blue", "B"], ["C"]],
"count": 1
},
{
"sides": [["blue", "bots"], ["A"]],
"count": 1
},
{
"sides": [["blue", "C"], ["A"]],
"count": 1
},
{
"sides": [["blue", "C"], ["B"]],
"count": 1
},
{
"sides": [["blue", "lift"], ["A"]],
"count": 1
},
{
"sides": [["blue", "lift"], ["B"]],
"count": 2
},
{
"sides": [["blue", "lift"], ["bots"]],
"count": 2
},
{
"sides": [["blue", "lift"], ["C"]],
"count": 2
},
{
"sides": [["blue", "blue"], ["A"]],
"count": 1
},
{
"sides": [["blue", "blue"], ["B"]],
"count": 1
},
{
"sides": [["blue", "blue"], ["bots"]],
"count": 1
},
{
"sides": [["blue", "blue"], ["C"]],
"count": 1
}
]

581
src/game/planning.js Normal file
View file

@ -0,0 +1,581 @@
import {
createCampaign,
recordMission,
voteCampaign,
repairCampaign,
} from "./campaign.js";
import {
baseDeck,
doubleDeck,
heroicDeck,
specializationCards,
cardBack,
PHASE_TURNS,
phaseForTurn,
SPECIALIZATIONS,
} from "./cards.js";
import { TRACKS, THREATS, threatById } from "./catalog.js";
import { shuffle, random } from "./random.js";
import {
beginResolution,
stepResolution,
resolveAll,
createShip,
} from "./resolution.js";
const requireRule = (condition, message) => {
if (!condition) throw Error(message);
};
export function createGame(
state,
{
seed = "preview",
specializations = [],
threatExpansion = false,
difficulty = 1,
seriousDifficulty = difficulty,
actionDeck,
threatAssignments,
campaign = null,
campaignLimit = 0,
carried = campaign?.carried ?? null,
excludeThreats = [],
} = {},
) {
const commonPool = Array.isArray(difficulty) ? difficulty : [difficulty],
seriousPool = Array.isArray(seriousDifficulty)
? seriousDifficulty
: [seriousDifficulty];
requireRule(
[commonPool, seriousPool].every(
(pool) =>
pool.length &&
pool.every((n) => [1, 2, 3].includes(n) && (threatExpansion || n < 3)),
),
"Invalid threat difficulty",
);
requireRule(
!specializations.length ||
(specializations.length === state.crewSize &&
new Set(specializations.filter(Boolean).map((x) => x.name)).size ===
specializations.filter(Boolean).length),
"Each crew member needs a different specialization",
);
const rng = random(seed),
deck = shuffle(
actionDeck ?? (state.mission.doubleActions ? doubleDeck() : baseDeck()),
rng,
),
heroes = shuffle(heroicDeck(), rng),
tracks = shuffle(TRACKS, rng);
const humans = state.players.length,
solo = humans === 1;
const g = {
seed,
carried,
campaign:
campaign ?? (campaignLimit ? createCampaign(seed, campaignLimit) : null),
solo,
threatExpansion,
difficulty,
seriousDifficulty,
specializations: structuredClone(specializations),
cards: Object.fromEntries(deck.map((c) => [c.id, c])),
deck: deck.map((c) => c.id),
hands: Array.from({ length: humans }, () => []),
packets: [],
programs: Array.from({ length: state.crewSize }, () =>
Array(12).fill(null),
),
slotVersions: Array.from({ length: state.crewSize }, () =>
Array(12).fill(0),
),
dealt: Array(humans).fill(0),
androidCards: [],
threats: [],
assignedThreats: [],
transferUsed: [],
dataCredits: Array(humans).fill(0),
androidDataCredits: 0,
androidDataDraws: Array(humans).fill(0),
teleportTokens: Array.from({ length: state.crewSize }, (_, id) => [id, id]),
tracks: Object.fromEntries(
["red", "white", "blue", "internal"].map((z, i) => [z, tracks[i]]),
),
initialShip: createShip(state.crewSize, seed, carried),
resolution: null,
};
function add(card) {
g.cards[card.id] = card;
return card.id;
}
if (solo) {
g.hands[0] = g.deck.splice(0);
}
for (let seat = 0; seat < humans; seat++) {
const counts = solo
? [0, 0, 0]
: humans === 2
? [9, 6, 6]
: humans === 3
? [6, 6, 6]
: [5, 5, 5];
if (!solo && humans < 5 && state.crewSize === 5) counts[0]++;
if (!solo && !specializations.length) counts[0]--;
if (!solo && specializations.length)
counts[0] +=
Math.floor((state.crewSize - humans) / humans) +
(seat < (state.crewSize - humans) % humans ? 1 : 0);
g.packets[seat] = counts.map((n) => g.deck.splice(0, n));
if (!solo) {
if (specializations.length) {
if (specializations[seat])
g.packets[seat][0].push(
...specializationCards(
specializations[seat].name,
specializations[seat].level,
seat,
).map(add),
);
} else g.packets[seat][0].push(add({ ...heroes.pop(), owner: seat }));
}
}
for (let crew = solo ? 0 : humans; crew < state.crewSize; crew++) {
const cards = specializations.length
? specializations[crew]
? specializationCards(
specializations[crew].name,
specializations[crew].level,
crew,
)
: []
: [{ ...heroes.pop(), owner: crew }];
g.androidCards.push(...cards.map(add));
}
const pools = {};
for (const position of ["external", "internal"])
for (const severity of ["normal", "serious"])
pools[`${position}/${severity}`] = shuffle(
THREATS.filter(
(t) =>
t.position === position &&
t.severity === severity &&
(severity === "serious" ? seriousPool : commonPool).includes(
t.difficulty,
) &&
!excludeThreats.includes(t.id) &&
(!t.expansion || threatExpansion),
),
rng,
);
const scheduled = state.timeline.filter((e) => e.type === "threat");
for (const [index, event] of scheduled.entries()) {
const key = `${event.position}/${event.severity}`;
const explicit = threatAssignments?.[index];
let card = explicit ? threatById(explicit) : pools[key].pop();
requireRule(
card,
`Not enough cards in ${key}; choose a larger difficulty pool`,
);
requireRule(
card.position === event.position && card.severity === event.severity,
"Threat assignment has wrong category",
);
g.assignedThreats.push({
eventId: event.id,
instance: index,
cardId: card.id,
turn: event.turn,
zone: event.zone,
});
}
function additional(card, depth = 0) {
requireRule(depth < 12, "Threat call chain too long");
const e = Object.values(card.effects)
.flat()
.find((e) => e.type === "call");
const draw = (position, severity) => {
const found = pools[`${position}/${severity}`].pop();
requireRule(found, `No cards left in ${position}/${severity} deck`);
return { cardId: found.id, ...additional(found, depth + 1) };
};
return {
...(e ? { calledCard: draw(e.position, e.severity) } : {}),
...(card.vortex ? { vortexCard: draw("internal", "normal") } : {}),
};
}
for (const t of g.assignedThreats)
Object.assign(t, additional(threatById(t.cardId)));
return g;
}
export function dealPhase(state, seat, phase) {
const g = state.game;
if (!g) return;
while (g.dealt[seat] < phase) {
g.hands[seat].push(...g.packets[seat][g.dealt[seat]]);
g.dealt[seat]++;
}
}
export function onAnnouncement(state, event) {
const g = state.game;
if (!g) return;
if (event.type === "phase-start")
for (const p of state.players) dealPhase(state, p.seat, p.planningPhase);
if (event.type === "threat")
g.threats.push(
structuredClone(g.assignedThreats.find((t) => t.eventId === event.id)),
);
if (event.type === "incoming-data" && !g.solo) {
const extra = state.mission.doubleActions
? state.crewSize - state.players.length
: 0;
for (const p of state.players)
g.dataCredits[p.seat] += 1 + Math.floor(extra / state.players.length);
g.androidDataCredits += extra % state.players.length;
}
if (event.type === "data-transfer") g.transferUsed = [];
if (g.solo && event.type === "communications-down")
state.communicationsAvailable = true;
}
export function finishGamePlanning(state) {
const g = state.game;
if (!g) return;
const programs = g.programs.map((p) =>
p.map((entry) =>
entry
? {
actions: entry.cards.flatMap(
({ id, side }) => g.cards[id].sides[side],
),
protected: entry.cards.some(({ id, side }) =>
g.cards[id].sides[side].includes("special:special-ops:advanced"),
),
}
: null,
),
);
g.resolution = beginResolution({
crewSize: state.crewSize,
seed: g.seed,
programs,
threats: g.threats,
tracks: g.tracks,
doubleActions: state.mission.doubleActions,
turns: state.mission.phaseEndsMs.length === 2 ? 7 : 12,
teleportTokens: g.teleportTokens,
carried: g.carried,
});
}
export const GAME_COMMAND_FIELDS = {
program: ["crew", "turn", "cards", "slotVersion"],
remove: ["crew", "turn", "slotVersion"],
transfer: ["card", "to"],
draw: ["android"],
teleport: ["crew", "from", "to"],
resolve: ["all"],
"campaign-vote": ["continue"],
"campaign-repair": ["crew", "zone", "tile", "bot", "skip"],
};
function editable(state, seat, crew, turn) {
const g = state.game,
p = state.players[seat];
requireRule(
state.stage === "programming" && !p.finishedPlanning,
"Programming is closed",
);
requireRule(
Number.isInteger(crew) && crew >= 0 && crew < state.crewSize,
"Unknown crew member",
);
requireRule(
g.solo || crew === seat || crew >= state.players.length,
"You cannot program another player",
);
const phase =
g.solo || crew >= state.players.length ? state.phase : p.planningPhase;
requireRule(
Number.isInteger(turn) &&
turn >= PHASE_TURNS[phase - 1][0] &&
turn <= PHASE_TURNS[phase - 1][1],
"This turn is locked or not open yet",
);
}
export function gameCommand(state, seat, command) {
const g = state.game;
requireRule(g, "Game not enabled");
const { crew, turn } = command;
if (command.type === "resolve") {
requireRule(state.stage === "resolution", "Resolution has not started");
requireRule(seat === 0, "Only the captain advances the shared resolution");
g.resolution = command.all
? resolveAll(g.resolution)
: stepResolution(g.resolution);
if (g.resolution.outcome && g.campaign)
g.campaign = recordMission(g.campaign, g.resolution, {
mission: state.mission.id,
usedSpecializations: Array.from(
{ length: state.players.length },
(_, seat) =>
g.resolution.log
.filter((e) => e.type === "specialization" && e.crew === seat)
.map((e) => `${e.name}:${e.tier}`),
),
doubleActions: state.mission.doubleActions,
humans: state.players.length,
difficulty: g.difficulty,
seriousDifficulty: g.seriousDifficulty,
crew: state.crewSize,
penalties: g.resolution.outcome.penalties,
threatCount: state.timeline
.filter((e) => e.type === "threat")
.reduce((n, t) => n + (t.severity === "serious" ? 2 : 1), 0),
});
return;
}
if (command.type === "campaign-vote") {
requireRule(g.campaign, "No campaign");
g.campaign = voteCampaign(
g.campaign,
seat,
command.continue,
state.players.length,
);
return;
}
if (command.type === "campaign-repair") {
requireRule(g.campaign, "No campaign");
requireRule(
g.solo || crew === seat || crew >= state.players.length,
"This repair belongs to another player",
);
const { type, sequence, ...choice } = command;
g.campaign = repairCampaign(g.campaign, choice);
return;
}
requireRule(state.stage === "programming", "Programming is closed");
if (command.type === "draw") {
if (command.android) {
requireRule(g.androidDataCredits > 0, "No shared android card available");
requireRule(
g.androidDataDraws[seat] === Math.min(...g.androidDataDraws),
"Divide extra cards evenly among players",
);
} else requireRule(g.dataCredits[seat] > 0, "No incoming data available");
requireRule(g.deck.length > 0, "Action deck is empty");
g.hands[seat].push(g.deck.shift());
if (command.android) {
g.androidDataCredits--;
g.androidDataDraws[seat]++;
} else g.dataCredits[seat]--;
return;
}
if (command.type === "transfer") {
requireRule(
!g.solo &&
state.transferClosesAt !== null &&
state.observedAt < state.transferClosesAt,
"Transfer window is closed",
);
requireRule(
!g.transferUsed.includes(seat),
"You already sent a card in this window",
);
requireRule(
Number.isInteger(command.to) &&
state.players[command.to] &&
command.to !== seat,
"Choose another player",
);
requireRule(
g.hands[seat].includes(command.card) &&
g.cards[command.card]?.kind === "normal",
"Only an ordinary card in your hand can be transferred",
);
g.hands[seat].splice(g.hands[seat].indexOf(command.card), 1);
g.hands[command.to].push(command.card);
g.transferUsed.push(seat);
return;
}
if (command.type === "teleport") {
requireRule(
Number.isInteger(crew) &&
(g.solo || crew === seat || crew >= state.players.length) &&
g.specializations[crew]?.name === "teleporter",
"Only the Teleporter moves these tokens",
);
requireRule(
g.solo ||
(state.transferClosesAt !== null &&
state.observedAt < state.transferClosesAt),
"Transfer window is closed",
);
requireRule(
[command.from, command.to].every(
(i) => Number.isInteger(i) && i >= 0 && i < state.crewSize,
),
"Unknown crew member",
);
g.teleportTokens[crew] = [command.from, command.to];
return;
}
editable(state, seat, crew, turn);
requireRule(
command.slotVersion === g.slotVersions[crew][turn - 1],
"This slot changed; refresh before editing it",
);
const current = g.programs[crew][turn - 1],
android = !g.solo && crew >= state.players.length;
requireRule(!android || !current, "Android programs cannot be taken back");
if (command.type === "remove") {
requireRule(current, "This slot is empty");
for (const { id } of current.cards) {
if (
g.cards[id].owner !== undefined &&
(g.solo || crew >= state.players.length)
)
g.androidCards.push(id);
else g.hands[seat].push(id);
}
g.programs[crew][turn - 1] = null;
} else {
requireRule(
Array.isArray(command.cards) &&
command.cards.length >= 1 &&
command.cards.length <= 2,
"Choose one action card",
);
requireRule(
new Set(command.cards.map((c) => c.id)).size === command.cards.length,
"Cannot play the same card twice",
);
for (const c of command.cards) {
requireRule(
c && Object.keys(c).every((k) => ["id", "side"].includes(k)),
"Invalid card choice",
);
const card = g.cards[c.id];
requireRule(
card && Number.isInteger(c.side) && card.sides[c.side],
"Invalid card side",
);
requireRule(
g.hands[seat].includes(c.id) ||
g.androidCards.includes(c.id) ||
current?.cards.some((x) => x.id === c.id),
"Card is not available",
);
requireRule(
card.owner === undefined || card.owner === crew,
"This card belongs to another crew member",
);
}
let cards = command.cards;
if (cards.length === 2) {
const special =
cards.find(
(c) =>
g.cards[c.id].sides[c.side][0] === "special:special-ops:advanced",
) ??
cards.find((c) =>
g.cards[c.id].sides[c.side][0].startsWith("special:"),
);
const other = cards.find((c) => c !== special),
a = special && g.cards[special.id].sides[special.side][0];
const otherActions = other && g.cards[other.id].sides[other.side];
requireRule(
a === "special:special-ops:advanced" ||
(a?.startsWith("special:medic:") &&
otherActions.length === 1 &&
["red", "blue", "lift"].includes(otherActions[0])),
"These cards cannot be combined",
);
cards = a.startsWith("special:medic:")
? [other, special]
: [special, other];
}
requireRule(
cards.length === 2 ||
!g.cards[cards[0].id].sides[cards[0].side].includes(
"special:special-ops:advanced",
),
"Advanced Special Ops needs a second card",
);
if (current)
for (const { id } of current.cards) {
if (g.cards[id].owner !== undefined && g.solo) g.androidCards.push(id);
else g.hands[seat].push(id);
}
for (const { id } of cards) {
g.hands[seat] = g.hands[seat].filter((x) => x !== id);
g.androidCards = g.androidCards.filter((x) => x !== id);
}
g.programs[crew][turn - 1] = { cards: structuredClone(cards) };
}
g.slotVersions[crew][turn - 1]++;
}
export function gameView(state, seat) {
const g = state.game;
if (!g) return undefined;
const valid = Number.isInteger(seat) && Boolean(state.players[seat]);
const revealed = state.stage === "resolution";
const publicShip = (ship) => {
const s = structuredClone(ship);
for (const z of Object.values(s.zones)) delete z.damageDeck;
return s;
};
return {
solo: g.solo,
campaign: g.campaign
? { ...g.campaign, lastShip: undefined, usedThreats: undefined }
: null,
catalogue: g.threatExpansion ? "base-and-new-frontier" : "base",
specializations: g.specializations,
tracks: g.tracks,
ship: publicShip(g.resolution?.ship ?? g.initialShip),
hand:
valid && state.phase > 0 ? g.hands[seat].map((id) => g.cards[id]) : [],
androidCards:
state.phase > 0 ? g.androidCards.map((id) => g.cards[id]) : [],
dataCredits: valid ? g.dataCredits[seat] : 0,
androidDataCredits: valid ? g.androidDataCredits : 0,
canDrawAndroid:
valid && g.androidDataDraws[seat] === Math.min(...g.androidDataDraws),
transferUsed: valid ? g.transferUsed.includes(seat) : false,
programs: g.programs.map((p, crew) =>
p.map((entry, index) => ({
turn: index + 1,
revision: g.slotVersions[crew][index],
cards:
entry?.cards.map(({ id, side }) =>
revealed ||
(valid && (g.solo || crew === seat)) ||
crew >= state.players.length
? { ...g.cards[id], side }
: cardBack(g.cards[id], side),
) ?? [],
})),
),
threats: g.threats.map(publicThreat),
teleportTokens: g.teleportTokens,
resolution: g.resolution
? {
turn: g.resolution.turn,
step: g.resolution.step,
outcome: g.resolution.outcome,
log: g.resolution.log,
frames: g.resolution.frames.map((f) => ({
...f,
ship: publicShip(f.ship),
threats: f.threats.map(publicThreat),
})),
}
: null,
};
}
function publicThreat({ vortexCard, calledCard, ...threat }) {
return {
...threat,
...(threat.cardId ? { card: threatById(threat.cardId) } : {}),
...(calledCard ? { calledCard: publicThreat(calledCard) } : {}),
};
}

20
src/game/random.js Normal file
View file

@ -0,0 +1,20 @@
// Serializable deterministic PRNG. The host keeps the seed and undrawn decks secret.
export function random(seed) {
let value = 2166136261;
for (const ch of String(seed))
value = Math.imul(value ^ ch.charCodeAt(0), 16777619);
return () => {
value += 0x6d2b79f5;
let n = Math.imul(value ^ (value >>> 15), 1 | value);
n ^= n + Math.imul(n ^ (n >>> 7), 61 | n);
return ((n ^ (n >>> 14)) >>> 0) / 4294967296;
};
}
export function shuffle(values, rng) {
const result = structuredClone(values);
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}

1561
src/game/resolution.js Normal file

File diff suppressed because it is too large Load diff

152
src/game/specializations.js Normal file
View file

@ -0,0 +1,152 @@
// The New Frontier pp. 16–23. The engine owns the meaning of an action;
// UI descriptions never decide whether an effect is legal.
import { shuffle, random } from "./random.js";
export function specialAction(r, p, name, tier, api) {
const { fire, transferEnergy, actionC, repair, note } = api;
const advanced = tier === "advanced",
station = p.station,
zone = station.split("-")[0];
const damaged = (s, a) =>
r.threats.some(
(t) =>
t.position === "internal" &&
t.repair === a &&
t.stations.includes(s) &&
!["pending", "destroyed"].includes(t.status) &&
!t.phasedOut,
);
note(r, "specialization", { crew: p.id, name, tier });
if (name === "rocketeer") {
if (!advanced) actionC(r, p, "blue-lower", { remote: true });
else actionC(r, p, station, { doubleRocket: station === "blue-lower" });
} else if (name === "data-analyst") {
if (!advanced) {
actionC(r, p, "white-upper", { remote: true });
r.ship.bonus++;
} else
actionC(r, p, station, { visual: station === "white-lower" ? 3 : 1 });
} else if (name === "energy-technician") {
if (!advanced) transferEnergy(r, p, false, "white-lower", true);
else if (station.endsWith("upper"))
for (const z of ["red", "white", "blue"])
r.turnState.temporaryShields[z] += z === zone ? 2 : 1;
} else if (name === "pulse-gunner") {
if (advanced) {
fire(
r,
p,
false,
station,
station === "white-lower" && !damaged(station, "A"),
);
return;
}
if (station === "white-lower" || damaged(station, "A")) {
fire(r, p);
return;
}
const prepared = r.ship.preparedWeapons.includes(station);
const energy = r.ship.zones[zone].reactor;
const sameReactor = station === "white-upper";
const eligible =
!r.turnState.fired.includes(station) &&
!r.turnState.fired.includes("white-lower") &&
!damaged("white-lower", "A") &&
r.ship.zones.white.reactor >= (sameReactor ? 2 : 1) &&
(station.endsWith("lower") || energy > 0);
if (eligible) {
fire(r, p);
fire(r, p, false, "white-lower");
} else {
if (prepared)
r.ship.preparedWeapons = r.ship.preparedWeapons.filter(
(s) => s !== station,
);
note(r, "ineffective", {
crew: p.id,
reason: "linked-weapons-unavailable",
});
}
} else if (name === "medic") {
if (advanced) {
r.turnState.protectingMedics.push(p.id);
r.ship.bonus--;
} else
r.turnState.stimulated.push(
...r.ship.crew
.filter((c) => !c.space && c.station === station)
.map((c) => c.id),
);
} else if (name === "teleporter") {
if (advanced) {
if (zone !== "white")
p.station = `${zone === "red" ? "blue" : "red"}-${station.endsWith("upper") ? "lower" : "upper"}`;
} else {
const pair = r.teleportTokens[p.id] ?? [p.id, p.id],
from = r.ship.crew[pair[0]],
to = r.ship.crew[pair[1]];
if (from && to && !from.space && !to.space) from.station = to.station;
}
} else if (name === "hypernavigator") {
if (!advanced && station.endsWith("lower")) r.turnState.slow = 1;
else if (advanced && station === "white-lower" && [10, 11].includes(r.turn))
r.turnState.earlyJump = true;
} else if (name === "special-ops") {
if (!advanced) p.prepared = true;
// Advanced is interpreted on the program entry: protection wraps both subactions.
} else if (name === "squad-leader") {
if (p.bots === null) return;
const bot = r.ship.bots[p.bots];
if (advanced) {
if (bot.disabled || station === "blue-lower") return;
api.heroicMovement(r, p, "red-upper");
if (p.station === "red-upper" && !damaged(p.station, "C")) actionC(r, p);
} else if (bot.disabled) bot.disabled = false;
else {
const z = r.ship.zones[zone],
upper = station.endsWith("upper");
const priority = upper
? [
"upper-weapon",
"lower-weapon",
"lift",
"shield",
"reactor",
"structure",
]
: [
"lower-weapon",
"upper-weapon",
"lift",
"reactor",
"shield",
"structure",
];
const tile = priority.find((t) => z.damage.includes(t));
if (tile) {
z.damage = z.damage.filter((t) => t !== tile);
z.damageDeck = shuffle(
[...z.damageDeck, tile],
random(`${r.turn}/${p.id}/${r.log.length}/${z.damageDeck.join()}`),
);
if (tile === "structure") z.carriedStructure = false;
note(r, "hull-repaired", { crew: p.id, zone, tile });
}
}
} else if (name === "mechanic") {
if (!advanced) {
if (!damaged(station, "A") && !r.ship.preparedWeapons.includes(station))
r.ship.preparedWeapons.push(station);
} else {
const t = r.threats.find(
(t) =>
t.position === "internal" &&
t.status === "active" &&
!t.phasedOut &&
t.stations.includes(station) &&
["A", "B", "C"].includes(t.repair),
);
if (t) repair(r, p, t.repair, true);
}
} else throw Error(`Unsupported specialization: ${name}`);
}

View file

@ -17,8 +17,8 @@ export function getMission(id) {
export function compileTimeline(mission, crewSize) { export function compileTimeline(mission, crewSize) {
const ends = mission.phaseEndsMs; const ends = mission.phaseEndsMs;
if (![4, 5].includes(crewSize)) if (![3, 4, 5].includes(crewSize))
throw new Error("Crew size must be four or five"); throw new Error("Crew size must be three, four or five");
if ( if (
!Array.isArray(ends) || !Array.isArray(ends) ||
![2, 3].includes(ends.length) || ![2, 3].includes(ends.length) ||

View file

@ -1,3 +1,12 @@
import {
createGame,
dealPhase,
onAnnouncement,
finishGamePlanning,
GAME_COMMAND_FIELDS,
gameCommand,
gameView,
} from "./game/planning.js";
import { compileTimeline } from "./missions.js"; import { compileTimeline } from "./missions.js";
export const PRESENCE_WINDOW_MS = 120_000; export const PRESENCE_WINDOW_MS = 120_000;
@ -12,15 +21,16 @@ function append(state, at, type, details = {}) {
state.revision++; state.revision++;
} }
export function createSession( export function createSession(
{ players, crewSize = Math.max(4, players), mission }, { players, crewSize = Math.max(4, players), mission, gameOptions },
now, now,
) { ) {
timestamp(now); timestamp(now);
if (!Number.isInteger(players) || players < 1 || players > 5) if (!Number.isInteger(players) || players < 1 || players > 5)
throw new Error("Invalid player count"); throw new Error("Invalid player count");
if (crewSize < players) throw new Error("Crew cannot omit a player"); if (crewSize < players || (crewSize === 3 && players !== 3))
throw new Error("Invalid crew configuration");
const timeline = compileTimeline(mission, crewSize); const timeline = compileTimeline(mission, crewSize);
return { const state = {
version: 1, version: 1,
stage: "presence", stage: "presence",
revision: 0, revision: 0,
@ -50,12 +60,15 @@ export function createSession(
log: [], log: [],
cancellation: null, cancellation: null,
}; };
if (gameOptions) state.game = createGame(state, gameOptions);
return state;
} }
function finish(state, at, early = false) { function finish(state, at, early = false) {
state.stage = "resolution"; state.stage = "resolution";
state.transferClosesAt = null; state.transferClosesAt = null;
state.communicationsAvailable = true; state.communicationsAvailable = true;
state.players.forEach((p) => (p.finishedPlanning = true)); state.players.forEach((p) => (p.finishedPlanning = true));
finishGamePlanning(state);
append(state, at, "programming-complete", { early }); append(state, at, "programming-complete", { early });
} }
@ -98,6 +111,7 @@ export function advanceClock(input, now) {
else if (event.type === "data-transfer") else if (event.type === "data-transfer")
state.transferClosesAt = at + event.durationMs; state.transferClosesAt = at + event.durationMs;
else if (event.type === "data-transfer-end") state.transferClosesAt = null; else if (event.type === "data-transfer-end") state.transferClosesAt = null;
onAnnouncement(state, event);
const { atMs, ...announcement } = event; const { atMs, ...announcement } = event;
append(state, at, "announcement", { event: announcement }); append(state, at, "announcement", { event: announcement });
} }
@ -125,9 +139,23 @@ export function submit(input, seat, command, receivedAt) {
command.sequence < 1 command.sequence < 1
) )
return reject("Invalid command sequence"); return reject("Invalid command sequence");
if (!["ready", "advance-phase", "finish-planning"].includes(command.type)) if (
![
"ready",
"advance-phase",
"finish-planning",
...Object.keys(GAME_COMMAND_FIELDS),
].includes(command.type)
)
return reject("Unsupported command"); return reject("Unsupported command");
if (Object.keys(command).some((key) => key !== "type" && key !== "sequence")) if (
Object.keys(command).some(
(key) =>
key !== "type" &&
key !== "sequence" &&
!(GAME_COMMAND_FIELDS[command.type] ?? []).includes(key),
)
)
return reject("Unexpected command field"); return reject("Unexpected command field");
const player = state.players[seat]; const player = state.players[seat];
if (command.sequence <= player.lastSequence) if (command.sequence <= player.lastSequence)
@ -135,6 +163,17 @@ export function submit(input, seat, command, receivedAt) {
if (command.sequence !== player.lastSequence + 1) if (command.sequence !== player.lastSequence + 1)
return reject("Refresh before sending the next command"); return reject("Refresh before sending the next command");
const now = state.observedAt; const now = state.observedAt;
if (GAME_COMMAND_FIELDS[command.type]) {
const draft = structuredClone(state);
try {
gameCommand(draft, seat, command);
} catch (error) {
return reject(error.message);
}
draft.players[seat].lastSequence = command.sequence;
draft.revision++;
return { state: draft, accepted: true, duplicate: false };
}
if (command.type === "ready") { if (command.type === "ready") {
if (state.stage !== "presence") return reject("Presence check is closed"); if (state.stage !== "presence") return reject("Presence check is closed");
if (!player.ready) { if (!player.ready) {
@ -152,9 +191,12 @@ export function submit(input, seat, command, receivedAt) {
if (state.stage !== "programming") return reject("Programming is closed"); if (state.stage !== "programming") return reject("Programming is closed");
if (player.finishedPlanning) return reject("Your plan is locked"); if (player.finishedPlanning) return reject("Your plan is locked");
if (command.type === "advance-phase") { if (command.type === "advance-phase") {
if (state.game?.solo)
return reject("Solo phases follow the shared clock");
if (player.planningPhase >= state.mission.phaseEndsMs.length) if (player.planningPhase >= state.mission.phaseEndsMs.length)
return reject("Already in the last phase"); return reject("Already in the last phase");
player.planningPhase++; player.planningPhase++;
dealPhase(state, seat, player.planningPhase);
append(state, now, "player-phase", { seat, phase: player.planningPhase }); append(state, now, "player-phase", { seat, phase: player.planningPhase });
} else { } else {
if (state.phase < state.mission.phaseEndsMs.length) if (state.phase < state.mission.phaseEndsMs.length)
@ -190,6 +232,7 @@ export function canEditTurn(state, seat, turn) {
export function snapshot(state, seat) { export function snapshot(state, seat) {
// An allowlist keeps the unannounced schedule out of every player/spectator view. // An allowlist keeps the unannounced schedule out of every player/spectator view.
return structuredClone({ return structuredClone({
game: gameView(state, seat),
version: state.version, version: state.version,
revision: state.revision, revision: state.revision,
stage: state.stage, stage: state.stage,

211
src/tutorials.js Normal file
View file

@ -0,0 +1,211 @@
// Small, original teaching scenarios. They use the same planning and resolution
// code as missions; only their clock is advanced explicitly by the local host.
import { createSession, submit, advanceClock } from "./session.js";
import { TRACKS } from "./game/catalog.js";
const lesson = (id, title, instructions, options = {}) => ({
id,
title,
instructions,
...options,
});
export const LESSONS = [
lesson(
"first-shot",
["Votre premier tir", "Your first shot"],
[
[
"La menace arrive au tour 2. Le T+ indique un tour de résolution, pas une minute. Les androïdes sont tous au centre ; le second s’occupe déjà de l’ordinateur.",
"The threat arrives on turn 2. T+ is a resolution turn, not a minute. Everyone starts on the bridge; android 2 already handles the computer.",
],
[
"Avec l’androïde 1, programmez A aux tours 2 et 3. Les tirs du laser central coûtent chacun 1 énergie. Le bouclier ennemi s’applique de nouveau à chaque tour.",
"For android 1, program A on turns 2 and 3. Each central laser shot uses 1 energy. Enemy shields apply again each turn.",
],
[
"Passez à la phase 2, puis lancez la résolution. Suivez le journal : les tirs combinés du tour précèdent le mouvement de la menace. Vous pouvez recommencer et comparer.",
"Advance to phase 2, then resolve. Watch the log: a turn’s combined fire happens before threat movement. Restart and compare different programs.",
],
],
{ threat: "E1-07", turn: 2 },
),
lesson(
"energy",
["Énergie et coordination", "Energy and coordination"],
[
[
"Le réacteur blanc commence avec 3 énergies. Le laser lourd et l’impulsion utilisent cette même réserve ; B à l’étage recharge le bouclier, pas le réacteur.",
"White starts with 3 reactor energy. Heavy laser and pulse share it; B upstairs fills the shield, not the reactor.",
],
[
"Androïde 1 : A, A, A aux tours 1–3, puis A au tour 4. Sans ravitaillement, ce dernier tir échouera. Essayez ensuite : androïde 3, ascenseur au tour 1 puis B au tour 2.",
"Android 1: A, A, A on turns 1–3, then A on turn 4. Without refueling, that last shot fails. Then try android 3: lift on turn 1, B on turn 2.",
],
[
"Dans la résolution, vérifiez la capsule consommée, l’énergie disponible et les tirs sans effet. Chaque arme ne peut tirer qu’une fois par tour, même si deux équipiers utilisent A.",
"During resolution, check the consumed capsule, available energy and failed shots. Each weapon can fire only once per turn, even if two crew use A.",
],
],
),
lesson(
"repairs",
["Réparer une panne", "Repairing a malfunction"],
[
[
"La panne apparaît en bleu supérieur au tour 2. Une panne détourne le bouton indiqué : il répare au lieu d’utiliser le système.",
"The malfunction appears in upper blue on turn 2. It overrides the indicated button: that button repairs instead of using the system.",
],
[
"Androïde 1 : flèche bleue au tour 1, puis B aux tours 2, 3 et 4. Inspectez la carte de menace pour lire ses vies et ses actions X/Y/Z.",
"Android 1: blue arrow on turn 1, then B on turns 2, 3 and 4. Inspect the threat card for hit points and X/Y/Z effects.",
],
[
"Un B joué avant l’apparition aurait chargé le bouclier au lieu de réparer. Comparez les résultats en modifiant le programme après avoir recommencé.",
"A B before the threat appears would fill the shield instead of repairing. Restart and change your program to compare.",
],
],
{ threat: "I1-05", turn: 2 },
),
lesson(
"battlebots",
["Robots et intercepteurs", "Battlebots and interceptors"],
[
[
"Les robots attendent en bleu supérieur et rouge inférieur. C prend une escouade ; le symbole robot est une action distincte qui combat les intrus.",
"Battlebots wait in upper blue and lower red. C picks up a squad; the battlebot symbol is a separate action for fighting intruders.",
],
[
"Androïde 1 : flèche bleue, C, flèche rouge aux tours 1–3. En phase 2 : flèche rouge puis C pour décoller depuis le rouge supérieur avec vos robots.",
"Android 1: blue arrow, C, red arrow on turns 1–3. In phase 2: red arrow, then C to launch from upper red with your battlebots.",
],
[
"En vol : robot pour rester et tirer ; une case vide vous fait rentrer. Une autre action est retardée au retour. Les robots désactivés ne permettent pas de décoller.",
"In flight: battlebot action to stay and fire; an empty slot returns you. Other actions are delayed on return. Disabled battlebots cannot launch.",
],
],
),
lesson(
"double-actions",
["Deux actions, dans l’ordre", "Two actions, in order"],
[
[
"Ce paquet contient des cartes à deux actions. Choisissez une moitié comme d’habitude : ses deux symboles s’exécutent de gauche à droite.",
"This deck has double-action cards. Choose a half normally: its two symbols execute left to right.",
],
[
"Comparez flèche bleue + A avec A + flèche bleue au tour 2 : le laser utilisé change. Vous ne pouvez pas volontairement ignorer une moitié réalisable.",
"Compare blue arrow + A with A + blue arrow on turn 2: they fire different lasers. You cannot voluntarily skip a performable half.",
],
[
"Si la première moitié provoque un retard (ascenseur occupé, Slime), la seconde passe au tour suivant. Les intercepteurs peuvent désormais changer de portée avec les doubles actions.",
"If the first half causes a delay (busy lift, Slime), the second moves to the next turn. Double actions also let interceptors change range.",
],
],
{ doubleActions: true },
),
lesson(
"phasing",
["Menaces de l’extension", "Expansion threats"],
[
[
"Le chasseur apparaît au tour 1. Dépliez sa carte : il alterne un tour visible et un tour déphasé. Les attaques entre crochets concernent les tours déphasés.",
"The fighter appears on turn 1. Open its card: it alternates a visible turn and a phased-out turn. Bracketed attacks apply on phased-out turns.",
],
[
"Essayez A aux tours 1, 2 et 3. Pendant le tour déphasé, votre arme l’ignore totalement et pourrait toucher une autre cible derrière lui.",
"Try A on turns 1, 2 and 3. While phased out, it is ignored completely and a weapon could hit another target behind it.",
],
[
"Le catalogue ajoute aussi plasma, mégaboucliers, renforts et intrus spéciaux. Chaque carte décrit ses exceptions ; les renforts sont révélés avec la menace qui peut les appeler.",
"Other new threats introduce plasma, megashields, reinforcements and special intruders. Each card explains its exceptions; reinforcements are revealed with their potential caller.",
],
],
{ threat: "E2-102", turn: 1 },
),
lesson(
"specializations",
["Spécialisations", "Specializations"],
[
[
"Les spécialisations remplacent les cartes héroïques. Niveau 1 : une capacité basique ; niveau 2 : une carte permettant basique ou avancée ; niveau 3 : les deux cartes.",
"Specializations replace heroic cards. Level 1: one basic ability; level 2: one card with basic or advanced; level 3: both cards.",
],
[
"L’androïde 1 est Artilleur niveau 3. Essayez sa capacité basique depuis la passerelle : la roquette part à distance et touche au tour suivant. Lisez l’aide affichée quand vous sélectionnez une capacité.",
"Android 1 is a level-3 Rocketeer. Try the basic ability from the bridge: it launches remotely and hits next turn. Selecting an ability shows its rules.",
],
[
"Une carte de spécialisation ne s’échange pas. Le Médecin et l’Agent spécial peuvent combiner certaines cartes ; le Téléporteur place ses jetons pendant les transferts. En partie libre, choisissez les spécialités dans la configuration.",
"Specialization cards cannot be transferred. Medic and Special Ops can combine some cards; Teleporter assigns tokens during transfers. Choose specialties in setup for free play.",
],
],
{
specializations: [
{ name: "rocketeer", level: 3 },
{ name: "data-analyst", level: 1 },
{ name: "medic", level: 1 },
{ name: "teleporter", level: 1 },
],
},
),
];
export function createLesson(id, now) {
const l = LESSONS.find((l) => l.id === id);
if (!l) throw Error("Unknown lesson");
const mission = {
id: `lesson-${id}`,
title: l.title[1],
doubleActions: !!l.doubleActions,
phaseEndsMs: [600000, 1200000],
events: l.threat
? [
{
atMs: 0,
type: "threat",
confirmed: true,
turn: l.turn,
position: l.threat.startsWith("I") ? "internal" : "external",
severity: "normal",
zone: l.threat.startsWith("I") ? undefined : "white",
},
]
: [],
};
let s = createSession(
{
players: 1,
mission,
gameOptions: {
seed: `lesson/${id}`,
threatExpansion: true,
difficulty: [1, 2, 3],
threatAssignments: l.threat ? [l.threat] : [],
specializations: l.specializations ?? [],
},
},
now,
);
s = submit(s, 0, { type: "ready", sequence: 1 }, now).state;
s = advanceClock(s, now + 3000);
s.tutorial = { id, title: l.title, instructions: l.instructions };
s.game.tracks = Object.fromEntries(
["red", "white", "blue", "internal"].map((z) => [
z,
structuredClone(TRACKS[6]),
]),
);
// Public, editable teammate example, using physical cards from the shared solo deck.
for (const turn of [1, 4]) {
const id = s.game.hands[0].find((id) =>
s.game.cards[id].sides.some(
(side) => side.length === 1 && side[0] === "C",
),
);
const side = s.game.cards[id].sides.findIndex(
(side) => side.length === 1 && side[0] === "C",
);
s.game.hands[0] = s.game.hands[0].filter((c) => c !== id);
s.game.programs[1][turn - 1] = { cards: [{ id, side }] };
s.game.slotVersions[1][turn - 1]++;
}
return s;
}

319
test/frontier.test.js Normal file
View file

@ -0,0 +1,319 @@
import test from "node:test";
import assert from "node:assert/strict";
import { THREATS, TRACKS } from "../src/game/catalog.js";
import { doubleDeck } from "../src/game/cards.js";
import {
beginResolution,
stepResolution,
resolveAll,
execute,
attack,
} from "../src/game/resolution.js";
import { createSession, snapshot } from "../src/session.js";
import { getMission, missionSummaries } from "../src/missions.js";
function scenario(card, options = {}) {
const cards = Array.isArray(card)
? card
: card
? [{ cardId: card, turn: 1, zone: "white" }]
: [];
return beginResolution({
crewSize: 4,
seed: "frontier",
programs: Array.from({ length: 4 }, () => Array(12).fill(null)),
threats: cards,
tracks: Object.fromEntries(
["red", "white", "blue", "internal"].map((z) => [z, TRACKS[6]]),
),
...options,
});
}
function at(r, turn, step) {
let n = 0;
while (!r.outcome && (r.turn !== turn || r.step !== step) && n++ < 100)
r = stepResolution(r);
return r;
}
test("90 physical double cards retain their side order and 78 combinations", () => {
const d = doubleDeck();
assert.equal(d.length, 90);
assert.equal(new Set(d.map((c) => c.id)).size, 90);
assert.equal(new Set(d.map((c) => JSON.stringify(c.sides))).size, 78);
assert.ok(d.every((c) => c.sides[0].length === 2 && c.sides[1].length === 1));
});
test("full 103-card catalogue, including 48 expansion cards, resolves without invalid numbers", () => {
assert.equal(THREATS.length, 103);
assert.equal(THREATS.filter((t) => t.expansion).length, 48);
for (const card of THREATS) {
const calls = Object.values(card.effects)
.flat()
.find((e) => e.type === "call");
const r = scenario([
{
cardId: card.id,
turn: 1,
zone: card.position === "external" ? "white" : null,
calledCard: calls
? { cardId: calls.position === "external" ? "E1-07" : "I1-01" }
: null,
vortexCard: card.vortex ? { cardId: "I1-01" } : null,
},
]);
const end = resolveAll(r);
assert.ok(Number.isFinite(end.outcome.score), card.id);
assert.deepEqual(
resolveAll(JSON.parse(JSON.stringify(r))),
end,
card.id + " replay",
);
for (const z of Object.values(end.ship.zones))
for (const n of ["reactor", "shield"])
assert.ok(Number.isFinite(z[n]) && z[n] >= 0, card.id);
}
});
test("pulse cannon targets every zone once, including a spanning threat", () => {
let r = scenario([
{ cardId: "E1-07", turn: 1, zone: "red" },
{ cardId: "E1-07", turn: 1, zone: "blue" },
{ cardId: "SE3-103", turn: 1, zone: "white" },
]);
r = at(r, 1, "crew");
r.ship.crew[0].station = "white-lower";
r.threats.forEach((t) => {
t.positionOnTrack = 8;
t.shield = 0;
});
execute(r, r.ship.crew[0], "A");
r = at(r, 1, "threats");
assert.deepEqual(
r.threats.map((t) => t.damage),
[1, 1, 1],
);
});
test("phasing alternates vulnerability while bracketed attacks still execute", () => {
let r = scenario("E2-102");
r = at(r, 1, "crew");
r.threats[0].track = {
length: 16,
marks: [
[13, "X"],
[10, "Y"],
[1, "Z"],
],
};
execute(r, r.ship.crew[0], "A");
r = at(r, 2, "crew");
assert.equal(r.threats[0].phasedOut, true);
const damage = r.threats[0].damage;
execute(r, r.ship.crew[0], "A");
r = at(r, 2, "threats");
assert.equal(r.threats[0].damage, damage);
r = at(r, 3, "crew");
assert.equal(r.threats[0].phasedOut, false);
const hits = r.log.filter((e) => e.type === "attack");
assert.equal(hits[1].damage, 1);
});
test("inaccessibility absorbs a combined first repair point, and remote repairs cannot finish", () => {
let r = at(scenario("SI2-101"), 1, "crew");
execute(r, r.ship.crew[0], "C");
assert.equal(r.threats[0].damage, 0);
execute(r, r.ship.crew[1], "C");
assert.equal(r.threats[0].damage, 1);
execute(r, r.ship.crew[2], "special:data-analyst:basic");
assert.equal(r.threats[0].damage, 1);
execute(r, r.ship.crew[3], "C");
assert.equal(r.threats[0].status, "destroyed");
});
test("polarization halves all lasers together, before shields, while pulse stays full", () => {
let r = at(scenario("E3-108"), 1, "crew");
r.threats[0].zone = "red";
r.threats[0].positionOnTrack = 8;
r.ship.crew[0].station = "red-upper";
r.ship.crew[1].station = "red-lower";
r.ship.crew[2].station = "white-lower";
r.ship.zones.red.damage = ["lower-weapon"];
for (let i = 0; i < 3; i++) execute(r, r.ship.crew[i], "A");
r = at(r, 1, "threats");
assert.equal(r.threats[0].damage, 3);
});
test("carrier protection depends on interceptor range, not targeting or damage", () => {
let r = at(scenario("E2-101"), 1, "crew");
r.ship.crew[0].space = 1;
r.threats[0].positionOnTrack = 11;
attack(r, r.threats[0], 2);
assert.equal(r.ship.zones.white.shield, 1);
assert.equal(r.ship.zones.white.damage.length, 0);
r.doubleActions = true;
r.ship.crew[0].space = 3;
r.threats[0].positionOnTrack = 5;
attack(r, r.threats[0], 2);
assert.equal(r.ship.zones.white.damage.length, 1);
});
test("jumps retain the distance and use only markers on the original trajectory this turn", () => {
let r = at(scenario("E3-105"), 1, "threats");
r.threats[0].positionOnTrack = 10;
r.threats[0].track = {
length: 10,
marks: [
[9, "X"],
[7, "Y"],
[1, "Z"],
],
};
r.tracks.red = { length: 10, marks: [[8, "Z"]] };
r = stepResolution(r);
assert.equal(r.threats[0].status, "active");
assert.equal(r.threats[0].zone, "blue");
assert.equal(r.threats[0].positionOnTrack, 7);
assert.deepEqual(
r.log.filter((e) => e.type === "threat-action").map((e) => e.mark),
["X", "Y"],
);
});
test("called threats appear after movement; preventing the call awards both destroyed cards", () => {
const setup = [
{
cardId: "SE3-105",
turn: 1,
zone: "white",
calledCard: { cardId: "E1-07" },
},
];
let r = at(scenario(setup), 1, "threats");
r.threats[0].positionOnTrack = 13;
r = stepResolution(r);
assert.equal(r.threats[1].status, "active");
assert.equal(r.threats[1].positionOnTrack, 16);
let prevented = at(scenario(setup), 1, "crew");
prevented.threats[0].hp = 1;
prevented.threats[0].shield = 0;
execute(prevented, prevented.ship.crew[0], "A");
prevented = at(prevented, 1, "threats");
assert.deepEqual(
prevented.threats.map((t) => t.status),
["destroyed", "destroyed"],
);
});
test("heroic movement respects sealed doors while Teleporter crosses them", () => {
let r = at(scenario("I3-104"), 1, "crew");
r.threats[0].flags = ["sealed-red"];
execute(r, r.ship.crew[0], "teleport:red-lower");
assert.equal(r.ship.crew[0].station, "white-lower");
r.teleportTokens[0] = [0, 1];
r.ship.crew[1].station = "red-lower";
execute(r, r.ship.crew[0], "special:teleporter:basic");
assert.equal(r.ship.crew[0].station, "red-lower");
});
test("Hypernavigator jumps straight to final step, ignoring skipped threat spawns and resolving last rocket", () => {
let r = scenario([{ cardId: "E1-07", turn: 11, zone: "blue" }]);
r.programs[0][9] = { actions: ["special:hypernavigator:advanced"] };
r.ship.crew[0].station = "white-lower";
r.ship.computer = [true, true, true];
r = at(r, 10, "crew");
r.ship.rocketFlight = [{ launched: 10, strength: 3, crew: 1 }];
r = resolveAll(r);
assert.equal(r.turn, 13);
assert.equal(r.threats[0].status, "pending");
assert.ok(r.outcome);
assert.ok(!r.frames.some((f) => f.turn === 11 || f.turn === 12));
});
test("all missions set up with independent common/serious difficulty; future cards stay private", () => {
for (const mission of missionSummaries)
for (const difficulty of [1, 2, 3]) {
const s = createSession(
{
players: 4,
mission: getMission(mission.id),
gameOptions: {
seed: mission.id,
threatExpansion: true,
difficulty,
seriousDifficulty: 3,
},
},
0,
);
assert.equal(snapshot(s, 0).game.threats.length, 0);
assert.ok(!JSON.stringify(snapshot(s, 0)).includes("vortexCard"));
}
});
test("a delayed first half moves a protected later slot indirectly", () => {
let r = scenario(null);
r.programs[0][0] = { actions: ["lift"] };
r.programs[1][0] = { actions: ["lift", "A"] };
r.programs[1][1] = {
actions: ["special:special-ops:advanced", "B"],
protected: true,
};
r = at(r, 1, "damage");
assert.deepEqual(r.programs[1][1].actions, ["A"]);
assert.deepEqual(r.programs[1][2].actions, [
"special:special-ops:advanced",
"B",
]);
assert.equal(r.ship.zones.white.reactor, 3, "delayed pulse has not fired");
});
test("Vortex deck changes respect the protected action waiting to execute", () => {
let r = at(scenario("SI3-104"), 1, "crew");
r.ship.crew[0].station = r.threats[0].stations[0];
r.turnState.pendingProtected = [1];
const old = r.ship.crew[1].station;
execute(r, r.ship.crew[0], r.threats[0].repair);
assert.equal(r.ship.crew[1].station, old);
assert.notEqual(r.ship.crew[2].station, old);
});
test("called threats are public recursively but Vortex draws remain secret", () => {
const s = createSession(
{
players: 1,
mission: getMission("realmission1"),
gameOptions: { seed: "secrecy", threatExpansion: true },
},
0,
);
s.game.threats = [
{
cardId: "SE3-105",
instance: 0,
turn: 1,
zone: "white",
calledCard: {
cardId: "E3-107",
calledCard: { cardId: "SI3-104", vortexCard: { cardId: "I1-01" } },
},
},
];
const publicThreat = snapshot(s, 0).game.threats[0];
assert.equal(
publicThreat.calledCard.calledCard.card.name,
"Space-Time Vortex",
);
assert.equal(JSON.stringify(publicThreat).includes("vortexCard"), false);
assert.equal(
s.game.threats[0].calledCard.calledCard.vortexCard.cardId,
"I1-01",
"view must not mutate state",
);
});
test("last-turn double movement delay loses its second half", () => {
let r = scenario(null);
r.ship.computer = [true, true, true];
r.programs[0][11] = { actions: ["lift"] };
r.programs[1][11] = { actions: ["lift", "A"] };
r = at(r, 12, "damage");
assert.equal(r.ship.zones.white.reactor, 3);
assert.equal(r.turnState.fired.includes("white-lower"), false);
});
test("Ninja follows the publisher appendix: poison on appearance, through-movement exempt", () => {
let r = scenario("I2-102");
r.programs[0][0] = { actions: ["blue"] };
r.programs[1][0] = { actions: ["lift", "red"] };
r = at(r, 1, "damage");
assert.deepEqual(r.threats[0].affected, [0]);
assert.equal(r.ship.crew[0].knockedOut, false, "poison resolves later at Z");
});

404
test/game.test.js Normal file
View file

@ -0,0 +1,404 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
createSession,
submit,
advanceClock,
snapshot,
} from "../src/session.js";
import { getMission } from "../src/missions.js";
import { baseDeck, heroicDeck } from "../src/game/cards.js";
import {
beginResolution,
stepResolution,
resolveAll,
delay,
} from "../src/game/resolution.js";
import { TRACKS } from "../src/game/catalog.js";
const tracks = Object.fromEntries(
["red", "white", "blue", "internal"].map((z) => [z, TRACKS[0]]),
);
function scenario(programs = [], threats = [], extra = {}) {
return beginResolution({
crewSize: 4,
seed: "tests",
programs: Array.from({ length: 4 }, (_, p) =>
Array.from({ length: 12 }, (_, i) =>
programs[p]?.[i] ? { actions: programs[p][i] } : null,
),
),
threats,
tracks,
...extra,
});
}
function to(r, turn, step) {
while (!r.outcome && (r.turn !== turn || r.step !== step))
r = stepResolution(r);
return r;
}
function started(players = 4, options = {}) {
let s = createSession(
{
players,
mission: getMission("realmission1"),
gameOptions: { seed: "test", ...options },
},
0,
);
for (let p = 0; p < players; p++)
s = submit(s, p, { type: "ready", sequence: 1 }, 0).state;
return advanceClock(s, 3000);
}
const command = (s, p, c) =>
submit(s, p, { ...c, sequence: s.players[p].lastSequence + 1 }, s.observedAt);
test("base multiset and heroic station pairings are complete", () => {
assert.equal(baseDeck().length, 90);
assert.equal(new Set(baseDeck().map((c) => c.id)).size, 90);
assert.deepEqual(
["A", "B", "C", "bots"].map(
(a) => baseDeck().filter((c) => c.sides[0][0] === a).length,
),
[30, 24, 21, 15],
);
assert.equal(heroicDeck().length, 6);
});
test("phase packets are private, released once; editing never leaks card faces", () => {
let s = started();
const own = snapshot(s, 0);
assert.equal(own.game.hand.length, 5);
const card = own.game.hand[0];
let result = command(s, 0, {
type: "program",
crew: 0,
turn: 1,
cards: [{ id: card.id, side: 0 }],
slotVersion: 0,
});
assert.ok(result.accepted, result.error);
s = result.state;
const other = snapshot(s, 1),
spectator = snapshot(s);
assert.equal(other.game.programs[0][0].cards[0].sides, undefined);
assert.equal(spectator.game.hand.length, 0);
const encoded = JSON.stringify(other);
assert.ok(!encoded.includes("assignedThreats"));
assert.ok(!encoded.includes("damageDeck"));
assert.ok(!encoded.includes("packets"));
assert.ok(!encoded.includes('"seed"'));
s = command(s, 0, { type: "advance-phase" }).state;
assert.equal(s.game.hands[0].length, 9);
assert.equal(
command(s, 0, { type: "remove", crew: 0, turn: 1, slotVersion: 1 })
.accepted,
false,
);
s = advanceClock(s, s.missionStartAt + s.mission.phaseEndsMs[0]);
assert.equal(s.game.hands[0].length, 9);
});
test("android slot races reject stale edits and donations are irreversible", () => {
let s = started(2);
const c = s.game.hands[0].find((id) => s.game.cards[id].kind === "normal");
s = command(s, 0, {
type: "program",
crew: 2,
turn: 1,
cards: [{ id: c, side: 0 }],
slotVersion: 0,
}).state;
const other = s.game.hands[1].find(
(id) => s.game.cards[id].kind === "normal",
);
const before = structuredClone(s.game);
const result = command(s, 1, {
type: "program",
crew: 2,
turn: 1,
cards: [{ id: other, side: 0 }],
slotVersion: 0,
});
assert.equal(result.accepted, false);
assert.deepEqual(result.state.game, before);
assert.equal(
command(s, 0, { type: "remove", crew: 2, turn: 1, slotVersion: 1 })
.accepted,
false,
);
});
test("invalid second card rejects atomically without removing a first card", () => {
const s = started(),
before = structuredClone(s.game);
const result = command(s, 0, {
type: "program",
crew: 0,
turn: 1,
cards: [
{ id: s.game.hands[0][0], side: 0 },
{ id: "forged", side: 0 },
],
slotVersion: 0,
});
assert.equal(result.accepted, false);
assert.deepEqual(result.state.game, before);
});
test("one transfer per announcement; heroic cards and exact-beep transfers are rejected", () => {
let s = started();
const event = s.timeline.find((e) => e.type === "data-transfer");
s = advanceClock(s, s.missionStartAt + event.atMs);
const hero = s.game.hands[0].find((id) => s.game.cards[id].kind === "heroic");
assert.equal(
command(s, 0, { type: "transfer", card: hero, to: 1 }).accepted,
false,
);
const card = s.game.hands[0].find((id) => s.game.cards[id].kind === "normal");
s = command(s, 0, { type: "transfer", card, to: 1 }).state;
assert.ok(s.game.hands[1].includes(card));
assert.equal(
command(s, 0, { type: "transfer", card: s.game.hands[0][0], to: 1 })
.accepted,
false,
);
s = advanceClock(s, s.transferClosesAt);
assert.equal(
command(s, 1, { type: "transfer", card, to: 0 }).accepted,
false,
);
});
test("solo exposes its shared deck only to its player and allows android edits", () => {
let s = started(1);
assert.equal(s.game.hands[0].length, 90);
assert.equal(snapshot(s).game.hand.length, 0);
const c = s.game.hands[0][0];
s = command(s, 0, {
type: "program",
crew: 3,
turn: 1,
cards: [{ id: c, side: 0 }],
slotVersion: 0,
}).state;
assert.equal(
command(s, 0, { type: "remove", crew: 3, turn: 1, slotVersion: 1 })
.accepted,
true,
);
});
test("lasers combine before shields and cannot fire twice from the same station", () => {
let r = scenario(
[
[["red"], ["A"]],
[["red"], ["lift"], ["A"]],
],
[{ cardId: "E1-07", turn: 1, zone: "red" }],
);
r = to(r, 2, "threats");
assert.equal(r.threats[0].damage, 2);
assert.equal(r.ship.zones.red.reactor, 1);
let same = scenario([[["A"]], [["A"]]]);
same = to(same, 1, "damage");
assert.equal(same.ship.zones.white.reactor, 2);
assert.equal(same.turnState.shots.length, 1);
});
test("occupied lift delays the next action, with noncumulative delays", () => {
let r = scenario([[["lift"]], [["lift"], ["B"], ["A"]]]);
r = to(r, 1, "damage");
assert.equal(r.programs[1][1], null);
assert.deepEqual(r.programs[1][2].actions, ["B"]);
delay(r, r.ship.crew[1], 2);
assert.deepEqual(r.programs[1][2].actions, ["B"]);
});
test("first half of a double action delays just its remaining half", () => {
let r = scenario([[["lift"]], [["lift", "B"], ["A"]]], [], {
doubleActions: true,
});
r = to(r, 1, "damage");
assert.deepEqual(r.programs[1][1].actions, ["B"]);
assert.deepEqual(r.programs[1][2].actions, ["A"]);
assert.equal(r.ship.fuel, 3);
r = to(r, 2, "damage");
assert.equal(r.ship.fuel, 2);
});
test("computer must be maintained in first two turns of each phase", () => {
let r = scenario([[["C"]]], []);
r = to(r, 3, "crew");
assert.equal(r.ship.computer[0], true);
assert.equal(r.log.filter((e) => e.type === "computer-missed").length, 0);
const bad = to(scenario(), 3, "crew");
assert.equal(bad.log.filter((e) => e.type === "computer-missed").length, 1);
});
test("rocket takes one turn and the final rocket resolves before jumping", () => {
const r = scenario([], [{ cardId: "E1-07", turn: 12, zone: "blue" }]);
r.ship.rocketFlight.push({ launched: 12, strength: 3, crew: 0 });
const end = resolveAll(r);
assert.ok(end.log.some((e) => e.type === "threat-hit" && e.turn === 13));
assert.ok(end.outcome);
});
test("shield absorbs before hull damage, plasma knockout needs no absorption", () => {
let r = scenario([], [{ cardId: "E1-101", turn: 1, zone: "white" }]);
r = to(r, 2, "appear");
assert.equal(
r.ship.crew.some((p) => p.knockedOut),
false,
);
r = resolveAll(r);
assert.ok(r.ship.crew.some((p) => p.knockedOut));
});
test("cryoshield absorbs first volley regardless of strength", () => {
let r = scenario(
[[["A"], ["A"]]],
[{ cardId: "E1-06", turn: 1, zone: "white" }],
);
r = to(r, 1, "threats");
assert.equal(r.threats[0].damage, 0);
assert.ok(r.threats[0].flags.includes("cryo-broken"));
r = to(r, 2, "threats");
assert.equal(r.threats[0].status, "destroyed");
});
test("serialized resolution resumes identically and scores a shared outcome", () => {
const r = to(
scenario([[["C"]]], [{ cardId: "E1-07", turn: 1, zone: "red" }]),
3,
"damage",
);
assert.deepEqual(resolveAll(JSON.parse(JSON.stringify(r))), resolveAll(r));
const end = resolveAll(r);
assert.ok(Number.isFinite(end.outcome.score));
});
test("medic acts before captain and applies only to first subaction", () => {
let r = scenario([[["A", "B"]], [["special:medic:basic"]]], [], {
doubleActions: true,
});
r = to(r, 1, "damage");
assert.equal(r.turnState.shots[0].strength, 6);
assert.equal(r.ship.zones.white.shield, 3);
});
test("visual confirmation awards 1/2/3/5/7, taking only the best result each phase", () => {
for (let count = 1; count <= 5; count++) {
let r = scenario([], [], {
crewSize: 5,
programs: Array.from({ length: 5 }, (_, i) =>
Array.from({ length: 12 }, (_, turn) =>
i < count && turn < 2 ? { actions: ["C"] } : null,
),
),
});
for (const p of r.ship.crew) p.station = "white-lower";
r = to(r, 2, "damage");
assert.equal(r.ship.visual[0], [0, 1, 2, 3, 5, 7][count]);
}
});
test("heroic overcharge survives unrelated damage tiles", async () => {
const { damageShip } = await import("../src/game/resolution.js");
const r = scenario();
r.ship.zones.white.shield = 4;
r.ship.zones.white.reactor = 6;
r.ship.zones.white.damageDeck = ["shield", "structure"];
damageShip(r, "white", 1, "test");
assert.equal(r.ship.zones.white.shield, 4);
assert.equal(r.ship.zones.white.reactor, 6);
damageShip(r, "white", 1, "test");
assert.equal(r.ship.zones.white.shield, 2);
assert.equal(r.ship.zones.white.reactor, 6);
});
test("Medic protection follows the medic after teleport and does not protect robots", async () => {
const { knockout } = await import("../src/game/resolution.js");
let r = scenario(
[[["special:medic:advanced"]], [["special:teleporter:basic"]]],
[],
{
teleportTokens: [
[0, 0],
[0, 2],
],
},
);
r.ship.crew[2].station = "red-upper";
r.ship.crew[2].bots = 0;
r.ship.bots[0].owner = 2;
r = to(r, 1, "damage");
knockout(r, r.ship.crew[2], "test");
knockout(r, r.ship.crew[1], "test");
assert.equal(r.ship.crew[2].knockedOut, false);
assert.equal(r.ship.bots[0].disabled, true);
assert.equal(r.ship.crew[1].knockedOut, true);
assert.equal(r.ship.bonus, -1);
});
test("Special Ops protection ends after its action, but prevents earlier knockout", async () => {
const { knockout } = await import("../src/game/resolution.js");
let r = scenario([[], [["special:special-ops:advanced", "red"]]]);
r.programs[1][0].protected = true;
r = to(r, 1, "crew");
knockout(r, r.ship.crew[1], "before");
assert.equal(r.ship.crew[1].knockedOut, false);
r = to(r, 1, "damage");
knockout(r, r.ship.crew[1], "after");
assert.equal(r.ship.crew[1].knockedOut, true);
});
test("Contamination damages each affected station, including two in the same zone", () => {
let r = scenario([], [{ cardId: "SI2-04", turn: 1 }]);
r.tracks.internal = {
length: 10,
marks: [
[8, "Y"],
[1, "Z"],
],
};
r.threats[0].track = r.tracks.internal;
r = to(r, 1, "computer");
assert.equal(r.ship.zones.red.damage.length, 2);
assert.equal(r.ship.zones.blue.damage.length, 2);
});
test("all base threat cards resolve independently and leave finite resource/score values", async () => {
const { THREATS } = await import("../src/game/catalog.js");
for (const card of THREATS.filter((t) => !t.expansion)) {
const r = resolveAll(
scenario(
[],
[
{
cardId: card.id,
turn: 1,
...(card.position === "external" ? { zone: "white" } : {}),
},
],
),
);
assert.ok(r.outcome, card.id);
assert.ok(Number.isFinite(r.outcome.score), card.id);
for (const z of Object.values(r.ship.zones)) {
assert.ok(Number.isFinite(z.shield) && z.shield >= 0, card.id);
assert.ok(Number.isFinite(z.reactor) && z.reactor >= 0, card.id);
}
}
});
test("solo Teleporter tokens work for an android and replaced special cards return to their owner", () => {
let s = started(1, {
specializations: ["medic", "teleporter", "mechanic", "special-ops"].map(
(name) => ({ name, level: 3 }),
),
});
const result = command(s, 0, { type: "teleport", crew: 1, from: 0, to: 2 });
assert.ok(result.accepted, result.error);
s = result.state;
assert.deepEqual(s.game.teleportTokens[1], [0, 2]);
const special = s.game.androidCards.find(
(id) => s.game.cards[id].owner === 1,
);
s = command(s, 0, {
type: "program",
crew: 1,
turn: 1,
cards: [{ id: special, side: 0 }],
slotVersion: 0,
}).state;
const normal = s.game.hands[0][0];
s = command(s, 0, {
type: "program",
crew: 1,
turn: 1,
cards: [{ id: normal, side: 0 }],
slotVersion: 1,
}).state;
assert.ok(s.game.androidCards.includes(special));
assert.ok(!s.game.hands[0].includes(special));
});

View file

@ -56,3 +56,151 @@ test("local host shares state across seats and commits deadline changes on rejec
await once(server, "close"); await once(server, "close");
} }
}); });
test("private programs and career completion survive a host restart without duplicate rewards", async () => {
const { mkdtemp, readFile, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const dir = await mkdtemp(join(tmpdir(), "space-alert-host-"));
let now = 2000000,
server,
base;
const start = async () => {
server = createPreviewServer({
clock: () => now,
storagePath: join(dir, "state.json"),
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
base = `http://127.0.0.1:${server.address().port}`;
};
const stop = async () => {
const closed = once(server, "close");
server.close();
server.closeAllConnections();
await closed;
};
const post = async (path, data) => {
const r = await fetch(base + path + "?seat=0", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(data),
});
const v = await r.json();
assert.ok(r.ok, JSON.stringify(v));
return v;
};
const get = () => fetch(base + "/api/state?seat=0").then((r) => r.json());
try {
await start();
let view = await post("/api/career", {
type: "create",
name: "Test explorer",
cloning: true,
});
const id = view.explorers[0].id;
view = await post("/api/new", {
players: 1,
mission: "realmission1",
careerIds: [id],
gameOptions: { specializations: [null, null, null, null] },
});
let response = await post("/api/command", {
type: "ready",
sequence: view.nextSequence,
});
view = response.view;
now += 3000;
view = await get();
const card = view.game.hand.find((c) => c.sides.some((s) => s[0] === "C"));
response = await post("/api/command", {
type: "program",
sequence: view.nextSequence,
crew: 0,
turn: 1,
slotVersion: 0,
cards: [{ id: card.id, side: card.sides.findIndex((s) => s[0] === "C") }],
});
await stop();
await start();
view = await get();
assert.equal(view.game.programs[0][0].cards[0].id, card.id);
assert.equal(view.explorers[0].activeRun, true);
const spectator = await fetch(base + "/api/state").then((r) => r.json());
assert.equal(spectator.game.hand.length, 0);
assert.equal(spectator.game.programs[0][0].cards[0].id, undefined);
now += 3600000;
view = await get();
response = await post("/api/command", {
type: "resolve",
all: true,
sequence: view.nextSequence,
});
const explorer = response.view.explorers[0];
assert.equal(explorer.runs.length, 1);
assert.equal(explorer.activeRun, false);
await stop();
await start();
assert.deepEqual((await get()).explorers[0], explorer);
assert.deepEqual((await get()).explorers[0], explorer);
const saved = JSON.parse(await readFile(join(dir, "state.json"), "utf8"));
assert.equal(saved.explorers[id].runs.length, 1);
} finally {
if (server?.listening) await stop();
await rm(dir, { recursive: true, force: true });
}
});
test("untimed lessons advance only explicitly and remain paused after restart", async () => {
const { mkdtemp, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const dir = await mkdtemp(join(tmpdir(), "space-alert-lesson-"));
let now = 1000,
server,
base;
const start = async () => {
server = createPreviewServer({
clock: () => now,
storagePath: join(dir, "session.json"),
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
base = `http://127.0.0.1:${server.address().port}`;
};
const stop = async () => {
const done = once(server, "close");
server.close();
server.closeAllConnections();
await done;
};
const post = async (path, body = {}) => {
const r = await fetch(base + path + "?seat=0", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
assert.ok(r.ok);
return r.json();
};
try {
await start();
let view = await post("/api/lesson", { lesson: "first-shot" });
assert.equal(view.phase, 1);
now += 86400000;
view = await fetch(base + "/api/state?seat=0").then((r) => r.json());
assert.equal(view.phase, 1);
assert.equal(view.stage, "programming");
await stop();
await start();
view = await fetch(base + "/api/state?seat=0").then((r) => r.json());
assert.equal(view.phase, 1);
view = await post("/api/lesson-next");
assert.equal(view.phase, 2);
view = await post("/api/lesson-next");
assert.equal(view.stage, "resolution");
} finally {
if (server?.listening) await stop();
await rm(dir, { recursive: true, force: true });
}
});

201
test/progression.test.js Normal file
View file

@ -0,0 +1,201 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
createCampaign,
recordMission,
voteCampaign,
repairCampaign,
departCampaign,
} from "../src/game/campaign.js";
import { createShip } from "../src/game/resolution.js";
import {
createExplorer,
startExplorer,
settleExplorer,
consentToCloning,
learnSpecialization,
claimAchievement,
eligibleAchievements,
experienceFor,
LEVEL_BOXES,
HARDCORE_SKIPS,
ACHIEVEMENTS,
} from "../src/game/career.js";
function resolved() {
return {
ship: createShip(4, "campaign"),
threats: [],
outcome: {
survived: true,
score: 10,
threatPoints: 15,
visual: 5,
bonus: 1,
penalties: 11,
},
};
}
test("campaign repairs are ordered, limited per zone, and unavailable to knocked-out crew", () => {
let c = createCampaign("c");
const r = resolved();
r.ship.zones.red.damage = ["structure", "shield", "reactor"];
r.ship.bots[0].disabled = true;
r.ship.crew[1].knockedOut = true;
c = recordMission(c, r);
c = voteCampaign(c, 0, true, 2);
assert.equal(c.stage, "decision");
c = voteCampaign(c, 1, true, 2);
c = repairCampaign(c, { crew: 0, zone: "red", tile: "shield" });
assert.equal(c.repairCursor, 2);
assert.equal(c.repairs[1].type, "recover");
assert.throws(() => repairCampaign(c, { crew: 3, skip: true }));
c = repairCampaign(c, { crew: 2, zone: "red", tile: "reactor" });
assert.throws(
() => repairCampaign(c, { crew: 3, zone: "red", tile: "structure" }),
/two hull/,
);
c = repairCampaign(c, { crew: 3, bot: 0 });
assert.equal(c.stage, "ready");
c = departCampaign(c);
const ship = createShip(4, "next", c.carried);
assert.equal(ship.zones.red.carriedStructure, true);
assert.equal(ship.zones.red.shield, 1);
assert.equal(ship.bots[0].disabled, false);
});
test("ending a campaign scores unrepaired final damage, average visual and all threat/bonus points", () => {
let c = recordMission(createCampaign("c"), resolved());
c = voteCampaign(c, 0, false, 4);
assert.equal(c.stage, "complete");
assert.equal(c.outcome.score, 10);
assert.throws(() => repairCampaign(c, { crew: 0, skip: true }));
let two = createCampaign("two");
two.missions = [
{
result: {
survived: true,
threatPoints: 10,
visual: 4,
bonus: 1,
penalties: 9,
},
metadata: {},
},
];
two = recordMission(two, resolved());
two = voteCampaign(two, 0, false, 1);
assert.equal(two.outcome.score, 20);
const failure = resolved();
failure.outcome.survived = false;
failure.ship.destroyed = true;
const lost = recordMission(createCampaign("lost"), failure);
assert.equal(lost.outcome.score, 0);
});
test("unrepaired robots stay off ship and a lone usable squad has a chosen initial station", () => {
const carried = {
zones: { red: ["shield", "reactor"], white: [], blue: [] },
disabledBots: [true, false],
botStation: "blue-upper",
};
const ship = createShip(4, "s", carried);
assert.equal(ship.zones.red.shield, 0);
assert.equal(ship.zones.red.reactor, 1);
assert.equal(ship.bots[0].station, null);
assert.equal(ship.bots[1].station, "blue-upper");
});
function success(id, score = 60) {
return {
id,
at: 1000,
survived: true,
score,
count: 1,
limit: 3,
humans: 4,
penalties: 0,
missions: [
{
humans: 4,
crew: 4,
doubleActions: false,
difficulty: 1,
seriousDifficulty: 1,
threatCount: 7,
penalties: 0,
},
],
};
}
test("experience is idempotent, rejects mismatched results and gives no training XP", () => {
let e = startExplorer(createExplorer("eli", "Eli"), "m");
assert.throws(() => settleExplorer(e, success("other")));
e = settleExplorer(e, success("m"));
assert.equal(e.xp, 8);
assert.equal(e.level, 1);
assert.deepEqual(settleExplorer(e, success("m")), e);
assert.throws(() => startExplorer(e, "next"), /Choose earned/);
e = learnSpecialization(e, "medic");
assert.equal(e.specializations.medic, 1);
e = startExplorer(e, "training");
e = settleExplorer(e, { ...success("training", 999), training: true });
assert.equal(e.xp, 8);
assert.equal(experienceFor(59, 2, 3), 11);
assert.equal(experienceFor(59, 3, 3), 17);
assert.equal(experienceFor(-5), 2);
});
test("hardcore skips dotted boxes only once a following blank is marked; cloning is permanent", () => {
assert.deepEqual(LEVEL_BOXES.slice(0, 4), [8, 12, 16, 20]);
assert.deepEqual(HARDCORE_SKIPS.slice(0, 8), [0, 0, 4, 7, 10, 13, 16, 18]);
let e = createExplorer("x", "X", false);
e.level = 2;
e.specializations = { medic: 1, mechanic: 1 };
e = startExplorer(e, "one");
e = settleExplorer(e, success("one", 0));
assert.equal(e.boxes, 6);
e = consentToCloning(e);
assert.equal(e.boxes, 6);
e = startExplorer(e, "two");
assert.throws(() => consentToCloning(e));
e = settleExplorer(e, { ...success("two"), survived: false });
assert.equal(e.dead, false);
assert.equal(e.clones, 1);
assert.equal(e.xp, 2);
let hardcore = startExplorer(createExplorer("y", "Y", false), "lost");
hardcore = settleExplorer(hardcore, { ...success("lost"), survived: false });
assert.equal(hardcore.dead, true);
assert.throws(() => startExplorer(hardcore, "again"));
});
test("achievements require pre-mission level, category choice and crew judgment when applicable", () => {
let e = settleExplorer(
startExplorer(createExplorer("x", "X"), "one"),
success("one"),
);
assert.ok(
eligibleAchievements(e, "one").some((a) => a.id === "fantastic-four"),
);
assert.ok(
!eligibleAchievements(e, "one").some((a) => a.id === "perfect-double"),
);
e = claimAchievement(e, "one", "fantastic-four");
assert.equal(e.xp, 11);
assert.throws(() => claimAchievement(e, "one", "not-even-a-scratch"));
assert.throws(() => claimAchievement(e, "one", "duck"));
e = claimAchievement(e, "one", "duck", { crewAgrees: true });
assert.equal(e.xp, 12);
assert.equal(
new Set(ACHIEVEMENTS.map((a) => a.id)).size,
ACHIEVEMENTS.length,
);
});
test("specialization upgrades enforce the level when each point was earned", () => {
let e = createExplorer("x", "X");
e.level = 6;
e = learnSpecialization(e, "medic");
assert.throws(() => learnSpecialization(e, "medic"));
e = learnSpecialization(e, "mechanic");
e = learnSpecialization(e, "medic");
assert.throws(() => learnSpecialization(e, "medic"));
e = learnSpecialization(e, "teleporter");
e = learnSpecialization(e, "rocketeer");
e = learnSpecialization(e, "medic");
assert.equal(e.specializations.medic, 3);
});

121
test/tutorials.test.js Normal file
View file

@ -0,0 +1,121 @@
import test from "node:test";
import assert from "node:assert/strict";
import { LESSONS, createLesson } from "../src/tutorials.js";
import { submit, advanceClock } from "../src/session.js";
import {
traitDescriptions,
effectDescription,
eventDescription,
} from "../preview/text.js";
import { THREATS } from "../src/game/catalog.js";
function program(s, crew, turn, actions) {
const g = s.game;
const id = [...g.hands[0], ...g.androidCards].find(
(id) =>
(g.cards[id].owner === undefined || g.cards[id].owner === crew) &&
g.cards[id].sides.some(
(a) => JSON.stringify(a) === JSON.stringify(actions),
),
);
assert.ok(id, `Missing ${actions}`);
const side = g.cards[id].sides.findIndex(
(a) => JSON.stringify(a) === JSON.stringify(actions),
);
const result = submit(
s,
0,
{
type: "program",
sequence: s.players[0].lastSequence + 1,
crew,
turn,
slotVersion: g.slotVersions[crew][turn - 1],
cards: [{ id, side }],
},
s.observedAt,
);
assert.equal(result.accepted, true, result.error);
return result.state;
}
const next = (s) =>
advanceClock(s, s.missionStartAt + s.mission.phaseEndsMs[s.phase - 1]);
function resolve(s) {
while (s.stage === "programming") s = next(s);
return submit(
s,
0,
{ type: "resolve", all: true, sequence: s.players[0].lastSequence + 1 },
s.observedAt,
).state.game.resolution;
}
test("all lessons preserve physical cards and resolve through the real engine", () => {
for (const l of LESSONS) {
const s = createLesson(l.id, 1000);
const ids = [
...s.game.hands[0],
...s.game.androidCards,
...s.game.programs
.flat()
.filter(Boolean)
.flatMap((x) => x.cards.map((c) => c.id)),
];
assert.equal(new Set(ids).size, ids.length, l.id);
assert.ok(resolve(s).outcome);
}
});
test("first-shot exercise destroys the fighter with the recommended two shots", () => {
let s = createLesson("first-shot", 0);
s = program(s, 0, 2, ["A"]);
s = program(s, 0, 3, ["A"]);
const r = resolve(s);
assert.equal(r.threats[0].status, "destroyed");
assert.equal(r.ship.zones.white.damage.length, 0);
});
test("energy exercise demonstrates the fourth shot failing without refueling", () => {
function run(refill) {
let s = createLesson("energy", 0);
for (const n of [1, 2, 3]) s = program(s, 0, n, ["A"]);
if (refill) {
s = program(s, 2, 1, ["lift"]);
s = program(s, 2, 2, ["B"]);
}
s = next(s);
s = program(s, 0, 4, ["A"]);
return resolve(s);
}
assert.equal(run(false).log.filter((e) => e.type === "fire").length, 3);
const r = run(true);
assert.equal(r.log.filter((e) => e.type === "fire").length, 4);
assert.equal(r.ship.fuel, 2);
});
test("repair exercise fixes Hacked Shields before its terminal effect", () => {
let s = createLesson("repairs", 0);
s = program(s, 0, 1, ["blue"]);
s = program(s, 0, 2, ["B"]);
s = program(s, 0, 3, ["B"]);
s = next(s);
s = program(s, 0, 4, ["B"]);
const r = resolve(s);
assert.equal(r.threats[0].status, "destroyed");
assert.equal(r.log.filter((e) => e.type === "repair").length, 3);
});
test("every catalogue effect has explanatory FR and EN text, and replay names work", () => {
for (const t of THREATS)
for (const locale of ["fr", "en"]) {
for (const e of Object.values(t.effects).flat())
assert.notEqual(
effectDescription(e, locale),
e.type,
`${t.id}/${e.type}/${locale}`,
);
assert.ok(
traitDescriptions(t, locale).every((s) => typeof s === "string"),
);
}
assert.match(
eventDescription({ type: "threat-destroyed", threat: 0 }, "fr", [
{ instance: 0, name: "Fighter" },
]),
/Fighter/,
);
});