Keep auto-charge and planning in Gaia’s action bar (#334)
* Improve premoves and fix random auctions and Ivits exploration * Fix blocked legacy random-faction sealed auctions * Allow premoves for initial building and booster choices * Compact setup actions and show ship explorers * Restore auto-charge controls in Gaia game UI * Use published player-settings protocol 0.3.4 * Allow verified protocol 0.3.4 during release-age quarantine * Keep planning and auto-charge in the action bar outside your turn * Bump viewer to 5.20.6 for action bar release
This commit is contained in:
parent
cfed58ed68
commit
85a516040f
94 changed files with 3923 additions and 6864 deletions
91
docs/bgs-premoves.md
Normal file
91
docs/bgs-premoves.md
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
# BGS premoves
|
||||
|
||||
Players compose turns in the existing Planning mode, then submit up to three complete turns.
|
||||
On their own turn the first plays immediately; otherwise it waits. The remaining turns run
|
||||
server-side when the player becomes active, including when their browser is closed.
|
||||
The queue above the board is private and can be inspected or cancelled during live play or
|
||||
while composing another planning line, or reviewing an earlier turn. Cancelling a later move also removes its successors.
|
||||
|
||||
## Execution and BGS protocol
|
||||
|
||||
`engine/wrapper.ts` uses the existing protocol hooks. No new protocol version is needed:
|
||||
|
||||
- `canMoveOutOfTurn` permits a seated player to submit a `premoves` command.
|
||||
- `isLiveUpdate` marks changes to the queue so BGS saves them without advancing clocks,
|
||||
notifications or the public move log. A queue command that executes a turn is a normal save.
|
||||
- `timeIncrements` returns monotonic per-seat counters. Each completed manual decision or
|
||||
executed premove earns one increment; automatic charging and queue edits earn none. Undo keeps
|
||||
the counters and clears queues, so replaying the log cannot generate extra increments.
|
||||
- `stripSecret` includes only the requesting player's plan, including through `logSlice`.
|
||||
|
||||
`automation` is optional on old saved games. It is initialized with zero counters so upgrading
|
||||
an existing game does not retrospectively credit turns. The primary viewer enables its queue
|
||||
only when this engine capability is present. The alternate viewer can continue making normal moves.
|
||||
|
||||
The engine resolves automatic charging/income first. A manual decision waits for the player and
|
||||
retains their queue. Each premove is checked against a disposable copy of the current board
|
||||
before being applied, so an unavailable action or a failed later command cannot spend resources.
|
||||
An illegal turn stops the remaining queue and leaves a private explanation. Queues survive passing
|
||||
and round changes; each move records its intended round and phase. Unplanned manual income or Gaia
|
||||
choices wait for the player, while planned income choices can execute automatically. Income already
|
||||
resolved by the normal auto-income setting is not applied twice. Dropping the seat or ending the
|
||||
game clears the queue.
|
||||
|
||||
Initial building placements and booster choices can also be queued once factions are assigned.
|
||||
`setupPremoves` advertises this capability. The queue contains only the player's own choices;
|
||||
opponents' hypothetical setup moves stay in the preview. Each queued choice is checked again
|
||||
on the real board when its setup turn arrives, including whether its planet or booster is available.
|
||||
|
||||
Commands carry the seat's setup/main-turn counter, round, queue revision and request ID. This rejects
|
||||
stale replacements and makes retries idempotent. Automatic leech does not stale a plan. Cancelling
|
||||
an existing suffix remains possible even when the retained prefix has become illegal.
|
||||
|
||||
The optional `timings` array is additive: older queues default to their recorded round's move phase,
|
||||
and older viewers' new submissions infer a new round after passing. `roundPremoves` advertises the
|
||||
new scheduling capability without a new BGS protocol release. Future-round legality is checked
|
||||
atomically on execution because the intervening income and board changes are not known at submission.
|
||||
|
||||
## Sandbox and live updates
|
||||
|
||||
Planning is the single composer and enforces the simulated position’s resource costs. Future turns can use simulated income or explicit charges; each is checked
|
||||
with actual resources when its turn arrives. Simulated charges are never commands or conditions.
|
||||
The queue stops immediately if the next turn is illegal, without waiting for a charge. An immediately
|
||||
played turn must already be affordable. A simulated-neighbour Trading Station keeps the `cheap`
|
||||
qualifier as a 3-credit ceiling: the engine checks the actual upgrade cost and stops if that price
|
||||
is unavailable, even if the player could afford 6 credits. It never grants a discount. The entire plan
|
||||
is sent atomically. Saving or cancelling a queue keeps the local plans and variations.
|
||||
Submitting a new plan replaces the existing queue, with confirmation before submission.
|
||||
|
||||
Real moves trim matching prefixes from every local variation, whether played manually or by a
|
||||
premove. Repeated actions such as research are matched against actual move history, not inferred
|
||||
from whether they remain legal. Simulation charges attached to a played turn are removed with it.
|
||||
Unrelated or invalid alternatives are preserved for editing. Reopening a saved plan after a reload
|
||||
applies the same reconciliation. A rollback requires explicit recovery instead of guessing.
|
||||
|
||||
Incoming turns and automatic charging rebase the simulation without closing it. Opponent updates
|
||||
preserve the partly composed current turn; your own real turn clears that unfinished preview. Queue changes update the real backup without clearing the draft.
|
||||
Local sandbox saves are scoped by the initial game move (BGS's game seed/name) and player seat,
|
||||
since BGS uses the same iframe URL for multiple games. Old unscoped BGS drafts are not restored
|
||||
into an arbitrary game.
|
||||
|
||||
## Local preview
|
||||
|
||||
```sh
|
||||
npm --prefix engine run build
|
||||
npm --prefix viewer run package
|
||||
npm --prefix viewer run premove:preview
|
||||
```
|
||||
|
||||
Open <http://127.0.0.1:5201/>. This small local host uses the built viewer and real engine wrapper;
|
||||
its state stays in server memory until the preview process restarts. It does not access a BGS database.
|
||||
|
||||
1. Choose **Plan a move**, use the normal controls, and finish the simulated turn.
|
||||
2. Choose **Queue moves**, then confirm. Reload: the private queue remains.
|
||||
3. **View on board** opens the queued line; cancelling it keeps an unrelated sandbox draft.
|
||||
4. **Play opponent's turn** upgrades Alex's adjacent mine, resolves your automatic charging,
|
||||
then executes your premove.
|
||||
5. **Other player's view** shows that seat's own queue, never yours. **Reset position** starts over.
|
||||
|
||||
Engine tests cover privacy, stale requests, chains, manual and automatic charging, atomic failure,
|
||||
cancellation and replay counters. The retained contention tests exercise occupied planets,
|
||||
research caps, federation and advanced technology tokens, and Lost Fleet space stations.
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
> **Archived:** this plan describes the retired standalone Lost Fleet host. BGS uses the
|
||||
> engine-owned queue documented in [BGS premoves](../bgs-premoves.md), with the sandbox as its
|
||||
> only composer. The separate editor, cancellation triggers and Supabase transport were removed.
|
||||
|
||||
# Premove — Implementation Plan (consolidated, ready for handoff)
|
||||
|
||||
> Status: **design finalized + reviewed, nothing built yet.** Originally written 2026-07-04 and
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@gaia-project/engine",
|
||||
"version": "4.12.2",
|
||||
"version": "4.14.5",
|
||||
"description": "Javascript engine for project gaia",
|
||||
"main": "dist/index.js",
|
||||
"types": "index.ts",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { expect } from "chai";
|
||||
import { EngineLike, resolvePremoveQueue } from "../viewer/src/logic/premove-resolver";
|
||||
import Engine from "./src/engine";
|
||||
import {
|
||||
AdvTechTile,
|
||||
|
|
@ -15,6 +14,7 @@ import {
|
|||
} from "./src/enums";
|
||||
import { GaiaHex } from "./src/gaia-hex";
|
||||
import { Power } from "./src/player-data";
|
||||
import { automation, playNextPremove } from "./src/premoves";
|
||||
|
||||
const parseMoves = Engine.parseMoves;
|
||||
|
||||
|
|
@ -86,8 +86,14 @@ function occupyPlanetsOfDistinctTypes(engine: Engine, player: PlayerEnum, count:
|
|||
// federation-eligibility CACHE specifically, as opposed to just making the move illegal outright)
|
||||
// would need a purpose-built fixture isolating that cache and wasn't reached this session.
|
||||
|
||||
function cloneEngineLike(engine: Engine): EngineLike {
|
||||
return Engine.fromData(JSON.parse(JSON.stringify(engine))) as unknown as EngineLike;
|
||||
function resolvePremoveQueue(clone: () => Engine, seat: number, rows: { seq: number; move: string }[], _mode: string) {
|
||||
const engine = clone();
|
||||
automation(engine).plans[seat] = { moves: rows.map((row) => row.move), round: engine.round, revision: 1 };
|
||||
const played = playNextPremove(engine);
|
||||
return { outcome: played ? "success" : "failed", reason: engine.automation.plans[seat].notice?.text };
|
||||
}
|
||||
function cloneEngineLike(engine: Engine): Engine {
|
||||
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
}
|
||||
|
||||
describe("Premove race-condition regressions (#69 audit)", () => {
|
||||
|
|
|
|||
456
engine/premoves.spec.ts
Normal file
456
engine/premoves.spec.ts
Normal file
|
|
@ -0,0 +1,456 @@
|
|||
import { expect } from "chai";
|
||||
import Engine from "./src/engine";
|
||||
import { Phase } from "./src/enums";
|
||||
import { automation, PremoveCommand } from "./src/premoves";
|
||||
import {
|
||||
automove,
|
||||
canMoveOutOfTurn,
|
||||
isLiveUpdate,
|
||||
logSlice,
|
||||
move,
|
||||
replay,
|
||||
setPlayerSettings,
|
||||
stripSecret,
|
||||
timeIncrements,
|
||||
toSave,
|
||||
} from "./wrapper";
|
||||
|
||||
const setup = Engine.parseMoves(`
|
||||
init 2 randomSeed
|
||||
p1 faction terrans
|
||||
p2 faction nevlas
|
||||
terrans build m -1x2
|
||||
nevlas build m -1x0
|
||||
nevlas build m 0x-4
|
||||
terrans build m -4x-1
|
||||
nevlas booster booster7
|
||||
terrans booster booster3
|
||||
`);
|
||||
let request = 0;
|
||||
function game() {
|
||||
return new Engine(setup);
|
||||
}
|
||||
function command(engine: Engine, seat: number, moves: string[]): PremoveCommand {
|
||||
return {
|
||||
type: "premoves",
|
||||
requestId: `test-${++request}`,
|
||||
moves,
|
||||
revision: engine.automation?.plans[seat]?.revision ?? 0,
|
||||
round: engine.round,
|
||||
turn: engine.automation?.turns[seat] ?? 0,
|
||||
};
|
||||
}
|
||||
function queue(engine: Engine, seat: number, moves: string[]) {
|
||||
return move(engine, command(engine, seat, moves), seat);
|
||||
}
|
||||
function json(engine: Engine): Engine {
|
||||
return JSON.parse(JSON.stringify(engine));
|
||||
}
|
||||
|
||||
describe("BGS premoves", () => {
|
||||
it("queues a second starting mine off turn without simulating other players in the real game", () => {
|
||||
let engine = new Engine(setup.slice(0, 4));
|
||||
const history = [...engine.moveHistory];
|
||||
const queued = command(engine, 0, ["terrans build m -4x-1"]);
|
||||
queued.timings = [{ round: 0, phase: Phase.SetupBuilding }];
|
||||
expect(canMoveOutOfTurn(json(engine), queued, 0)).to.equal(true);
|
||||
engine = move(json(engine), queued, 0);
|
||||
expect(isLiveUpdate(engine)).to.equal(true);
|
||||
expect(engine.moveHistory).to.deep.equal(history);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
|
||||
expect(stripSecret(engine, 1).automation.plans).to.deep.equal({});
|
||||
engine = move(json(engine), "nevlas build m -1x0", 1);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(1);
|
||||
engine = move(json(engine), "nevlas build m 0x-4", 1);
|
||||
expect(engine.moveHistory.slice(-1)).to.deep.equal(["terrans build m -4x-1"]);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(engine.phase).to.equal(Phase.SetupBooster);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 2]);
|
||||
expect(engine.automation.turns).to.deep.equal([1, 2]);
|
||||
automove(engine);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 2]);
|
||||
});
|
||||
|
||||
it("can cancel a starting placement and rejects a submission stale after a manual placement", () => {
|
||||
let engine = new Engine(setup.slice(0, 4));
|
||||
const stale = command(engine, 0, ["terrans build m -4x-1"]);
|
||||
engine = queue(engine, 0, ["terrans build m -4x-1"]);
|
||||
engine = queue(engine, 0, []);
|
||||
engine = move(json(engine), "nevlas build m -1x0", 1);
|
||||
engine = move(json(engine), "nevlas build m 0x-4", 1);
|
||||
expect(engine.playerToMove).to.equal(0);
|
||||
expect(engine.players[0].data.occupied).to.have.length(1);
|
||||
engine = move(json(engine), "terrans build m -4x-1", 0);
|
||||
stale.revision = engine.automation.plans[0].revision;
|
||||
stale.timings = [{ round: 0, phase: Phase.SetupBooster }];
|
||||
stale.moves = ["terrans booster booster3"];
|
||||
expect(() => move(json(engine), stale, 0)).to.throw("turn has changed");
|
||||
});
|
||||
|
||||
it("stops an unavailable setup placement without making an alternative move", () => {
|
||||
let engine = new Engine(setup.slice(0, 4));
|
||||
engine = queue(engine, 0, ["terrans build m -1x2"]);
|
||||
engine = move(json(engine), "nevlas build m -1x0", 1);
|
||||
engine = move(json(engine), "nevlas build m 0x-4", 1);
|
||||
expect(engine.playerToMove).to.equal(0);
|
||||
expect(engine.players[0].data.occupied).to.have.length(1);
|
||||
expect(engine.automation.plans[0].notice.kind).to.equal("stopped");
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 2]);
|
||||
});
|
||||
|
||||
it("waits for the initial booster pick after a queued mine, then rechecks availability", () => {
|
||||
let engine = new Engine(setup.slice(0, 4));
|
||||
const cmd = command(engine, 0, ["terrans build m -4x-1", "terrans booster booster7"]);
|
||||
cmd.timings = [
|
||||
{ round: 0, phase: Phase.SetupBuilding },
|
||||
{ round: 0, phase: Phase.SetupBooster },
|
||||
];
|
||||
engine = move(json(engine), cmd, 0);
|
||||
engine = move(json(engine), "nevlas build m -1x0", 1);
|
||||
engine = move(json(engine), "nevlas build m 0x-4", 1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal(["terrans booster booster7"]);
|
||||
engine = move(json(engine), "nevlas booster booster7", 1);
|
||||
expect(engine.phase).to.equal(Phase.SetupBooster);
|
||||
expect(engine.playerToMove).to.equal(0);
|
||||
expect(engine.automation.plans[0].notice.kind).to.equal("stopped");
|
||||
expect(engine.players[0].data.tiles.booster).to.equal(null);
|
||||
});
|
||||
|
||||
it("keeps a setup queue through income into round one without adding invented setup moves", () => {
|
||||
let engine = new Engine(setup.slice(0, 4));
|
||||
const cmd = command(engine, 0, ["terrans build m -4x-1", "terrans booster booster3", "terrans up nav."]);
|
||||
cmd.timings = [
|
||||
{ round: 0, phase: Phase.SetupBuilding },
|
||||
{ round: 0, phase: Phase.SetupBooster },
|
||||
{ round: 1, phase: Phase.RoundMove },
|
||||
];
|
||||
engine = move(json(engine), cmd, 0);
|
||||
engine = move(json(engine), "nevlas build m -1x0", 1);
|
||||
engine = move(json(engine), "nevlas build m 0x-4", 1);
|
||||
engine = move(json(engine), "nevlas booster booster7", 1);
|
||||
expect(engine.phase).to.equal(Phase.RoundMove);
|
||||
expect(engine.round).to.equal(1);
|
||||
expect(engine.moveHistory).to.deep.equal(new Engine([...setup, "terrans up nav."]).moveHistory);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([3, 3]);
|
||||
});
|
||||
|
||||
it("rejects premoves before faction selection and setup timings in a running round", () => {
|
||||
expect(() => queue(new Engine(setup.slice(0, 1)), 0, ["p1 faction terrans"])).to.throw("after faction selection");
|
||||
const engine = new Engine(setup.slice(0, 4));
|
||||
const cmd = command(engine, 0, ["terrans build m -4x-1"]);
|
||||
cmd.timings = [{ round: 1, phase: Phase.SetupBuilding }];
|
||||
expect(() => move(json(engine), cmd, 0)).to.throw("Invalid premove schedule");
|
||||
cmd.timings = [{ round: 0, phase: Phase.RoundMove }];
|
||||
expect(() => move(json(engine), cmd, 0)).to.throw("Invalid premove schedule");
|
||||
});
|
||||
|
||||
it("keeps the 3c Trading Station constraint and executes after a real neighbour arrives", () => {
|
||||
let engine = game();
|
||||
Object.assign(engine.players[0].data, { ores: 20, credits: 20, qics: 10 });
|
||||
setPlayerSettings(engine, 1, { autoCharge: "2" });
|
||||
const credits = engine.players[1].data.credits;
|
||||
engine = queue(engine, 1, ["nevlas build ts 4A11 cheap."]);
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal(["nevlas build ts 4A11 cheap."]);
|
||||
expect(engine.players[1].data.credits).to.equal(credits);
|
||||
engine = move(json(engine), "terrans build m 4B0.", 0);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("played");
|
||||
expect(engine.players[1].data.credits).to.equal(credits - 3);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
});
|
||||
|
||||
it("stops an isolated 3c-only upgrade atomically instead of spending 6c", () => {
|
||||
let engine = game();
|
||||
const credits = engine.players[1].data.credits;
|
||||
const qics = engine.players[1].data.qics;
|
||||
const ores = engine.players[1].data.ores;
|
||||
expect(credits).to.be.at.least(6);
|
||||
engine = queue(engine, 1, ["nevlas spend 1q for 1o. build ts 4A11 cheap."]);
|
||||
engine = move(json(engine), "terrans up nav.", 0);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
|
||||
expect(engine.automation.plans[1].notice.text).to.contain("not available for 3c");
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal([]);
|
||||
expect(engine.players[1].data.credits).to.equal(credits);
|
||||
expect(engine.players[1].data.qics).to.equal(qics);
|
||||
expect(engine.players[1].data.ores).to.equal(ores);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
|
||||
});
|
||||
|
||||
it("can queue a power spend before a charge, then uses real autoleech when the turn arrives", () => {
|
||||
let engine = game();
|
||||
Object.assign(engine.players[1].data.power, { area1: 0, area2: 1, area3: 0 });
|
||||
setPlayerSettings(engine, 1, { autoCharge: "2" });
|
||||
const credits = engine.players[1].data.credits;
|
||||
engine = queue(engine, 1, ["nevlas spend 1pw for 1c. up nav."]);
|
||||
expect(engine.players[1].data.power.area3).to.equal(0);
|
||||
expect(engine.players[1].data.credits).to.equal(credits);
|
||||
expect(engine.players[1].data.analysis).to.equal(false);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
|
||||
engine = move(json(engine), "terrans build ts -1x2.", 0);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("played");
|
||||
expect(engine.players[1].data.credits).to.equal(credits + 1);
|
||||
expect(engine.players[1].data.power.area3).to.equal(0);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
});
|
||||
|
||||
it("stops instead of waiting or fabricating power when the anticipated charge never arrives", () => {
|
||||
let engine = game();
|
||||
Object.assign(engine.players[1].data.power, { area1: 0, area2: 1, area3: 0 });
|
||||
const credits = engine.players[1].data.credits;
|
||||
engine = queue(engine, 1, ["nevlas spend 1pw for 1c. up nav."]);
|
||||
engine = move(json(engine), "terrans up nav.", 0);
|
||||
expect(engine.playerToMove).to.equal(1);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal([]);
|
||||
expect(engine.players[1].data.power.area3).to.equal(0);
|
||||
expect(engine.players[1].data.credits).to.equal(credits);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
|
||||
});
|
||||
|
||||
it("still rejects an unaffordable move submitted to play immediately", () => {
|
||||
const engine = game();
|
||||
engine.players[0].data.knowledge = 0;
|
||||
expect(() => queue(engine, 0, ["terrans up nav."])).to.throw();
|
||||
expect(engine.players[0].data.knowledge).to.equal(0);
|
||||
});
|
||||
|
||||
it("saves a private off-turn queue without changing turns, logs or clocks", () => {
|
||||
let engine = game();
|
||||
const before = engine.moveHistory.length;
|
||||
const cmd = command(engine, 1, ["nevlas up nav."]);
|
||||
expect(canMoveOutOfTurn(json(engine), cmd, 1)).to.equal(true);
|
||||
engine = move(json(engine), cmd, 1);
|
||||
expect(toSave(engine)).to.equal(engine);
|
||||
expect(isLiveUpdate(engine)).to.equal(true);
|
||||
expect(engine.playerToMove).to.equal(0);
|
||||
expect(engine.moveHistory.length).to.equal(before);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
|
||||
expect(stripSecret(engine, 1).automation.plans[1].moves).to.deep.equal(cmd.moves);
|
||||
expect(stripSecret(engine, 0).automation.plans).to.deep.equal({});
|
||||
expect(logSlice(engine).state.automation.plans).to.deep.equal({});
|
||||
});
|
||||
it("runs the queue after auto-leech and awards each completed main turn exactly once", () => {
|
||||
let engine = queue(game(), 1, ["nevlas up nav."]);
|
||||
engine = move(json(engine), "terrans build ts -1x2.", 0);
|
||||
expect(engine.moveHistory.slice(-3)[1]).to.match(/^nevlas charge/);
|
||||
expect(engine.moveHistory.slice(-1)[0]).to.match(/^nevlas up nav/);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
expect(isLiveUpdate(engine)).to.equal(false);
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal([]);
|
||||
automove(engine);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
});
|
||||
it("keeps a queue through a manual charge decision and executes after it", () => {
|
||||
let engine = game();
|
||||
engine.move("terrans build ts -1x2.");
|
||||
automove(engine);
|
||||
engine.move("nevlas build ts -1x0.");
|
||||
expect(engine.phase).to.equal(Phase.RoundLeech);
|
||||
engine = queue(engine, 0, ["terrans up nav."]);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(1);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
|
||||
engine = move(json(engine), "terrans charge 2pw", 0);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(0);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 0]);
|
||||
expect(engine.automation.turns).to.deep.equal([1, 0]);
|
||||
});
|
||||
it("runs several seats' queues, with autoleech between them", () => {
|
||||
let engine = queue(game(), 1, ["nevlas build ts -1x0."]);
|
||||
setPlayerSettings(engine, 0, { autoCharge: "2" });
|
||||
engine = queue(engine, 0, ["terrans build ts -1x2.", "terrans up nav."]);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(0);
|
||||
expect(engine.automation.plans[1].moves).to.have.length(0);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
|
||||
});
|
||||
it("stops an illegal chain atomically, leaving the resources and active turn intact", () => {
|
||||
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas build ts -1x0."]);
|
||||
engine.players[1].data.knowledge = 0;
|
||||
const wallet = engine.players[1].data.ores;
|
||||
engine = move(json(engine), "terrans up nav.", 0);
|
||||
expect(engine.playerToMove).to.equal(1);
|
||||
expect(engine.players[1].data.ores).to.equal(wallet);
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal([]);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
|
||||
});
|
||||
it("rejects another seat's moves, incomplete plans, stale turns and stale queue edits", () => {
|
||||
const engine = game();
|
||||
expect(() => queue(engine, 1, ["terrans up nav."])).to.throw("own moves");
|
||||
expect(() => queue(engine, 1, ["nevlas burn 1"])).to.throw();
|
||||
const stale = command(engine, 1, ["nevlas up nav."]);
|
||||
queue(engine, 1, ["nevlas up terra."]);
|
||||
expect(() => move(engine, stale, 1)).to.throw("queue changed");
|
||||
const turn = command(engine, 1, ["nevlas up nav."]);
|
||||
automation(engine).turns[1]++;
|
||||
expect(() => move(engine, turn, 1)).to.throw("turn has changed");
|
||||
expect(canMoveOutOfTurn(engine, "nevlas up nav.", 1)).to.equal(false);
|
||||
expect(canMoveOutOfTurn(engine, stale, -1)).to.equal(false);
|
||||
});
|
||||
it("makes duplicate submissions harmless, even after the move has executed", () => {
|
||||
let engine = game();
|
||||
const cmd = command(engine, 0, ["terrans up nav."]);
|
||||
engine = move(engine, cmd, 0);
|
||||
const history = [...engine.moveHistory];
|
||||
engine = move(json(engine), cmd, 0);
|
||||
expect(engine.moveHistory).to.deep.equal(history);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(0);
|
||||
});
|
||||
|
||||
it("rolls back free conversions when a later command in the same premove becomes illegal", () => {
|
||||
let engine = queue(game(), 1, ["nevlas spend 1q for 1o. up nav."]);
|
||||
engine.players[1].data.knowledge = 0;
|
||||
const before = [engine.players[1].data.qics, engine.players[1].data.ores];
|
||||
engine = move(json(engine), "terrans up nav.", 0);
|
||||
expect([engine.players[1].data.qics, engine.players[1].data.ores]).to.deep.equal(before);
|
||||
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
|
||||
});
|
||||
|
||||
it("allows cancellation even when the retained prefix is no longer legal", () => {
|
||||
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas build ts -1x0."]);
|
||||
engine.players[1].data.knowledge = 0;
|
||||
engine = queue(engine, 1, ["nevlas up nav."]);
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal(["nevlas up nav."]);
|
||||
engine = queue(engine, 1, []);
|
||||
expect(engine.automation.plans[1].moves).to.deep.equal([]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
|
||||
});
|
||||
|
||||
it("keeps a queued move after a pass and executes it in the next round", () => {
|
||||
let engine = queue(game(), 0, ["terrans pass booster4", "terrans up nav."]);
|
||||
expect(engine.round).to.equal(1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal(["terrans up nav."]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
|
||||
engine = move(json(engine), "nevlas pass booster5", 1);
|
||||
expect(engine.round).to.equal(2);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(engine.players[0].data.research.nav).to.equal(1);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
|
||||
});
|
||||
|
||||
it("can queue after already passing without reopening the current round", () => {
|
||||
let engine = move(game(), "terrans pass booster4", 0);
|
||||
const before = [...engine.moveHistory];
|
||||
engine = queue(engine, 0, ["terrans up nav."]);
|
||||
expect(engine.moveHistory).to.deep.equal(before);
|
||||
expect(isLiveUpdate(engine)).to.equal(true);
|
||||
expect(engine.automation.plans[0].timings).to.deep.equal([{ round: 2, phase: Phase.RoundMove }]);
|
||||
engine = move(json(engine), "nevlas pass booster5", 1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
|
||||
});
|
||||
|
||||
it("still limits the queue to three moves", () => {
|
||||
expect(() => queue(game(), 1, Array(4).fill("nevlas up nav."))).to.throw("at most three");
|
||||
});
|
||||
|
||||
const passedItarsGame = () => {
|
||||
const engine = new Engine([
|
||||
"init 2 Gaudy-plow-4506",
|
||||
"p1 faction itars",
|
||||
"p2 faction ivits",
|
||||
"itars build m 3B3",
|
||||
"itars build m 2B2",
|
||||
"ivits build PI 4B3",
|
||||
"ivits booster booster3",
|
||||
"itars booster booster8",
|
||||
"ivits income t",
|
||||
"itars pass booster9",
|
||||
]);
|
||||
engine.players.forEach((player) => {
|
||||
player.settings.autoIncome = false;
|
||||
});
|
||||
return engine;
|
||||
};
|
||||
|
||||
it("queues next-round income and a main turn while waiting for the opponent's manual income", () => {
|
||||
let engine = passedItarsGame();
|
||||
engine = move(
|
||||
engine,
|
||||
{
|
||||
...command(engine, 0, ["itars income t", "itars up nav."]),
|
||||
timings: [
|
||||
{ round: 2, phase: Phase.RoundIncome },
|
||||
{ round: 2, phase: Phase.RoundMove },
|
||||
],
|
||||
},
|
||||
0
|
||||
);
|
||||
expect(isLiveUpdate(engine)).to.equal(true);
|
||||
engine = move(json(engine), "ivits pass booster5", 1);
|
||||
expect(engine.phase).to.equal(Phase.RoundIncome);
|
||||
expect(engine.playerToMove).to.equal(1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal(["itars up nav."]);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
engine = move(json(engine), "ivits income t", 1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(engine.players[0].data.research.nav).to.equal(1);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 2]);
|
||||
});
|
||||
|
||||
it("waits for an unplanned manual income choice without clearing next-round moves", () => {
|
||||
let engine = queue(passedItarsGame(), 0, ["itars up nav."]);
|
||||
engine = move(json(engine), "ivits pass booster5", 1);
|
||||
expect(engine.phase).to.equal(Phase.RoundIncome);
|
||||
expect(engine.playerToMove).to.equal(0);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(1);
|
||||
engine = move(json(engine), "itars income t", 0);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(1);
|
||||
engine = move(json(engine), "ivits income t", 1);
|
||||
expect(engine.automation.plans[0].moves).to.have.length(0);
|
||||
expect(timeIncrements(engine)).to.deep.equal([2, 2]);
|
||||
});
|
||||
|
||||
it("does not replay or credit income that automatic income has already resolved", () => {
|
||||
let engine = passedItarsGame();
|
||||
engine.players.forEach((player) => {
|
||||
player.settings.autoIncome = true;
|
||||
});
|
||||
engine = move(
|
||||
engine,
|
||||
{
|
||||
...command(engine, 0, ["itars income t", "itars up nav."]),
|
||||
timings: [
|
||||
{ round: 2, phase: Phase.RoundIncome },
|
||||
{ round: 2, phase: Phase.RoundMove },
|
||||
],
|
||||
},
|
||||
0
|
||||
);
|
||||
engine = move(json(engine), "ivits pass booster5", 1);
|
||||
expect(engine.automation.plans[0].moves).to.deep.equal([]);
|
||||
expect(engine.players[0].data.research.nav).to.equal(1);
|
||||
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
|
||||
});
|
||||
|
||||
it("can cancel next-round moves and rejects schedules that go backwards", () => {
|
||||
let engine = queue(passedItarsGame(), 0, ["itars up nav."]);
|
||||
engine = queue(engine, 0, []);
|
||||
engine = move(json(engine), "ivits pass booster5", 1);
|
||||
engine = move(json(engine), "itars income t", 0);
|
||||
engine = move(json(engine), "ivits income t", 1);
|
||||
expect(engine.players[0].data.research.nav).to.equal(0);
|
||||
expect(() =>
|
||||
move(
|
||||
engine,
|
||||
{
|
||||
...command(engine, 0, ["itars up nav.", "itars up terra."]),
|
||||
timings: [
|
||||
{ round: 3, phase: Phase.RoundMove },
|
||||
{ round: 2, phase: Phase.RoundMove },
|
||||
],
|
||||
},
|
||||
0
|
||||
)
|
||||
).to.throw("round order");
|
||||
});
|
||||
it("preserves increment totals and clears plans when replaying an existing game", async () => {
|
||||
let engine = queue(game(), 1, ["nevlas up nav."]);
|
||||
engine = move(engine, "terrans up nav.", 0);
|
||||
const counts = timeIncrements(engine);
|
||||
engine = await replay(json(engine), { to: setup.length });
|
||||
expect(timeIncrements(engine)).to.deep.equal(counts);
|
||||
expect(engine.automation.plans).to.deep.equal({});
|
||||
});
|
||||
});
|
||||
|
|
@ -161,11 +161,19 @@ describe("the analysis sandbox's second Trading Station (viewer ANALYSIS_MODE_PL
|
|||
expect(fullRun.player(PlayerEnum.Player1).data.credits).to.equal(14);
|
||||
});
|
||||
|
||||
it("cannot be played in a real game - there is no such entry to match", () => {
|
||||
it("rejects the 3c constraint on an isolated real mine, even when 6c is affordable", () => {
|
||||
const engine = richGame();
|
||||
const isolated = tradingStations(engine).find((b) => b.cost === "6c,2o")!;
|
||||
|
||||
expect(() => engine.move(`terrans build ts ${isolated.coordinates} cheap.`)).to.throw();
|
||||
expect(() => engine.move(`terrans build ts ${isolated.coordinates} cheap.`)).to.throw("not available for 3c");
|
||||
expect(engine.player(PlayerEnum.Player1).data.credits).to.equal(20);
|
||||
});
|
||||
|
||||
it("accepts the 3c constraint on a real mine that already has a neighbour", () => {
|
||||
const engine = richGame();
|
||||
const neighbour = tradingStations(engine).find((b) => b.cost === "3c,2o")!;
|
||||
engine.move(`terrans build ts ${neighbour.coordinates} cheap.`);
|
||||
expect(engine.player(PlayerEnum.Player1).data.credits).to.equal(17);
|
||||
});
|
||||
|
||||
it("leaves an ordinary trailing log annotation alone", () => {
|
||||
|
|
|
|||
|
|
@ -76,10 +76,12 @@ import {
|
|||
moveRotateSectors,
|
||||
moveSetup,
|
||||
moveSilentBid,
|
||||
repairBannedRandomFactions,
|
||||
} from "./move/setup";
|
||||
import { moveGaiaFormTransdim, moveSpaceshipAction } from "./move/spaceship-actions";
|
||||
import Player from "./player";
|
||||
import { MoveTokens, powerLogString } from "./player-data";
|
||||
import type { AutomationState } from "./premove-types";
|
||||
import { lastTile } from "./research-tracks";
|
||||
import { SeededSpaceshipTech, SpaceshipActionType } from "./spaceships";
|
||||
import { roundScoringEvents } from "./tiles/scoring";
|
||||
|
|
@ -440,6 +442,7 @@ export default class Engine {
|
|||
pendingMove = "";
|
||||
// Tells the UI if the new move should be on the same line or not
|
||||
newTurn = true;
|
||||
automation?: AutomationState;
|
||||
|
||||
constructor(moves: string[] = [], options: EngineOptions = {}, engineVersion?: string, replay?: boolean) {
|
||||
this.options = options;
|
||||
|
|
@ -927,6 +930,7 @@ export default class Engine {
|
|||
}
|
||||
}
|
||||
|
||||
repairBannedRandomFactions(engine);
|
||||
return engine;
|
||||
}
|
||||
|
||||
|
|
@ -954,7 +958,12 @@ export default class Engine {
|
|||
replayedTo(move = Infinity, keepReplayMode = false) {
|
||||
const oldHistory = this.moveHistory.slice(0, move);
|
||||
const oldPlayers = this.players;
|
||||
const engine = new Engine(oldHistory.slice(0, 1), this.options, this.version ?? "1.0.0", true);
|
||||
const options = { ...this.options };
|
||||
// Lost Fleet stores its generated map here too; it is not a custom-map setup option.
|
||||
if (options.lostFleet) {
|
||||
delete options.map;
|
||||
}
|
||||
const engine = new Engine(oldHistory.slice(0, 1), options, this.version ?? "1.0.0", true);
|
||||
|
||||
for (let i = 0; i < oldPlayers.length && i < engine.players.length; i++) {
|
||||
engine.players[i].name = oldPlayers[i].name;
|
||||
|
|
@ -1125,7 +1134,9 @@ export default class Engine {
|
|||
}
|
||||
|
||||
parseMove(move: string) {
|
||||
const split = move.split(" ");
|
||||
// The journal can append power changes when a setup move loads the factions.
|
||||
// They describe the result, not extra arguments to the recorded command.
|
||||
const split = move.replace(powerRegex, "").trim().split(" ");
|
||||
return {
|
||||
command: (split[0] || Command.EndTurn) as Command,
|
||||
args: split.slice(1),
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import {
|
|||
SpaceshipTechTile,
|
||||
SubPhase,
|
||||
} from "./enums";
|
||||
import { spaceshipHex } from "./exploration";
|
||||
import { qicForExplorationDistance, spaceshipHex } from "./exploration";
|
||||
import { GaiaHex } from "./gaia-hex";
|
||||
import { moveExplore } from "./move/exploration";
|
||||
import { moveFormFederation } from "./move/federation";
|
||||
|
|
@ -166,6 +166,63 @@ describe("Lost Fleet exploration", () => {
|
|||
expect(command.data.ships.every((entry) => entry.slot === 1)).to.be.true;
|
||||
});
|
||||
|
||||
it("explores from an adjacent Ivits space station with no QIC, including after reload", () => {
|
||||
const engine = createLostFleetRoundMoveEngine(4, [
|
||||
Faction.Ivits,
|
||||
Faction.Terrans,
|
||||
Faction.Lantids,
|
||||
Faction.HadschHallas,
|
||||
]);
|
||||
const player = engine.player(PlayerEnum.Player1);
|
||||
const ship = spaceshipHex(engine.map, Spaceship.Eclipse);
|
||||
const station = [...engine.map.grid.neighbours(ship)].find(
|
||||
(hex) => !hex.hasPlanet() && !hex.occupied() && !hex.data.spaceship
|
||||
);
|
||||
expect(station, "empty space adjacent to Eclipse").to.not.equal(undefined);
|
||||
const institute = [...engine.map.grid.values()]
|
||||
.filter((hex) => hex.hasPlanet())
|
||||
.sort((a, b) => engine.map.distance(b, ship) - engine.map.distance(a, ship))[0];
|
||||
institute.data.player = player.player;
|
||||
institute.data.building = Building.PlanetaryInstitute;
|
||||
station.data.player = player.player;
|
||||
station.data.building = Building.SpaceStation;
|
||||
player.data.occupied = [institute, station];
|
||||
player.data.buildings[Building.PlanetaryInstitute] = 1;
|
||||
player.data.buildings[Building.SpaceStation] = 1;
|
||||
player.data.qics = 0;
|
||||
|
||||
const restored = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
const command = availableExploreCommand(restored);
|
||||
const eclipse = command?.data.ships.find((entry) => entry.ship === Spaceship.Eclipse);
|
||||
expect(eclipse, "station makes Eclipse reachable even with zero QIC").to.not.equal(undefined);
|
||||
expect(eclipse.cost).to.equal("5vp");
|
||||
restored.move("ivits explore eclipse");
|
||||
expect(restored.player(PlayerEnum.Player1).data.qics).to.equal(0);
|
||||
expect(restored.player(PlayerEnum.Player1).data.victoryPoints).to.equal(25);
|
||||
expect(restored.player(PlayerEnum.Player1).data.hasExplored(Spaceship.Eclipse)).to.equal(true);
|
||||
});
|
||||
|
||||
it("does not use another player's station or a Gaiaformer as an exploration origin", () => {
|
||||
const engine = createLostFleetRoundMoveEngine(4, [
|
||||
Faction.Ivits,
|
||||
Faction.Terrans,
|
||||
Faction.Lantids,
|
||||
Faction.HadschHallas,
|
||||
]);
|
||||
const player = engine.player(PlayerEnum.Player1);
|
||||
const ship = spaceshipHex(engine.map, Spaceship.Eclipse);
|
||||
const station = [...engine.map.grid.neighbours(ship)].find(
|
||||
(hex) => !hex.hasPlanet() && !hex.occupied() && !hex.data.spaceship
|
||||
);
|
||||
station.data.player = PlayerEnum.Player2;
|
||||
station.data.building = Building.SpaceStation;
|
||||
player.data.occupied = [station];
|
||||
expect(qicForExplorationDistance(engine.map, ship, player, false)).to.equal(null);
|
||||
station.data.player = player.player;
|
||||
station.data.building = Building.GaiaFormer;
|
||||
expect(qicForExplorationDistance(engine.map, ship, player, false)).to.equal(null);
|
||||
});
|
||||
|
||||
it("should pay the Explore cost, take the lowest free slot, charge power, and survive serialization", () => {
|
||||
const engine = createLostFleetRoundMoveEngine(3);
|
||||
occupyNearestPlanet(engine, PlayerEnum.Player1, Spaceship.Twilight);
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function qicForExplorationDistance(
|
|||
replay: boolean,
|
||||
temporaryRange = pl.data.temporaryRange
|
||||
): QicNeeded | null {
|
||||
const origins = pl.data.occupied.filter((loc) => loc.colonizedBy(pl.player));
|
||||
const origins = pl.data.occupied.filter((loc) => loc.isRangeStartingPoint(pl.player));
|
||||
|
||||
if (origins.length === 0) {
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ChargeDecision, ChargeRequest, decideChargeRequest } from "../auto-charge";
|
||||
import { AvailableCommand, AvailableFreeActionData } from "../available/types";
|
||||
import Engine from "../engine";
|
||||
import Engine, { AuctionVariant } from "../engine";
|
||||
import { Command, Faction, PowerArea, Resource } from "../enums";
|
||||
import assert from "../utils/assert";
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ export function autoMove(engine: Engine, partialMove?: string, options?: { autoP
|
|||
return false;
|
||||
}
|
||||
|
||||
/** Automatically choose faction when there's only one faction available */
|
||||
/** Resolve forced picks and nominate a complete random pool for sealed auctions. */
|
||||
function autoChooseFaction(engine: Engine, cmd: AvailableCommand<Command.ChooseFaction>): string | false {
|
||||
if (engine.availableCommands.length > 1) {
|
||||
// There can be a bid command too
|
||||
|
|
@ -81,7 +81,13 @@ function autoChooseFaction(engine: Engine, cmd: AvailableCommand<Command.ChooseF
|
|||
|
||||
const factions: Faction[] = cmd.data;
|
||||
|
||||
if (factions.length === 1) {
|
||||
const randomNomination =
|
||||
engine.randomFactions &&
|
||||
[AuctionVariant.Silent, AuctionVariant.PreferenceSplit].includes(engine.options.auction) &&
|
||||
// An old game may have banned a faction from its already-drawn pool.
|
||||
// Do not partially automate an incomplete pool or silently replace its factions.
|
||||
factions.length === engine.players.length - engine.setup.length;
|
||||
if (factions.length === 1 || (randomNomination && factions.length > 0)) {
|
||||
return `${Command.ChooseFaction} ${factions[0]}`;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
import { isEqual } from "lodash";
|
||||
import { AvailableBuilding, AvailableCommand } from "../available/types";
|
||||
import Engine from "../engine";
|
||||
import { Building, Command, Phase, Planet, Player as PlayerEnum } from "../enums";
|
||||
import { Building, Command, Phase, Planet, Player as PlayerEnum, Resource } from "../enums";
|
||||
import Player from "../player";
|
||||
import Reward from "../reward";
|
||||
import assert from "../utils/assert";
|
||||
|
||||
/**
|
||||
* Qualifier that may follow the location on a build move, as in `build ts 1x2 cheap`. Purely
|
||||
* additive: no recorded game history carries it, and only the viewer's analysis sandbox ever produces
|
||||
* it (see `AvailableBuilding.analysisCheap`), where it selects the second, neighbour-priced Trading
|
||||
* Station offered for a hex that is really isolated. A real game has no such entry to select, so the
|
||||
* move simply fails to match and the assert at the bottom rejects it.
|
||||
* produced by the planning viewer. In a simulation it selects the assumed-neighbour price; in a
|
||||
* real turn or premove it requires a Trading Station costing at most 3 credits. It never grants a
|
||||
* discount that is not already available on the real board.
|
||||
*
|
||||
* Matched positionally - the first argument after the location - and NOT by scanning every trailing
|
||||
* token: build moves already carry log annotations there (`build gf 6A9 using area1: 6.`), which
|
||||
|
|
@ -33,11 +32,13 @@ export function moveBuild(
|
|||
const wantCheap = qualifier === ANALYSIS_CHEAP_BUILD;
|
||||
|
||||
for (const elem of buildings) {
|
||||
if (
|
||||
elem.building === building &&
|
||||
!!elem.analysisCheap === wantCheap &&
|
||||
isEqual(engine.map.parse(elem.coordinates), parsed)
|
||||
) {
|
||||
const matchesPrice = wantCheap
|
||||
? elem.building === Building.TradingStation &&
|
||||
Reward.parse(elem.cost)
|
||||
.filter((cost) => cost.type === Resource.Credit)
|
||||
.reduce((sum, cost) => sum + cost.count, 0) <= 3
|
||||
: !elem.analysisCheap;
|
||||
if (elem.building === building && matchesPrice && isEqual(engine.map.parse(elem.coordinates), parsed)) {
|
||||
placeBuilding(engine, pl, elem);
|
||||
return;
|
||||
}
|
||||
|
|
@ -45,7 +46,9 @@ export function moveBuild(
|
|||
|
||||
assert(
|
||||
false,
|
||||
`Impossible to execute build command at ${location}, available: ${buildings.map((b) => b.coordinates)}`
|
||||
wantCheap
|
||||
? `The Trading Station at ${location} is not available for 3c.`
|
||||
: `Impossible to execute build command at ${location}, available: ${buildings.map((b) => b.coordinates)}`
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,7 +28,10 @@ export function moveChargePower(
|
|||
|
||||
const offer = leechCommand.offers.find((ofr) => ofr.offer === income);
|
||||
|
||||
assert(offer, `Cannot leech ${income}. Possible leeches: ${leechCommand.offers.map((ofr) => ofr.offer).join(" - ")}`);
|
||||
assert(
|
||||
offer,
|
||||
`Cannot charge ${income}. Possible charges: ${leechCommand.offers.map((ofr) => ofr.offer).join(" - ")}`
|
||||
);
|
||||
|
||||
engine.player(player).gainRewards(leechRewards, Command.ChargePower);
|
||||
engine.player(player).payCosts(Reward.parse(offer.cost), Command.ChargePower);
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ import { lastTile } from "../research-tracks";
|
|||
import Reward from "../reward";
|
||||
import { initCustomSetup, possibleSetupBoardActions } from "../setup";
|
||||
import assert from "../utils/assert";
|
||||
import { moveInit } from "./setup";
|
||||
import { drawRandomFactions, moveInit, randomFactionsAfterBans, repairBannedRandomFactions } from "./setup";
|
||||
|
||||
export function phaseSetupInit(engine: Engine, move: string) {
|
||||
const split = move.split(" ");
|
||||
|
|
@ -327,7 +327,11 @@ function beginSetupPreferenceBidPhase(engine: Engine) {
|
|||
}
|
||||
|
||||
function beginSetupFactionPhase(engine: Engine) {
|
||||
if (randomFactionsAfterBans(engine) && !engine.randomFactions) {
|
||||
drawRandomFactions(engine);
|
||||
}
|
||||
engine.changePhase(Phase.SetupFaction);
|
||||
repairBannedRandomFactions(engine);
|
||||
engine.turnOrder = engine.players.map((pl) => pl.player as PlayerEnum);
|
||||
engine.moveToNextPlayer(engine.turnOrder, { loop: false });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { uniq } from "lodash";
|
||||
import { difference, uniq } from "lodash";
|
||||
import seedrandom from "seedrandom";
|
||||
import {
|
||||
defaultPreferenceSplitBudget,
|
||||
isValidPreferenceSplitBudget,
|
||||
|
|
@ -9,7 +10,7 @@ import {
|
|||
import { silentAuctionBidError } from "../algorithms/silent-auction";
|
||||
import { AvailableCommand } from "../available/types";
|
||||
import Engine, { AuctionVariant } from "../engine";
|
||||
import { BoardAction, Command, Faction, Player as PlayerEnum } from "../enums";
|
||||
import { BoardAction, Command, Faction, Phase, Player as PlayerEnum } from "../enums";
|
||||
import { lostFleetTerraformingBoard, remainingFactions } from "../factions";
|
||||
import SpaceMap from "../map";
|
||||
import Player from "../player";
|
||||
|
|
@ -40,10 +41,6 @@ export function moveInit(engine: Engine, players: number, seed: string) {
|
|||
isValidPreferenceSplitBudget(budget),
|
||||
`The Preference Split Auction's bid budget must be a whole number between ${MIN_PREFERENCE_SPLIT_BUDGET} and ${MAX_PREFERENCE_SPLIT_BUDGET}, got ${engine.options.auctionBudget}`
|
||||
);
|
||||
assert(
|
||||
!engine.options.randomFactions,
|
||||
"The Preference Split Auction cannot be combined with forced random factions"
|
||||
);
|
||||
}
|
||||
|
||||
engine.map = new SpaceMap(
|
||||
|
|
@ -82,18 +79,66 @@ export function moveInit(engine: Engine, players: number, seed: string) {
|
|||
engine.addPlayer(new Player(engine.expansions, i));
|
||||
}
|
||||
|
||||
if (engine.options.randomFactions) {
|
||||
const randomFactions = [];
|
||||
|
||||
for (const _ of engine.players) {
|
||||
const possible = remainingFactions(randomFactions, engine.expansions);
|
||||
|
||||
randomFactions.push(possible[Math.floor(possible.length * engine.map.rng())]);
|
||||
}
|
||||
engine.randomFactions = randomFactions;
|
||||
if (engine.options.randomFactions && !randomFactionsAfterBans(engine)) {
|
||||
drawRandomFactions(engine, engine.map.rng);
|
||||
}
|
||||
}
|
||||
|
||||
export function randomFactionsAfterBans(engine: Engine): boolean {
|
||||
return !!(
|
||||
engine.options.randomFactions &&
|
||||
engine.isVersionOrLater("4.14.3") &&
|
||||
(engine.options.banPhase ?? engine.options.auction === AuctionVariant.Silent)
|
||||
);
|
||||
}
|
||||
|
||||
export function drawRandomFactions(engine: Engine, rng?: () => number) {
|
||||
// The map's RNG is not persisted. After bans, derive a separate deterministic stream
|
||||
// from the recorded init move so loading a saved game cannot change the draw.
|
||||
const random = rng ?? seedrandom(`${engine.moveHistory[0]}:random-factions`);
|
||||
const factions: Faction[] = [];
|
||||
for (const _ of engine.players) {
|
||||
const possible = difference(remainingFactions(factions, engine.expansions), engine.bannedFactions);
|
||||
assert(possible.length > 0, "Not enough unbanned faction colours for all players");
|
||||
factions.push(possible[Math.floor(possible.length * random())]);
|
||||
}
|
||||
engine.randomFactions = factions;
|
||||
}
|
||||
|
||||
/** Old games drew before bans, so banning a drawn faction could leave the last seat without a pick. */
|
||||
export function repairBannedRandomFactions(engine: Engine): boolean {
|
||||
if (
|
||||
engine.phase !== Phase.SetupFaction ||
|
||||
engine.isVersionOrLater("4.14.3") ||
|
||||
!engine.options.randomFactions ||
|
||||
!engine.randomFactions ||
|
||||
![AuctionVariant.Silent, AuctionVariant.PreferenceSplit].includes(engine.options.auction)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const banned = engine.randomFactions.filter((faction) => engine.bannedFactions.includes(faction));
|
||||
if (!banned.length || banned.some((faction) => engine.setup.includes(faction))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const retained = engine.randomFactions.filter((faction) => !banned.includes(faction));
|
||||
const random = seedrandom(`${engine.moveHistory[0]}:replace-banned-random-factions`);
|
||||
const replacements = banned.map(() => {
|
||||
const possible = difference(remainingFactions(retained, engine.expansions), engine.bannedFactions);
|
||||
assert(possible.length > 0, "Not enough unbanned faction colours for all players");
|
||||
const faction = possible[Math.floor(possible.length * random())];
|
||||
retained.push(faction);
|
||||
return faction;
|
||||
});
|
||||
engine.randomFactions = engine.randomFactions.map((faction) =>
|
||||
banned.includes(faction) ? replacements[banned.indexOf(faction)] : faction
|
||||
);
|
||||
// Saved states may still contain the empty command list generated by the old pool.
|
||||
engine.availableCommands = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function moveSetup(
|
||||
engine: Engine,
|
||||
command: AvailableCommand<Command.Setup>,
|
||||
|
|
|
|||
|
|
@ -92,9 +92,6 @@ describe("PlayerData", () => {
|
|||
});
|
||||
|
||||
it("still clamps gains with the flag set - a real player's gains cap the same way (§12)", () => {
|
||||
// The flag used to lift these clamps, because analysis mode injected a sandbox wallet that the
|
||||
// clamps then ate. Nothing is injected now: the seat keeps its real numbers and is simply
|
||||
// allowed to overdraw them, so clamping a GAIN is the faithful behaviour rather than a bug.
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
data.credits = 25;
|
||||
|
|
@ -112,22 +109,17 @@ describe("PlayerData", () => {
|
|||
expect(data.knowledge).to.equal(15);
|
||||
});
|
||||
|
||||
it("stops enforcing affordability for the spendable resources once the flag is set (§12)", () => {
|
||||
it("enforces every resource cost while planning", () => {
|
||||
const data = new PlayerData();
|
||||
data.credits = 1;
|
||||
|
||||
expect(data.hasResource(new Reward(10, Resource.Credit))).to.equal(false);
|
||||
|
||||
data.analysis = true;
|
||||
|
||||
expect(data.hasResource(new Reward(10, Resource.Credit))).to.equal(true);
|
||||
expect(data.hasResource(new Reward(10, Resource.Ore))).to.equal(true);
|
||||
expect(data.hasResource(new Reward(10, Resource.Knowledge))).to.equal(true);
|
||||
expect(data.hasResource(new Reward(10, Resource.Qic))).to.equal(true);
|
||||
expect(data.hasResource(new Reward(10, Resource.ChargePower))).to.equal(true);
|
||||
data.credits = 1;
|
||||
for (const resource of [Resource.Credit, Resource.Ore, Resource.Knowledge, Resource.Qic, Resource.ChargePower]) {
|
||||
expect(data.hasResource(new Reward(10, resource))).to.equal(false);
|
||||
}
|
||||
expect(data.hasResource(new Reward(1, Resource.Credit))).to.equal(true);
|
||||
});
|
||||
|
||||
it("keeps components and board positions genuinely gated - only spendable resources are overdrawable", () => {
|
||||
it("keeps components and board positions gated while planning", () => {
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
|
||||
|
|
@ -138,19 +130,9 @@ describe("PlayerData", () => {
|
|||
expect(data.hasResource(new Reward(1, Resource.MoveTokenFromArea3ToGaia))).to.equal(false);
|
||||
});
|
||||
|
||||
it("lets a spend go negative, which is what the player board then shows", () => {
|
||||
it("can validate a future premove without spending real power", () => {
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
data.credits = 2;
|
||||
|
||||
data.gainReward(new Reward(9, Resource.Credit), true);
|
||||
|
||||
expect(data.credits).to.equal(-7);
|
||||
});
|
||||
|
||||
it("tops a power cost up instead of driving a bowl negative, and counts what it assumed", () => {
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
data.validatingFuturePremove = true;
|
||||
data.power = { area1: 0, area2: 0, area3: 0, gaia: 0 } as any;
|
||||
|
||||
data.spendPower(4);
|
||||
|
|
@ -163,7 +145,7 @@ describe("PlayerData", () => {
|
|||
|
||||
it("charges real tokens up from the lower bowls before assuming any", () => {
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
data.validatingFuturePremove = true;
|
||||
data.power = { area1: 4, area2: 0, area3: 0, gaia: 0 } as any;
|
||||
|
||||
data.spendPower(2);
|
||||
|
|
@ -175,9 +157,12 @@ describe("PlayerData", () => {
|
|||
it("does not survive a toJSON -> clone round trip", () => {
|
||||
const data = new PlayerData();
|
||||
data.analysis = true;
|
||||
data.validatingFuturePremove = true;
|
||||
|
||||
expect(data.toJSON()).to.not.have.property("analysis");
|
||||
expect(data.toJSON()).to.not.have.property("validatingFuturePremove");
|
||||
expect(data.clone().analysis).to.equal(false);
|
||||
expect(data.clone().validatingFuturePremove).to.equal(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -148,27 +148,13 @@ export default class PlayerData extends EventEmitter {
|
|||
temporaryStep = 0;
|
||||
canUpgradeResearch = true;
|
||||
turns = 0;
|
||||
/**
|
||||
* Analysis mode (docs/lost-fleet/ANALYSIS_MODE_PLAN.md §3.4) - true only on a disposable sandbox
|
||||
* clone, never on a real game's player data. It lifts affordability (`hasResource` below) so an
|
||||
* unaffordable move can still be played and the debt shown, and it turns on `spendPower`'s power
|
||||
* top-up. It deliberately does NOT lift the MAX_ORE/MAX_CREDIT/MAX_KNOWLEDGE gain clamps: analysis
|
||||
* mode used to inject a fake wallet that those clamps ate, but a seat now keeps its real numbers,
|
||||
* and a real player's gains cap exactly the same way - so clamping is the faithful behaviour.
|
||||
* Deliberately absent from toJSON() (like the other internal variables above), so it can never
|
||||
* round-trip through a serialize/deserialize into a real game - the viewer re-applies it to a fresh
|
||||
* clone on every replay step instead of relying on it surviving.
|
||||
*/
|
||||
/** Enables explicit planning options, such as simulating a neighbouring Trading Station.
|
||||
* Costs still apply. Never serialized into a real game's player data. */
|
||||
analysis = false;
|
||||
/**
|
||||
* How much power the analysis sandbox has assumed this seat charged (ANALYSIS_MODE_PLAN.md §12).
|
||||
* Power is the one overdrawable resource that cannot go negative - bowls hold tokens, not a balance
|
||||
* - so instead of driving area 3 below zero, `spendPower` charges the shortfall up first and adds
|
||||
* it here, giving the UI one honest number for "this line only works if you also charge N power".
|
||||
*
|
||||
* Non-serialized for the same reason as `analysis` above, and recomputed from scratch on every
|
||||
* replay, so it always describes exactly the line currently on screen.
|
||||
*/
|
||||
/** Only the server's disposable future-premove validator may relax resource checks. The move
|
||||
* is checked again against the real wallet before execution. Never enabled by the viewer or saved. */
|
||||
validatingFuturePremove = false;
|
||||
/** Power assumed by the disposable future-premove validator. Never serialized. */
|
||||
analysisAssumedPower = 0;
|
||||
// when picking rewards
|
||||
toPick: { rewards: Reward[]; count: number; source: EventSource } = undefined;
|
||||
|
|
@ -385,8 +371,8 @@ export default class PlayerData extends EventEmitter {
|
|||
}
|
||||
|
||||
/**
|
||||
* The spendable resources the viewer's analysis mode (ANALYSIS_MODE_PLAN.md §12) lets a player
|
||||
* overdraw: the four wallet resources plus power. Everything else `getResources` answers for stays
|
||||
* The spendable resources the future-premove validator can
|
||||
* temporarily overdraw: the four wallet resources plus power. Everything else `getResources` answers for stays
|
||||
* genuinely gated even in analysis mode, because those are physical components or board positions
|
||||
* rather than a stock you can be in debt on - a Gaiaformer you do not own, or a power token that is
|
||||
* not in the Gaia area, cannot be conjured by assuming you overspent.
|
||||
|
|
@ -413,11 +399,9 @@ export default class PlayerData extends EventEmitter {
|
|||
if (this.getResources(type) >= reward.count) {
|
||||
return true;
|
||||
}
|
||||
// Analysis mode (§12): affordability is what the engine enforces at command-GENERATION time, so
|
||||
// lifting it here is the whole mechanism behind "let me build it anyway and show me the debt".
|
||||
// Deliberately not a resource top-up: the seat keeps its real numbers and simply goes negative,
|
||||
// which is what the player board then displays.
|
||||
return this.analysis && PlayerData.ANALYSIS_OVERDRAWABLE.includes(type);
|
||||
// Future premoves can include explicitly simulated charges. Only their disposable server-side
|
||||
// validation relaxes costs; normal play and the planning UI both enforce the displayed wallet.
|
||||
return this.validatingFuturePremove && PlayerData.ANALYSIS_OVERDRAWABLE.includes(type);
|
||||
}
|
||||
|
||||
getResources(type: Resource): number {
|
||||
|
|
@ -544,7 +528,7 @@ export default class PlayerData extends EventEmitter {
|
|||
}
|
||||
|
||||
/**
|
||||
* Analysis mode's power top-up (§12). `hasResource` lets this seat commit to a power cost it cannot
|
||||
* Future-premove validation's power top-up. `hasResource` lets this seat commit to a power cost it cannot
|
||||
* really pay, but `spendPower` below moves tokens area3 -> area1 with no floor, so an unpayable
|
||||
* cost would leave a NEGATIVE bowl - a state the board renders as nonsense and every later charge
|
||||
* then compounds. Instead: charge the shortfall up first, one step at a time through the engine's
|
||||
|
|
@ -570,7 +554,7 @@ export default class PlayerData extends EventEmitter {
|
|||
}
|
||||
|
||||
spendPower(power: number) {
|
||||
if (this.analysis) {
|
||||
if (this.validatingFuturePremove) {
|
||||
this.assumePowerForAnalysis(power);
|
||||
}
|
||||
if (this.brainstone === PowerArea.Area3) {
|
||||
|
|
|
|||
|
|
@ -314,15 +314,16 @@ export default class Player extends EventEmitter {
|
|||
* How many times over this player can pay `cost` - the "convert up to N" range behind free-action
|
||||
* conversions (available/actions.ts).
|
||||
*
|
||||
* The loop only ever ends because `hasResource` eventually says no, so analysis mode
|
||||
* (ANALYSIS_MODE_PLAN.md §12), where `hasResource` deliberately says yes to any amount of an
|
||||
* The loop only ever ends because `hasResource` eventually says no, so disposable future-premove validation, where `hasResource` deliberately says yes to any amount of an
|
||||
* overdrawable resource, needs its own ceiling or this spins forever and hangs the browser. The
|
||||
* ceiling is what the seat can really pay plus a fixed slack, so a conversion can be overdrawn
|
||||
* like everything else while the range stays a finite, sane number of steps.
|
||||
*/
|
||||
maxPayRange(cost: Reward[]): number {
|
||||
const costs = Reward.merge(cost);
|
||||
const limit = this.data.analysis ? this.realMaxPayRange(costs) + Player.ANALYSIS_EXTRA_PAY_RANGE : Infinity;
|
||||
const limit = this.data.validatingFuturePremove
|
||||
? this.realMaxPayRange(costs) + Player.ANALYSIS_EXTRA_PAY_RANGE
|
||||
: Infinity;
|
||||
|
||||
for (let max = 0; ; max += 1) {
|
||||
if (max >= limit) {
|
||||
|
|
@ -598,6 +599,7 @@ export default class Player extends EventEmitter {
|
|||
}
|
||||
|
||||
removeRoundBoosterEvents(type?: Operator.Income) {
|
||||
if (!this.data.tiles.booster) return;
|
||||
const events = boosterEvents(this.data.tiles.booster).filter(
|
||||
(ev) => (type && ev.operator === Operator.Income) || (!type && ev.operator !== Operator.Income)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -95,6 +95,17 @@ describe("Preference Split Auction variant", () => {
|
|||
expect(engine.playerToMove).to.equal(0);
|
||||
});
|
||||
|
||||
it("replays the bids even when the last entry includes a power-change annotation", () => {
|
||||
expect(engine.moveHistory[engine.moveHistory.length - 1]).to.include("⇒");
|
||||
const replayed = engine.replayedTo();
|
||||
expect(replayed.preferenceSplitBids).to.deep.equal(engine.preferenceSplitBids);
|
||||
expect(replayed.preferenceSplitResult).to.deep.equal(engine.preferenceSplitResult);
|
||||
expect(replayed.players.map((player) => player.faction)).to.deep.equal(
|
||||
engine.players.map((player) => player.faction)
|
||||
);
|
||||
expect(replayed.phase).to.equal(engine.phase);
|
||||
});
|
||||
|
||||
it("keeps the whole resolution auditable on the engine", () => {
|
||||
const terrans = engine.preferenceSplitResult.allocations[0];
|
||||
|
||||
|
|
@ -253,8 +264,12 @@ describe("Preference Split Auction variant", () => {
|
|||
}
|
||||
});
|
||||
|
||||
it("refuses forced random factions, which would leave nothing to express a preference over", () => {
|
||||
expect(() => new Engine(["init 4 djfjjv4k"], options({ randomFactions: true }))).to.throw(/random factions/);
|
||||
it("automatically nominates the random pool before the preference bids", () => {
|
||||
const engine = new Engine(["init 4 djfjjv4k"], options({ randomFactions: true }));
|
||||
while (engine.autoMove());
|
||||
expect(engine.phase).to.equal(Phase.SetupPreferenceBid);
|
||||
expect(engine.setup).to.deep.equal(engine.randomFactions);
|
||||
expect(engine.setup).to.have.length(4);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
34
engine/src/premove-types.ts
Normal file
34
engine/src/premove-types.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import type { Phase } from "./enums";
|
||||
|
||||
export type PremoveTiming = { round: number; phase: Phase };
|
||||
|
||||
export type PremovePlan = {
|
||||
moves: string[];
|
||||
timings?: PremoveTiming[];
|
||||
revision: number;
|
||||
round: number;
|
||||
requestId?: string;
|
||||
notice?: { kind: "played" | "stopped"; text: string };
|
||||
};
|
||||
|
||||
export type AutomationState = {
|
||||
version: 1;
|
||||
roundPremoves?: true;
|
||||
setupPremoves?: true;
|
||||
plans: Record<number, PremovePlan>;
|
||||
increments: number[];
|
||||
turns: number[];
|
||||
liveUpdate: boolean;
|
||||
};
|
||||
|
||||
export type PremoveCommand = {
|
||||
type: "premoves";
|
||||
requestId: string;
|
||||
moves: string[];
|
||||
timings?: PremoveTiming[];
|
||||
round: number;
|
||||
turn: number;
|
||||
revision: number;
|
||||
};
|
||||
|
||||
export const MAX_PREMOVES = 3;
|
||||
226
engine/src/premoves.ts
Normal file
226
engine/src/premoves.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
import Engine from "./engine";
|
||||
import { Phase, Round } from "./enums";
|
||||
import assert from "./utils/assert";
|
||||
|
||||
import type { AutomationState, PremoveCommand, PremovePlan, PremoveTiming } from "./premove-types";
|
||||
import { MAX_PREMOVES } from "./premove-types";
|
||||
export type { AutomationState, PremoveCommand, PremovePlan } from "./premove-types";
|
||||
|
||||
export function automation(engine: Engine): AutomationState {
|
||||
const state = (engine.automation ??= {
|
||||
version: 1,
|
||||
plans: {},
|
||||
increments: engine.players.map(() => 0),
|
||||
turns: engine.players.map(() => 0),
|
||||
liveUpdate: false,
|
||||
});
|
||||
state.roundPremoves = true;
|
||||
state.setupPremoves = true;
|
||||
return state;
|
||||
}
|
||||
|
||||
const setupPhases = [Phase.SetupBuilding, Phase.SetupBooster];
|
||||
const phases = [...setupPhases, Phase.RoundIncome, Phase.RoundGaia, Phase.RoundMove];
|
||||
const phaseOrder = (phase: Phase) => phases.indexOf(phase === Phase.RoundLeech ? Phase.RoundMove : phase);
|
||||
const position = (timing: PremoveTiming) => timing.round * phases.length + phaseOrder(timing.phase);
|
||||
const sameTiming = (a: PremoveTiming, b: PremoveTiming) => a.round === b.round && a.phase === b.phase;
|
||||
|
||||
export function premoveTimings(plan: PremovePlan): PremoveTiming[] {
|
||||
return plan.timings ?? plan.moves.map(() => ({ round: plan.round, phase: Phase.RoundMove }));
|
||||
}
|
||||
|
||||
export function assertOwnMove(engine: Engine, move: string, seat: number) {
|
||||
assert(typeof move === "string" && move.length <= 8000, "Invalid move");
|
||||
const actor = move.trim().split(/\s+/)[0];
|
||||
assert(actor === `p${seat + 1}` || actor === engine.players[seat]?.faction, "You may only play your own moves");
|
||||
}
|
||||
|
||||
export function canQueue(engine: Engine, seat: number): boolean {
|
||||
return (
|
||||
Number.isInteger(seat) &&
|
||||
!!engine.players[seat] &&
|
||||
!engine.players[seat].dropped &&
|
||||
!engine.ended &&
|
||||
(phases.includes(engine.phase) || engine.phase === Phase.RoundLeech)
|
||||
);
|
||||
}
|
||||
|
||||
export function setPremoves(engine: Engine, command: PremoveCommand, seat: number) {
|
||||
assert(canQueue(engine, seat), "Premoves are available after faction selection");
|
||||
const state = automation(engine);
|
||||
const old = state.plans[seat];
|
||||
assert(
|
||||
typeof command.requestId === "string" && command.requestId.length > 0 && command.requestId.length <= 80,
|
||||
"Invalid plan request"
|
||||
);
|
||||
if (old?.requestId === command.requestId) {
|
||||
state.liveUpdate = true;
|
||||
return;
|
||||
}
|
||||
assert(command.revision === (old?.revision ?? 0), "Your premove queue changed. Please check it and try again.");
|
||||
assert(Array.isArray(command.moves) && command.moves.length <= MAX_PREMOVES, "Queue at most three moves");
|
||||
let nextRound = engine.round + (engine.passedPlayers?.includes(seat) ? 1 : 0);
|
||||
const timings =
|
||||
command.timings ??
|
||||
command.moves.map((move) => {
|
||||
const timing = { round: nextRound, phase: setupPhases.includes(engine.phase) ? engine.phase : Phase.RoundMove };
|
||||
if (/\bpass\b/.test(move)) nextRound++;
|
||||
return timing;
|
||||
});
|
||||
assert(Array.isArray(timings) && timings.length === command.moves.length, "Invalid premove schedule");
|
||||
const cancelling =
|
||||
old &&
|
||||
command.moves.length < old.moves.length &&
|
||||
command.moves.every(
|
||||
(move, i) => move === old.moves[i] && timings[i] && sameTiming(timings[i], premoveTimings(old)[i])
|
||||
);
|
||||
let previous = position({ round: engine.round, phase: engine.phase });
|
||||
for (const timing of cancelling ? [] : timings) {
|
||||
assert(
|
||||
timing &&
|
||||
Number.isInteger(timing.round) &&
|
||||
timing.round >= engine.round &&
|
||||
timing.round <= Round.LastRound &&
|
||||
phases.includes(timing.phase) &&
|
||||
(setupPhases.includes(timing.phase) ? timing.round === Round.None : timing.round >= Round.Round1),
|
||||
"Invalid premove schedule"
|
||||
);
|
||||
assert(position(timing) >= previous, "Premoves must follow round order");
|
||||
previous = position(timing);
|
||||
}
|
||||
if (command.moves.length > 0 && !cancelling) {
|
||||
assert(
|
||||
command.round === engine.round && command.turn === state.turns[seat],
|
||||
"Your turn has changed. Please review your plan."
|
||||
);
|
||||
const preview = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
for (const [index, move] of command.moves.entries()) {
|
||||
assertOwnMove(preview, move, seat);
|
||||
const timing = timings[index];
|
||||
assert(
|
||||
!(timing.round === engine.round && engine.passedPlayers?.includes(seat)),
|
||||
"You have already passed this round"
|
||||
);
|
||||
if (setupPhases.includes(timing.phase)) {
|
||||
if (index === 0 && timing.phase === engine.phase && engine.playerToMove === seat) {
|
||||
preview.move(move);
|
||||
assert(preview.newTurn, "Finish each planned turn before queuing it");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A later round/phase depends on income and other players' decisions. Validate its timing
|
||||
// and ownership now; execute the complete move atomically against the real board when due.
|
||||
if (
|
||||
timing.round !== engine.round ||
|
||||
timing.phase !== Phase.RoundMove ||
|
||||
engine.phase === Phase.RoundIncome ||
|
||||
engine.phase === Phase.RoundGaia
|
||||
)
|
||||
continue;
|
||||
assert(
|
||||
preview.round === engine.round && !preview.passedPlayers.includes(seat),
|
||||
"Schedule moves after passing in the next round"
|
||||
);
|
||||
// Validate the shape of future turns without assuming today's wallet is final. Charges
|
||||
// and income may arrive before them. Only this disposable preview may overdraw resources;
|
||||
// playNextPremove always checks the entire turn again on the real, unmodified position.
|
||||
const playsNow = engine.phase === Phase.RoundMove && engine.newTurn && engine.playerToMove === seat;
|
||||
preview.players[seat].data.analysis = true;
|
||||
preview.players[seat].data.validatingFuturePremove = !(playsNow && index === 0);
|
||||
preview.forcePremovePreviewTurn(seat);
|
||||
preview.move(move);
|
||||
assert(preview.newTurn, "Finish each planned turn before queuing it");
|
||||
}
|
||||
}
|
||||
state.plans[seat] = {
|
||||
moves: [...command.moves],
|
||||
timings: timings.map((timing) => ({ ...timing })),
|
||||
revision: (old?.revision ?? 0) + 1,
|
||||
round: engine.round,
|
||||
requestId: command.requestId,
|
||||
};
|
||||
state.liveUpdate = true;
|
||||
}
|
||||
|
||||
export function creditDecision(engine: Engine, seat: number, phase: Phase) {
|
||||
const state = automation(engine);
|
||||
state.increments[seat]++;
|
||||
if (phase === Phase.RoundMove || setupPhases.includes(phase)) state.turns[seat]++;
|
||||
}
|
||||
|
||||
export function clearExpiredPremoves(engine: Engine) {
|
||||
for (const [seat, plan] of Object.entries(automation(engine).plans)) {
|
||||
if (plan.moves.length && (engine.ended || engine.players[+seat].dropped)) {
|
||||
plan.moves = [];
|
||||
plan.timings = [];
|
||||
plan.revision++;
|
||||
plan.notice = {
|
||||
kind: "stopped",
|
||||
text: "Your remaining premoves were cleared because you are no longer playing.",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function playNextPremove(engine: Engine): boolean {
|
||||
if (engine.ended || !phases.includes(engine.phase) || !engine.newTurn) return false;
|
||||
const seat = engine.playerToMove;
|
||||
const state = automation(engine);
|
||||
const plan = state.plans[seat];
|
||||
if (!plan?.moves.length) return false;
|
||||
const timings = premoveTimings(plan);
|
||||
const timing = timings[0];
|
||||
const current = { round: engine.round, phase: engine.phase };
|
||||
if (position(timing) > position(current)) return false;
|
||||
// Automatic income or a manual income choice may already have answered this prompt. Consume
|
||||
// that planned choice without applying it twice; subsequent moves use the actual resources.
|
||||
if (timing.round === engine.round && timing.phase === Phase.RoundIncome && engine.phase !== Phase.RoundIncome) {
|
||||
plan.moves.shift();
|
||||
plan.timings = timings.slice(1);
|
||||
plan.revision++;
|
||||
return true;
|
||||
}
|
||||
const move = plan.moves[0];
|
||||
try {
|
||||
assert(sameTiming(timing, current), "The round or phase planned for this move has already passed");
|
||||
const probe = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
assertOwnMove(probe, move, seat);
|
||||
probe.move(move);
|
||||
assert(probe.newTurn, "The planned move no longer completes a turn");
|
||||
} catch (error) {
|
||||
plan.moves = [];
|
||||
plan.timings = [];
|
||||
plan.revision++;
|
||||
plan.notice = {
|
||||
kind: "stopped",
|
||||
text: `Premoves stopped: ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
return false;
|
||||
}
|
||||
// Validate on a disposable engine first: a failed multi-command turn must not spend anything.
|
||||
engine.move(move);
|
||||
engine.generateAvailableCommandsIfNeeded();
|
||||
plan.moves.shift();
|
||||
plan.timings = timings.slice(1);
|
||||
plan.revision++;
|
||||
plan.notice = { kind: "played", text: `Played for you: ${move}` };
|
||||
state.liveUpdate = false;
|
||||
creditDecision(engine, seat, current.phase);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A manual turn replaces a due main-turn queue, but cannot erase a plan for a later round. */
|
||||
export function reconcileManualPremoves(engine: Engine, seat: number, round: number, phase: Phase) {
|
||||
const plan = automation(engine).plans[seat];
|
||||
if (!plan?.moves.length) return;
|
||||
const timings = premoveTimings(plan);
|
||||
if (!sameTiming(timings[0], { round, phase })) return;
|
||||
if (phase === Phase.RoundIncome) {
|
||||
plan.moves.shift();
|
||||
plan.timings = timings.slice(1);
|
||||
} else {
|
||||
plan.moves = [];
|
||||
plan.timings = [];
|
||||
}
|
||||
plan.revision++;
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
import { expect } from "chai";
|
||||
import * as wrapper from "../wrapper";
|
||||
import Engine, { AuctionVariant } from "./engine";
|
||||
import { Command, Faction, Phase } from "./enums";
|
||||
import { factionPlanet } from "./factions";
|
||||
|
||||
describe("Random factions", () => {
|
||||
it("should only allow player to select given random faction", () => {
|
||||
|
|
@ -23,4 +26,284 @@ describe("Random factions", () => {
|
|||
expect(() => engine("p1 faction bescods", "p2 faction gleens")).to.not.throw();
|
||||
});
|
||||
});
|
||||
for (const auction of [
|
||||
undefined,
|
||||
AuctionVariant.ChooseBid,
|
||||
AuctionVariant.BidWhileChoosing,
|
||||
AuctionVariant.Silent,
|
||||
AuctionVariant.PreferenceSplit,
|
||||
]) {
|
||||
for (const lostFleet of [false, true]) {
|
||||
for (const count of [2, 3, 4, 5]) {
|
||||
it(`draws ${count} unbanned colours with ${auction ?? "no auction"}, expansion=${lostFleet}`, () => {
|
||||
let engine = new Engine([`init ${count} random-auction-bans`], {
|
||||
auction,
|
||||
randomFactions: true,
|
||||
banPhase: true,
|
||||
lostFleet,
|
||||
});
|
||||
expect(engine.phase).to.equal(Phase.SetupFactionBan);
|
||||
expect(engine.randomFactions).to.equal(undefined);
|
||||
while (engine.phase === Phase.SetupFactionBan) {
|
||||
const command = engine.findAvailableCommand(engine.playerToMove, Command.BanFaction);
|
||||
engine.move(`p${engine.playerToMove + 1} banFaction ${command.data[0]}`);
|
||||
engine = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
}
|
||||
expect(engine.randomFactions).to.have.length(count);
|
||||
expect(new Set(engine.randomFactions.map(factionPlanet)).size).to.equal(count);
|
||||
expect(engine.randomFactions.filter((faction) => engine.bannedFactions.includes(faction))).to.deep.equal([]);
|
||||
const pool = [...engine.randomFactions];
|
||||
if (auction === AuctionVariant.BidWhileChoosing) {
|
||||
expect(engine.autoMove()).to.equal(false);
|
||||
expect(engine.setup).to.deep.equal([]);
|
||||
} else {
|
||||
while (engine.autoMove());
|
||||
expect(engine.setup).to.deep.equal(pool);
|
||||
const phase =
|
||||
auction === AuctionVariant.Silent
|
||||
? Phase.SetupSilentBid
|
||||
: auction === AuctionVariant.PreferenceSplit
|
||||
? Phase.SetupPreferenceBid
|
||||
: auction
|
||||
? Phase.SetupAuction
|
||||
: Phase.SetupBuilding;
|
||||
expect(engine.phase).to.equal(phase);
|
||||
}
|
||||
const replayed = new Engine(
|
||||
engine.moveHistory,
|
||||
{ auction, randomFactions: true, banPhase: true, lostFleet },
|
||||
engine.version,
|
||||
true
|
||||
);
|
||||
expect(replayed.randomFactions).to.deep.equal(pool);
|
||||
expect(replayed.setup).to.deep.equal(engine.setup);
|
||||
expect(replayed.phase).to.equal(engine.phase);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it("takes the hosted silent auction straight from the last ban to bids", async () => {
|
||||
let engine = await wrapper.init(4, [], { auction: AuctionVariant.Silent, randomFactions: true }, "random-hosted");
|
||||
for (let seat = 0; seat < 4; seat++) {
|
||||
engine = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
const command = engine.findAvailableCommand(seat, Command.BanFaction);
|
||||
engine = wrapper.move(engine, `p${seat + 1} banFaction ${command.data[0]}`, seat);
|
||||
}
|
||||
expect(engine.phase).to.equal(Phase.SetupSilentBid);
|
||||
expect(engine.setup).to.deep.equal(engine.randomFactions);
|
||||
expect(engine.sealedBidPendingSeats()).to.deep.equal([0, 1, 2, 3]);
|
||||
for (let seat = 0; seat < 4; seat++) {
|
||||
const bids = engine.setup.map((faction) => `${faction} 0`).join(" ");
|
||||
engine = wrapper.move(
|
||||
Engine.fromData(JSON.parse(JSON.stringify(engine))),
|
||||
`p${seat + 1} silentBid ${bids}`,
|
||||
seat
|
||||
);
|
||||
}
|
||||
expect(engine.phase).to.equal(Phase.SetupBuilding);
|
||||
expect(engine.players.map((player) => player.faction)).to.deep.equal(engine.randomFactions);
|
||||
});
|
||||
|
||||
it("automatically nominates a silent random pool when bans are disabled", async () => {
|
||||
const engine = await wrapper.init(
|
||||
4,
|
||||
[],
|
||||
{ auction: AuctionVariant.Silent, randomFactions: true, banPhase: false },
|
||||
"random-no-bans"
|
||||
);
|
||||
expect(engine.phase).to.equal(Phase.SetupSilentBid);
|
||||
expect(engine.bannedFactions).to.deep.equal([]);
|
||||
expect(engine.setup).to.deep.equal(engine.randomFactions);
|
||||
});
|
||||
|
||||
it("preserves the pre-4.14.3 random pool and manual nominations when replaying", () => {
|
||||
const engine = new Engine(["init 3 12"], { auction: AuctionVariant.Silent, randomFactions: true }, "4.14.2");
|
||||
expect(engine.randomFactions).to.deep.equal([Faction.Bescods, Faction.Gleens, Faction.BalTaks]);
|
||||
for (const [seat, faction] of [Faction.Terrans, Faction.Lantids, Faction.HadschHallas].entries()) {
|
||||
engine.move(`p${seat + 1} banFaction ${faction}`);
|
||||
}
|
||||
for (const [seat, faction] of [...engine.randomFactions].reverse().entries()) {
|
||||
engine.move(`p${seat + 1} faction ${faction}`);
|
||||
}
|
||||
const replayed = engine.replayedTo();
|
||||
expect(replayed.randomFactions).to.deep.equal(engine.randomFactions);
|
||||
expect(replayed.setup).to.deep.equal(engine.setup);
|
||||
});
|
||||
|
||||
describe("saved silent auctions from before 4.14.3", () => {
|
||||
function oldGame(bans = 4, nominations = 0): Engine {
|
||||
const engine = new Engine(
|
||||
["init 4 saved-random-auction"],
|
||||
{
|
||||
auction: AuctionVariant.Silent,
|
||||
randomFactions: true,
|
||||
},
|
||||
"4.14.2"
|
||||
);
|
||||
const eligibleBans = Faction.values(engine.expansions).filter(
|
||||
(faction) => !engine.randomFactions.includes(faction)
|
||||
);
|
||||
for (let seat = 0; seat < bans; seat++) {
|
||||
engine.move(`p${seat + 1} banFaction ${eligibleBans[seat]}`);
|
||||
}
|
||||
const choices = [...engine.randomFactions].reverse();
|
||||
for (let seat = 0; seat < nominations; seat++) {
|
||||
engine.move(`p${seat + 1} faction ${choices[seat]}`);
|
||||
}
|
||||
return engine;
|
||||
}
|
||||
|
||||
for (const bans of [0, 1, 2, 3]) {
|
||||
it(`keeps the existing draw when resuming after ${bans} bans`, () => {
|
||||
const original = oldGame(bans);
|
||||
const pool = [...original.randomFactions];
|
||||
const history = [...original.moveHistory];
|
||||
let resumed = Engine.fromData(JSON.parse(JSON.stringify(original)));
|
||||
while (resumed.phase === Phase.SetupFactionBan) {
|
||||
const seat = resumed.playerToMove;
|
||||
const command = resumed.findAvailableCommand(seat, Command.BanFaction);
|
||||
const faction = command.data.find((candidate) => !pool.includes(candidate));
|
||||
resumed = wrapper.move(resumed, `p${seat + 1} banFaction ${faction}`, seat);
|
||||
resumed = Engine.fromData(JSON.parse(JSON.stringify(resumed)));
|
||||
}
|
||||
expect(resumed.randomFactions).to.deep.equal(pool);
|
||||
expect(resumed.setup).to.deep.equal(pool);
|
||||
expect(resumed.bannedFactions.slice(0, bans)).to.deep.equal(original.bannedFactions);
|
||||
expect(resumed.moveHistory.slice(0, history.length)).to.deep.equal(history);
|
||||
expect(resumed.phase).to.equal(Phase.SetupSilentBid);
|
||||
expect(resumed.replayedTo().randomFactions).to.deep.equal(pool);
|
||||
});
|
||||
}
|
||||
|
||||
for (const nominations of [0, 1, 2, 3]) {
|
||||
it(`completes remaining nominations without changing ${nominations} manual choices`, () => {
|
||||
const original = oldGame(4, nominations);
|
||||
const history = [...original.moveHistory];
|
||||
const resumed = Engine.fromData(JSON.parse(JSON.stringify(original)));
|
||||
wrapper.automove(resumed);
|
||||
const expected = [
|
||||
...original.setup,
|
||||
...original.randomFactions.filter((faction) => !original.setup.includes(faction)),
|
||||
];
|
||||
expect(resumed.version).to.equal(original.version);
|
||||
expect(resumed.randomFactions).to.deep.equal(original.randomFactions);
|
||||
expect(resumed.bannedFactions).to.deep.equal(original.bannedFactions);
|
||||
expect(resumed.setup).to.deep.equal(expected);
|
||||
expect(resumed.players.map((player) => player.faction)).to.deep.equal(expected);
|
||||
expect(resumed.moveHistory.slice(0, history.length)).to.deep.equal(history);
|
||||
expect(resumed.phase).to.equal(Phase.SetupSilentBid);
|
||||
expect(resumed.sealedBidPendingSeats()).to.deep.equal([0, 1, 2, 3]);
|
||||
const replayed = resumed.replayedTo();
|
||||
expect(replayed.setup).to.deep.equal(expected);
|
||||
expect(replayed.players.map((player) => player.faction)).to.deep.equal(expected);
|
||||
expect(replayed.moveHistory).to.deep.equal(resumed.moveHistory);
|
||||
});
|
||||
}
|
||||
|
||||
it("still accepts a nomination from an already-open selection screen before completing the others", () => {
|
||||
const original = oldGame(4, 1);
|
||||
const faction = original.randomFactions[1];
|
||||
const resumed = wrapper.move(JSON.parse(JSON.stringify(original)), `p2 faction ${faction}`, 1);
|
||||
expect(resumed.setup.slice(0, 2)).to.deep.equal([...original.setup, faction]);
|
||||
expect(resumed.randomFactions).to.deep.equal(original.randomFactions);
|
||||
expect(resumed.phase).to.equal(Phase.SetupSilentBid);
|
||||
});
|
||||
|
||||
it("replaces only banned factions in an old pool before completing nominations", () => {
|
||||
const original = oldGame(3);
|
||||
const pool = [...original.randomFactions];
|
||||
original.move(`p4 banFaction ${original.randomFactions[0]}`);
|
||||
const saved = JSON.parse(JSON.stringify(original));
|
||||
saved.randomFactions = pool;
|
||||
const resumed = Engine.fromData(saved);
|
||||
wrapper.automove(resumed);
|
||||
expect(resumed.phase).to.equal(Phase.SetupSilentBid);
|
||||
expect(resumed.randomFactions.slice(1)).to.deep.equal(pool.slice(1));
|
||||
expect(resumed.bannedFactions).not.to.include(resumed.randomFactions[0]);
|
||||
expect(new Set(resumed.randomFactions.map(factionPlanet)).size).to.equal(4);
|
||||
expect(resumed.bannedFactions).to.deep.equal(original.bannedFactions);
|
||||
expect(resumed.moveHistory.slice(0, original.moveHistory.length)).to.deep.equal(original.moveHistory);
|
||||
expect(resumed.replayedTo().randomFactions).to.deep.equal(resumed.randomFactions);
|
||||
});
|
||||
|
||||
for (const auction of [AuctionVariant.Silent, AuctionVariant.PreferenceSplit]) {
|
||||
for (const nominations of [0, 1, 2, 3]) {
|
||||
it(`repairs the blocked Lost Fleet pool after ${nominations} manual picks with ${auction}`, () => {
|
||||
const original = new Engine(
|
||||
["init 4 Merry-novel-6174"],
|
||||
{ randomFactions: true, auction, banPhase: true, lostFleet: true, officialCenterSectors: true },
|
||||
"4.14.2"
|
||||
);
|
||||
const pool = [...original.randomFactions];
|
||||
expect(pool).to.deep.equal([Faction.Firaks, Faction.Gleens, Faction.Itars, Faction.Taklons]);
|
||||
const bans = [Faction.Firaks, Faction.Ivits, Faction.Lantids, Faction.Xenos];
|
||||
for (const [seat, faction] of bans.entries()) {
|
||||
original.move(`p${seat + 1} banFaction ${faction}`);
|
||||
}
|
||||
const choices = [Faction.Itars, Faction.Gleens, Faction.Taklons].slice(0, nominations);
|
||||
for (const [seat, faction] of choices.entries()) {
|
||||
original.move(`p${seat + 1} faction ${faction}`);
|
||||
}
|
||||
const saved = JSON.parse(JSON.stringify(original));
|
||||
saved.randomFactions = pool;
|
||||
saved.availableCommands = [
|
||||
{
|
||||
name: Command.ChooseFaction,
|
||||
player: nominations,
|
||||
data: pool.filter((faction) => !bans.includes(faction) && !choices.includes(faction)),
|
||||
},
|
||||
];
|
||||
|
||||
const resumed = Engine.fromData(saved);
|
||||
wrapper.automove(resumed);
|
||||
expect(resumed.phase).to.equal(
|
||||
auction === AuctionVariant.Silent ? Phase.SetupSilentBid : Phase.SetupPreferenceBid
|
||||
);
|
||||
expect(resumed.setup.slice(0, nominations)).to.deep.equal(choices);
|
||||
expect(resumed.randomFactions.slice(1)).to.deep.equal(pool.slice(1));
|
||||
expect(resumed.randomFactions.some((faction) => bans.includes(faction))).to.equal(false);
|
||||
expect(new Set(resumed.randomFactions.map(factionPlanet)).size).to.equal(4);
|
||||
expect(resumed.bannedFactions).to.deep.equal(bans);
|
||||
expect(resumed.moveHistory.slice(0, original.moveHistory.length)).to.deep.equal(original.moveHistory);
|
||||
expect(resumed.sealedBidPendingSeats()).to.deep.equal([0, 1, 2, 3]);
|
||||
const replayed = resumed.replayedTo();
|
||||
expect(replayed.randomFactions).to.deep.equal(resumed.randomFactions);
|
||||
expect(replayed.options.map).to.deep.equal(resumed.options.map);
|
||||
expect(replayed.setup).to.deep.equal(resumed.setup);
|
||||
expect(replayed.players.map((player) => player.faction)).to.deep.equal(resumed.setup);
|
||||
const loaded = Engine.fromData(JSON.parse(JSON.stringify(resumed)));
|
||||
expect(loaded.randomFactions).to.deep.equal(resumed.randomFactions);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const submitted of [1, 2, 3]) {
|
||||
it(`preserves ${submitted} submitted bid vectors and their nomination tie-breakers`, () => {
|
||||
const original = oldGame(4, 4);
|
||||
const bid = (seat: number) =>
|
||||
`p${seat + 1} silentBid ${original.setup.map((faction) => `${faction} 0`).join(" ")}`;
|
||||
for (let seat = 0; seat < submitted; seat++) {
|
||||
original.move(bid(seat));
|
||||
}
|
||||
let resumed = Engine.fromData(JSON.parse(JSON.stringify(original)));
|
||||
wrapper.automove(resumed);
|
||||
expect(resumed.randomFactions).to.deep.equal(original.randomFactions);
|
||||
expect(resumed.setup).to.deep.equal(original.setup);
|
||||
expect(resumed.bannedFactions).to.deep.equal(original.bannedFactions);
|
||||
expect(resumed.silentAuctionBids).to.deep.equal(original.silentAuctionBids);
|
||||
expect(resumed.moveHistory).to.deep.equal(original.moveHistory);
|
||||
expect(resumed.sealedBidPendingSeats()).to.deep.equal(original.sealedBidPendingSeats());
|
||||
for (let seat = submitted; seat < 4; seat++) {
|
||||
resumed = wrapper.move(JSON.parse(JSON.stringify(resumed)), bid(seat), seat);
|
||||
}
|
||||
expect(resumed.phase).to.equal(Phase.SetupBuilding);
|
||||
// Equal bids must keep the original manually nominated factions as tie-breakers.
|
||||
expect(resumed.players.map((player) => player.faction)).to.deep.equal(original.setup);
|
||||
const replayed = resumed.replayedTo();
|
||||
expect(replayed.players.map((player) => player.faction)).to.deep.equal(original.setup);
|
||||
expect(replayed.silentAuctionBids).to.deep.equal(resumed.silentAuctionBids);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,6 +7,17 @@ import {
|
|||
defaultAutoChargeMaxPassedRoundLeech,
|
||||
defaultAutoChargeTargetSpendablePower,
|
||||
} from "./src/player";
|
||||
import type { PremoveCommand } from "./src/premove-types";
|
||||
import {
|
||||
assertOwnMove,
|
||||
automation,
|
||||
canQueue,
|
||||
clearExpiredPremoves,
|
||||
creditDecision,
|
||||
playNextPremove,
|
||||
reconcileManualPremoves,
|
||||
setPremoves,
|
||||
} from "./src/premoves";
|
||||
import assert from "./src/utils/assert";
|
||||
|
||||
export async function init(
|
||||
|
|
@ -102,7 +113,7 @@ export function playerSettings(engine: Engine, player: number) {
|
|||
};
|
||||
}
|
||||
|
||||
export function move(engine: Engine, move: string, player: number) {
|
||||
export function move(engine: Engine, move: string | PremoveCommand, player: number) {
|
||||
if (!move) {
|
||||
// Don't save
|
||||
(engine as any).noSave = true;
|
||||
|
|
@ -113,7 +124,17 @@ export function move(engine: Engine, move: string, player: number) {
|
|||
engine = Engine.fromData(engine);
|
||||
}
|
||||
|
||||
automation(engine).liveUpdate = false;
|
||||
if (typeof move !== "string") {
|
||||
assert(move?.type === "premoves", "Unknown move");
|
||||
setPremoves(engine, move, player);
|
||||
automove(engine);
|
||||
return engine;
|
||||
}
|
||||
assertOwnMove(engine, move, player);
|
||||
|
||||
const round = engine.round;
|
||||
const phase = engine.phase;
|
||||
const backup = JSON.stringify(engine);
|
||||
|
||||
engine.move(move);
|
||||
|
|
@ -132,6 +153,8 @@ export function move(engine: Engine, move: string, player: number) {
|
|||
engine.generateAvailableCommandsIfNeeded();
|
||||
|
||||
if (engine.newTurn) {
|
||||
creditDecision(engine, player, phase);
|
||||
reconcileManualPremoves(engine, player, round, phase);
|
||||
afterMove(engine, round);
|
||||
|
||||
automove(engine);
|
||||
|
|
@ -167,9 +190,26 @@ export function automove(engine: Engine) {
|
|||
modified = true;
|
||||
oldRound = engine.round;
|
||||
}
|
||||
clearExpiredPremoves(engine);
|
||||
if (playNextPremove(engine)) {
|
||||
afterMove(engine, oldRound);
|
||||
modified = true;
|
||||
}
|
||||
} while (modified);
|
||||
}
|
||||
|
||||
export function canMoveOutOfTurn(engine: Engine, move: string | PremoveCommand, player: number): boolean {
|
||||
return typeof move === "object" && move?.type === "premoves" && canQueue(engine, player);
|
||||
}
|
||||
|
||||
export function isLiveUpdate(engine: Engine): boolean {
|
||||
return engine.automation?.liveUpdate === true;
|
||||
}
|
||||
|
||||
export function timeIncrements(engine: Engine): number[] {
|
||||
return engine.automation?.increments ?? engine.players.map(() => 0);
|
||||
}
|
||||
|
||||
export function ended(engine: Engine) {
|
||||
return engine.ended;
|
||||
}
|
||||
|
|
@ -191,7 +231,9 @@ export async function replay(engine: Engine, { to = Infinity } = { to: Infinity
|
|||
engine = Engine.fromData(engine);
|
||||
}
|
||||
|
||||
const previous = automation(engine);
|
||||
engine = engine.replayedTo(to, false);
|
||||
engine.automation = { ...previous, plans: {}, liveUpdate: false };
|
||||
|
||||
automove(engine);
|
||||
|
||||
|
|
@ -210,8 +252,11 @@ export function moveAI(engine: Engine, player: number) {
|
|||
}
|
||||
|
||||
const round = engine.round;
|
||||
const phase = engine.phase;
|
||||
automation(engine).liveUpdate = false;
|
||||
|
||||
if (engine.moveAI()) {
|
||||
creditDecision(engine, player, phase);
|
||||
afterMove(engine, round);
|
||||
engine.generateAvailableCommandsIfNeeded();
|
||||
// resolve forced / trivial decisions (free leech, income, ...) so the game
|
||||
|
|
@ -224,6 +269,7 @@ export function moveAI(engine: Engine, player: number) {
|
|||
|
||||
export async function dropPlayer(engine: Engine, player: number) {
|
||||
engine = engine instanceof Engine ? engine : Engine.fromData(engine);
|
||||
automation(engine).liveUpdate = false;
|
||||
|
||||
engine.players[player].dropped = true;
|
||||
|
||||
|
|
@ -307,6 +353,8 @@ export function stripSecret(engine: Engine, player?: number): Engine {
|
|||
// Plain-JSON copy: this runs on both live Engine instances and the saved plain data, and the
|
||||
// platform JSON-serializes whatever we return anyway.
|
||||
const data = JSON.parse(JSON.stringify(engine)) as Engine;
|
||||
const state = automation(data);
|
||||
state.plans = player === undefined || !state.plans[player] ? {} : { [player]: state.plans[player] };
|
||||
|
||||
if (data.phase !== Phase.SetupSilentBid && data.phase !== Phase.SetupPreferenceBid) {
|
||||
return data;
|
||||
|
|
|
|||
10
pnpm-lock.yaml
generated
10
pnpm-lock.yaml
generated
|
|
@ -173,8 +173,8 @@ importers:
|
|||
viewer:
|
||||
dependencies:
|
||||
'@boardgamers/protocol':
|
||||
specifier: 0.3.3
|
||||
version: 0.3.3
|
||||
specifier: 0.3.4
|
||||
version: 0.3.4
|
||||
'@gaia-project/engine':
|
||||
specifier: workspace:../engine
|
||||
version: link:../engine
|
||||
|
|
@ -433,8 +433,8 @@ packages:
|
|||
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@boardgamers/protocol@0.3.3':
|
||||
resolution: {integrity: sha512-AS+x84WHXRudW6xt/s/5I3xYmNTQFbZEBp3V+41w0I2RirSr2fWjYnYf0p11nwTbZ6G5upivKz/sjYLtk8HOYA==}
|
||||
'@boardgamers/protocol@0.3.4':
|
||||
resolution: {integrity: sha512-rlHzGBgFD7qm/4OnnKao62GqpuGTL6wMvoH0T9QPp6Sm3Nf5bMBeL+KRVWCkPoewV5FRcp0TElAsqZT+5GRVjQ==}
|
||||
|
||||
'@bramus/specificity@2.4.2':
|
||||
resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
|
||||
|
|
@ -7083,7 +7083,7 @@ snapshots:
|
|||
|
||||
'@bcoe/v8-coverage@1.0.2': {}
|
||||
|
||||
'@boardgamers/protocol@0.3.3':
|
||||
'@boardgamers/protocol@0.3.4':
|
||||
dependencies:
|
||||
zod: 4.6.2
|
||||
|
||||
|
|
|
|||
|
|
@ -15,4 +15,4 @@ allowBuilds:
|
|||
nodent-runtime: true
|
||||
yorkie: true
|
||||
minimumReleaseAgeExclude:
|
||||
- "@boardgamers/protocol@0.2.2 || 0.3.3"
|
||||
- "@boardgamers/protocol@0.2.2 || 0.3.3 || 0.3.4"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@gaia-project/viewer",
|
||||
"version": "5.18.0",
|
||||
"version": "5.20.6",
|
||||
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
|
||||
"contributors": [
|
||||
"coyotte508",
|
||||
|
|
@ -23,7 +23,8 @@
|
|||
"test:tutorial": "vitest run src/tutorial",
|
||||
"test:tutorial:browser": "node scripts/tutorial-smoke.mjs",
|
||||
"tutorial:preview": "node scripts/tutorial-preview.mjs",
|
||||
"tutorial:manifest": "node scripts/tutorial-manifest.cjs"
|
||||
"tutorial:manifest": "node scripts/tutorial-manifest.cjs",
|
||||
"premove:preview": "node scripts/premove-preview.mjs"
|
||||
},
|
||||
"unpkg": "dist/package/viewer.umd.js",
|
||||
"files": [
|
||||
|
|
@ -39,7 +40,7 @@
|
|||
"dist/package/css"
|
||||
],
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.3.3",
|
||||
"@boardgamers/protocol": "0.3.4",
|
||||
"@gaia-project/engine": "workspace:../engine",
|
||||
"bootstrap": "^4.4.1",
|
||||
"bootstrap-vue": "^2.12.0",
|
||||
|
|
|
|||
104
viewer/scripts/premove-preview.html
Normal file
104
viewer/scripts/premove-preview.html
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Gaia Project · Premoves preview</title>
|
||||
<link rel="stylesheet" href="/bundle.css" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
.preview-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 16px;
|
||||
background: #123a5a;
|
||||
color: #fff;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.preview-tools a {
|
||||
color: #cceaff;
|
||||
}
|
||||
.preview-tools strong {
|
||||
margin-right: auto;
|
||||
}
|
||||
.preview-tools button {
|
||||
border: 1px solid #82a9c7;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
border-radius: 5px;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
#error {
|
||||
color: #902b20;
|
||||
background: #fff2e9;
|
||||
padding: 10px;
|
||||
}
|
||||
#error:empty {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="preview-tools">
|
||||
<strong>Gaia Project · Local premove preview</strong><a id="other" target="_blank">Other player's view ↗</a
|
||||
><button id="opponent">Play opponent's turn</button><button id="reset">Reset position</button
|
||||
><button id="theme">Light / dark</button>
|
||||
</header>
|
||||
<div id="error" role="alert"></div>
|
||||
<div id="app"></div>
|
||||
<script src="/vue.js"></script>
|
||||
<script src="/bootstrap.js"></script>
|
||||
<script src="/bundle.js"></script>
|
||||
<script>
|
||||
const seat = Number(new URL(location.href).searchParams.get("seat") ?? 1);
|
||||
const host = gaiaViewer.launch("#app");
|
||||
let revision = -1;
|
||||
document.querySelector("#other").href = "/?seat=" + (1 - seat);
|
||||
async function send(path, body) {
|
||||
const response = await fetch(
|
||||
path + "?seat=" + seat,
|
||||
body === undefined
|
||||
? {}
|
||||
: { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
|
||||
);
|
||||
const data = await response.json();
|
||||
if (data.error) {
|
||||
host.store.commit("planError", data.error);
|
||||
document.querySelector("#error").textContent = data.error;
|
||||
return;
|
||||
}
|
||||
document.querySelector("#error").textContent = "";
|
||||
revision = data.revision;
|
||||
host.emit("state", data.state);
|
||||
}
|
||||
host.on("fetchState", () => send("/state"));
|
||||
host.on("move", (move) => send("/move", { move }));
|
||||
host.emit("player", { index: seat });
|
||||
host.emit("preferences", { sound: false });
|
||||
host.emit("chat:state", { canSend: false, mentions: [] });
|
||||
host.emit("chat:messages", []);
|
||||
document.querySelector("#opponent").onclick = () => send("/opponent", {});
|
||||
document.querySelector("#reset").onclick = () => {
|
||||
localStorage.clear();
|
||||
send("/reset", {});
|
||||
};
|
||||
document.querySelector("#theme").onclick = () => {
|
||||
const dark = document.documentElement.dataset.theme !== "dark";
|
||||
document.documentElement.classList.toggle("dark", dark);
|
||||
host.emit("theme", { dark });
|
||||
};
|
||||
setInterval(async () => {
|
||||
const response = await fetch("/state?seat=" + seat);
|
||||
const data = await response.json();
|
||||
if (data.revision !== revision) {
|
||||
revision = data.revision;
|
||||
host.emit("state", data.state);
|
||||
}
|
||||
}, 1000);
|
||||
send("/state");
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
89
viewer/scripts/premove-preview.mjs
Normal file
89
viewer/scripts/premove-preview.mjs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { readFile } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { default: Engine } = require("../../engine/dist/index.js");
|
||||
const wrapper = require("../../engine/dist/wrapper.js");
|
||||
const { automation } = require("../../engine/dist/src/premoves.js");
|
||||
const files = {
|
||||
"/bundle.js": fileURLToPath(new URL("../dist/package/viewer.umd.js", import.meta.url)),
|
||||
"/bundle.css": fileURLToPath(new URL("../dist/package/viewer.css", import.meta.url)),
|
||||
"/vue.js": require.resolve("vue/dist/vue.min.js"),
|
||||
"/bootstrap.js": require.resolve("bootstrap-vue/dist/bootstrap-vue.min.js"),
|
||||
};
|
||||
const setup = Engine.parseMoves(`
|
||||
init 2 randomSeed
|
||||
p1 faction terrans
|
||||
p2 faction nevlas
|
||||
terrans build m -1x2
|
||||
nevlas build m -1x0
|
||||
nevlas build m 0x-4
|
||||
terrans build m -4x-1
|
||||
nevlas booster booster7
|
||||
terrans booster booster3
|
||||
`);
|
||||
let state;
|
||||
let revision = 0;
|
||||
function reset() {
|
||||
state = new Engine(setup);
|
||||
state.players[0].name = "Alex";
|
||||
state.players[1].name = "You";
|
||||
wrapper.setPlayerSettings(state, 0, { autoCharge: "2" });
|
||||
wrapper.setPlayerSettings(state, 1, { autoCharge: "2" });
|
||||
state.generateAvailableCommandsIfNeeded();
|
||||
automation(state);
|
||||
revision++;
|
||||
}
|
||||
reset();
|
||||
// Optional local snapshot, useful when rebuilding the engine without resetting a UI test.
|
||||
if (process.env.PREMOVE_PREVIEW_STATE) {
|
||||
state = Engine.fromData(JSON.parse(await readFile(process.env.PREMOVE_PREVIEW_STATE, "utf8")));
|
||||
}
|
||||
const clone = () => JSON.parse(JSON.stringify(state));
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const seat = Number(url.searchParams.get("seat") ?? 1);
|
||||
try {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (url.pathname === "/") {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(await readFile(new URL("./premove-preview.html", import.meta.url)));
|
||||
} else if (files[url.pathname]) {
|
||||
res.setHeader("Content-Type", url.pathname.endsWith(".css") ? "text/css" : "text/javascript");
|
||||
res.end(await readFile(files[url.pathname]));
|
||||
} else {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
if (req.method === "POST") {
|
||||
if (url.pathname === "/reset") reset();
|
||||
else if (url.pathname === "/opponent") {
|
||||
const player = wrapper.currentPlayer(state);
|
||||
if (player === seat) throw new Error("It is your turn. Use the game controls or reset the preview.");
|
||||
state =
|
||||
state.moveHistory.length === setup.length
|
||||
? wrapper.move(clone(), "terrans build ts -1x2.", 0)
|
||||
: wrapper.moveAI(clone(), player);
|
||||
revision++;
|
||||
} else if (url.pathname === "/move") {
|
||||
let body = "";
|
||||
for await (const chunk of req) body += chunk;
|
||||
const { move } = JSON.parse(body);
|
||||
const current = wrapper.currentPlayer(state);
|
||||
if (current !== seat && !wrapper.canMoveOutOfTurn(state, move, seat)) throw new Error("It is not your turn.");
|
||||
const result = wrapper.move(clone(), move, seat);
|
||||
if (wrapper.toSave(result)) {
|
||||
state = result;
|
||||
revision++;
|
||||
}
|
||||
res.end(JSON.stringify({ revision, state: wrapper.stripSecret(result, seat) }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.end(JSON.stringify({ revision, state: wrapper.stripSecret(state, seat) }));
|
||||
}
|
||||
} catch (error) {
|
||||
res.writeHead(422, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: error.message }));
|
||||
}
|
||||
});
|
||||
server.listen(Number(process.env.PORT || 5201), "127.0.0.1", () => console.log("Gaia premoves: http://127.0.0.1:5201"));
|
||||
|
|
@ -194,16 +194,33 @@ try {
|
|||
}, state);
|
||||
await page.waitForFunction(() => fetches > 0);
|
||||
assert.equal(await page.evaluate(() => readyCount), 1, "ready fires once");
|
||||
const action = { seat: 0, id: "test", move: "p1 up nav.", mode: "sequential" };
|
||||
const action = { type: "premoves", requestId: "test", moves: ["p1 up nav."], round: 1, turn: 0, revision: 0 };
|
||||
const received = await page.evaluate((action) => {
|
||||
let forwarded;
|
||||
host.on("queuePremove", (payload) => {
|
||||
host.on("move", (payload) => {
|
||||
forwarded = payload;
|
||||
});
|
||||
host.store.dispatch("queuePremove", action);
|
||||
host.store.dispatch("submitPlan", action);
|
||||
return forwarded;
|
||||
}, action);
|
||||
assert.deepEqual(received, action, "Gaia extension events keep working");
|
||||
assert.deepEqual(received, action, "premove plans use the ordinary move protocol");
|
||||
const settings = await page.evaluate(() => {
|
||||
host.emit("settings", { autoCharge: "3", autoIncome: true });
|
||||
let update;
|
||||
host.on("update:setting", (payload) => {
|
||||
update = payload;
|
||||
});
|
||||
host.store.dispatch("updatePlayerSetting", { name: "autoCharge", value: "4" });
|
||||
return { current: host.store.state.playerSettings, update };
|
||||
});
|
||||
assert.deepEqual(
|
||||
settings,
|
||||
{
|
||||
current: { autoCharge: "3", autoIncome: true },
|
||||
update: { name: "autoCharge", value: "4" },
|
||||
},
|
||||
"viewer settings stay confirmed until the host responds"
|
||||
);
|
||||
await page.screenshot({
|
||||
path: `/tmp/${game}-protocol-${ui}-${lostFleet ? "fleet" : "base"}-${width}.png`,
|
||||
fullPage: true,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ Vue.use(BootstrapVue);
|
|||
|
||||
// The commit confirmation (ANALYSIS_MODE_PLAN.md §6). Composing a turn inside the sandbox never
|
||||
// confirms (§12.4); this does, because Commit is the one control whose effect reaches the real game
|
||||
// - where the sandbox's own Undo does not follow - and it clears the line on the way out.
|
||||
// - where the sandbox's own Undo does not follow.
|
||||
describe("AnalysisCommitConfirm", () => {
|
||||
const plan = (over: Partial<AnalysisCommitPlan> = {}): AnalysisCommitPlan => ({
|
||||
live: null,
|
||||
|
|
@ -20,8 +20,14 @@ describe("AnalysisCommitConfirm", () => {
|
|||
...over,
|
||||
});
|
||||
|
||||
const mounted: Wrapper<Vue>[] = [];
|
||||
afterEach(() => {
|
||||
for (const wrapper of mounted.splice(0)) wrapper.destroy();
|
||||
});
|
||||
|
||||
const open = async (p: AnalysisCommitPlan): Promise<Wrapper<Vue>> => {
|
||||
const wrapper = mount(AnalysisCommitConfirm, { propsData: { plan: p }, attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
wrapper.vm.$bvModal.show("analysis-commit-confirm");
|
||||
await Vue.nextTick();
|
||||
await Vue.nextTick();
|
||||
|
|
@ -55,19 +61,27 @@ describe("AnalysisCommitConfirm", () => {
|
|||
it("says nothing plays immediately when the commit happens off turn", async () => {
|
||||
const wrapper = await open(plan({ live: null, queued: ["terrans up nav."] }));
|
||||
|
||||
expect(dialogText()).to.contain("not your turn");
|
||||
expect(dialogText()).to.contain("on your next turn");
|
||||
expect(dialogText()).to.not.contain("plays now");
|
||||
wrapper.destroy();
|
||||
});
|
||||
|
||||
it("lists the moves being left behind and why, since committing clears the line", async () => {
|
||||
it("explains the 3c-only constraint when the plan used a simulated neighbour", async () => {
|
||||
await open(plan({ queued: ["terrans build ts 4A4 cheap."], simulatedNeighbour: true }));
|
||||
const constraint = document.body.querySelector(".analysis-commit__neighbour");
|
||||
expect(constraint).to.not.equal(null);
|
||||
expect(constraint.textContent).to.contain("3c, plus ore");
|
||||
expect(constraint.textContent).to.contain("never spend 6c");
|
||||
});
|
||||
|
||||
it("lists the unsent moves and explains that plans stay saved", async () => {
|
||||
const wrapper = await open(plan({ live: "terrans up nav.", dropped: ["terrans build ts 1A2."], cut: "overdrawn" }));
|
||||
|
||||
const text = dialogText();
|
||||
expect(text).to.contain("1 more move stays behind");
|
||||
expect(text).to.contain("spend more than you actually have");
|
||||
expect(text).to.contain("terrans build ts 1A2.");
|
||||
expect(text).to.contain("clears this line");
|
||||
expect(text).to.contain("Your plans stay saved");
|
||||
wrapper.destroy();
|
||||
});
|
||||
|
||||
|
|
@ -75,7 +89,7 @@ describe("AnalysisCommitConfirm", () => {
|
|||
const wrapper = await open(plan({ live: "a", queued: ["b"], dropped: ["c", "d"], limit: "queue" }));
|
||||
|
||||
expect(dialogText()).to.contain("2 more moves stay behind");
|
||||
expect(dialogText()).to.contain("premove queue is full");
|
||||
expect(dialogText()).to.contain("up to three moves");
|
||||
wrapper.destroy();
|
||||
});
|
||||
|
||||
|
|
@ -86,18 +100,11 @@ describe("AnalysisCommitConfirm", () => {
|
|||
wrapper.destroy();
|
||||
});
|
||||
|
||||
it("explains an assumed-power cut in the terms the player can act on", async () => {
|
||||
const wrapper = await open(plan({ live: "a", dropped: ["b"], cut: "assumed-power" }));
|
||||
|
||||
expect(dialogText()).to.contain("topped up your power");
|
||||
wrapper.destroy();
|
||||
});
|
||||
|
||||
it("emits nothing until the player actually confirms", async () => {
|
||||
const wrapper = await open(plan({ live: "terrans up nav." }));
|
||||
expect(wrapper.emitted("confirm")).to.equal(undefined);
|
||||
|
||||
const ok = footerButton("Commit 1 move");
|
||||
const ok = footerButton("Play 1 move");
|
||||
expect(ok, "the confirm button should name what it is about to do").to.not.equal(undefined);
|
||||
ok.click();
|
||||
await Vue.nextTick();
|
||||
|
|
|
|||
|
|
@ -1,21 +1,12 @@
|
|||
<template>
|
||||
<!-- The one confirmation step sandbox mode has (ANALYSIS_MODE_PLAN.md §6/decision #13). Composing a
|
||||
turn inside the sandbox deliberately does NOT confirm (§12.4 - Undo covers a misclick and
|
||||
nothing there is real), but Commit is the single control that takes moves OUT of the sandbox
|
||||
and plays them for real, where Undo does not reach: move 1 is dispatched live and the rest are
|
||||
queued to fire by themselves, possibly with the app closed. It is also the moment the line is
|
||||
cleared, so anything not committed is gone - which is exactly why the moves being left behind
|
||||
are listed here too, rather than only the ones going out.
|
||||
Rendered exactly ONCE per page, by Commands.vue, for the same reason AnalysisModeInfo.vue is:
|
||||
AnalysisHeaderControls.vue is mounted twice (desktop title + mobile sticky bar) and two copies
|
||||
of one b-modal id make the button open whichever Bootstrap-Vue registered first. -->
|
||||
<!-- One confirmation for committing real moves, shared by desktop and mobile controls. -->
|
||||
<b-modal
|
||||
id="analysis-commit-confirm"
|
||||
size="lg"
|
||||
title="Commit these moves for real?"
|
||||
:title="view.live ? 'Play these moves?' : 'Queue these premoves?'"
|
||||
ok-variant="success"
|
||||
:ok-title="okTitle"
|
||||
cancel-title="Keep playing in the sandbox"
|
||||
cancel-title="Keep planning"
|
||||
:ok-disabled="total === 0"
|
||||
dialog-class="gaia-viewer-modal"
|
||||
@ok="$emit('confirm')"
|
||||
|
|
@ -23,6 +14,14 @@
|
|||
<p class="analysis-commit__lede">
|
||||
{{ lede }}
|
||||
</p>
|
||||
<p v-if="view.queued.length" class="small">
|
||||
Each premove uses your actual resources when your turn arrives. Simulated charges are not queued. If a move cannot
|
||||
be played then, the queue stops; it does not wait for more charges.
|
||||
</p>
|
||||
<p v-if="view.simulatedNeighbour" class="analysis-commit__neighbour">
|
||||
This Trading Station upgrade will only play at <strong>3c, plus ore</strong>. If that price is unavailable on your
|
||||
turn, the premoves stop. It will never spend 6c or wait for a neighbour.
|
||||
</p>
|
||||
|
||||
<ol class="analysis-commit__list">
|
||||
<li v-if="view.live" class="analysis-commit__row analysis-commit__row--live">
|
||||
|
|
@ -33,12 +32,16 @@
|
|||
<span class="analysis-commit__badge analysis-commit__badge--queued"
|
||||
>premove {{ i + 1 }}<template v-if="view.live"> · after your live move</template></span
|
||||
>
|
||||
<span v-if="view.timings" class="small text-muted">{{
|
||||
view.timings[i + (view.live ? 1 : 0)].round === 0
|
||||
? "Setup"
|
||||
: `Round ${view.timings[i + (view.live ? 1 : 0)].round}`
|
||||
}}</span>
|
||||
<span class="analysis-commit__move">{{ move }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<!-- Never silently truncate. A player who queued six moves in the sandbox and got four needs to
|
||||
know which two did not make it and why, before the line is cleared out from under them. -->
|
||||
<!-- Show the unsent tail; it stays in the local plan. -->
|
||||
<template v-if="view.dropped.length > 0">
|
||||
<p class="analysis-commit__dropped-head">
|
||||
{{ view.dropped.length }} more {{ view.dropped.length === 1 ? "move stays" : "moves stay" }} behind —
|
||||
|
|
@ -53,7 +56,8 @@
|
|||
</template>
|
||||
|
||||
<p class="analysis-commit__foot mb-0">
|
||||
{{ footer }}
|
||||
Your plans stay saved. Played moves are removed automatically.
|
||||
<span v-if="view.queued.length">This replaces your current queue. You can view or cancel it at any time.</span>
|
||||
</p>
|
||||
</b-modal>
|
||||
</template>
|
||||
|
|
@ -69,15 +73,13 @@ const EMPTY_PLAN: AnalysisCommitPlan = { live: null, queued: [], dropped: [], cu
|
|||
* because it is wording, not logic - the cut itself is decided by `analysisCommitPrefix`. */
|
||||
const CUT_TEXT: Record<AnalysisCommitCut, string> = {
|
||||
faction:
|
||||
"this line was played as a faction you picked in the sandbox, so none of it describes a move the real game would accept.",
|
||||
"cheap-build":
|
||||
"it includes a Trading Station the sandbox priced as if an opponent were next to it, so the rest of the line was played on credits you do not really have.",
|
||||
illegal: "the next move is not legal on the real board without the power you assumed in here.",
|
||||
"this plan was played as a faction you picked while planning, so none of it describes a move the real game would accept.",
|
||||
illegal: "the next move cannot be played on the current board.",
|
||||
overdrawn: "the next move would spend more than you actually have.",
|
||||
"assumed-power":
|
||||
"the next move only worked because the sandbox topped up your power — charge it for real first and it can be committed later.",
|
||||
"the next move only worked because the simulation added power — charge it for real first and it can be committed later.",
|
||||
foreign: "the next move belongs to another seat, and committing it would take somebody else's turn.",
|
||||
cap: `only ${MAX_COMMITTABLE_MOVES} moves can go out at once — one live plus a full premove queue.`,
|
||||
cap: `you can submit up to ${MAX_COMMITTABLE_MOVES} moves at once.`,
|
||||
};
|
||||
|
||||
export default Vue.extend({
|
||||
|
|
@ -87,9 +89,6 @@ export default Vue.extend({
|
|||
* Commands.vue holds `null` whenever Game.vue has no plan to give (outside sandbox mode, or a
|
||||
* line with nothing committable in it) - which would otherwise render this as `null.live`. */
|
||||
plan: { type: Object as () => AnalysisCommitPlan | null, default: null },
|
||||
/** How many lines the strip currently holds (§13) - only the footer reads it, to say honestly
|
||||
* that committing clears the OTHER lines too rather than only the one being played. */
|
||||
lineCount: { type: Number, default: 1 },
|
||||
},
|
||||
computed: {
|
||||
view(): AnalysisCommitPlan {
|
||||
|
|
@ -100,7 +99,7 @@ export default Vue.extend({
|
|||
return (view.live ? 1 : 0) + view.queued.length;
|
||||
},
|
||||
okTitle(): string {
|
||||
return `Commit ${this.total} move${this.total === 1 ? "" : "s"}`;
|
||||
return `${this.view.live ? "Play" : "Queue"} ${this.total} move${this.total === 1 ? "" : "s"}`;
|
||||
},
|
||||
lede(): string {
|
||||
const view = this.view as AnalysisCommitPlan;
|
||||
|
|
@ -109,34 +108,21 @@ export default Vue.extend({
|
|||
return "This move is played in the real game as soon as you confirm.";
|
||||
}
|
||||
if (view.live) {
|
||||
return `The first move is played in the real game as soon as you confirm. The other ${queued} ${
|
||||
queued === 1 ? "is queued as a premove" : "are queued as premoves"
|
||||
} and play by themselves, in this order, when your turn comes round again — even with the app closed.`;
|
||||
return "The first move plays now. The rest will play in order on your following turns, even with the browser closed.";
|
||||
}
|
||||
return `It is not your turn, so nothing is played immediately: all ${queued} ${
|
||||
queued === 1 ? "move is queued as a premove" : "moves are queued as premoves"
|
||||
} and play by themselves, in this order, when your turn comes — even with the app closed.`;
|
||||
return `${queued === 1 ? "This move will play" : "These moves will play in order"} on your next ${queued === 1 ? "turn" : "turns"}, even with the browser closed. Charge decisions are handled separately.`;
|
||||
},
|
||||
|
||||
droppedReason(): string {
|
||||
const view = this.view as AnalysisCommitPlan;
|
||||
if (view.limit === "no-premoves") {
|
||||
return "offline games have no premove queue, so only the move you play right now can be committed.";
|
||||
}
|
||||
if (view.limit === "queue") {
|
||||
return "your premove queue is full — cancel a queued move and commit again to send more.";
|
||||
return "you can queue up to three moves at once.";
|
||||
}
|
||||
return view.cut ? CUT_TEXT[view.cut] : "they are past what can be committed in one go.";
|
||||
},
|
||||
footer(): string {
|
||||
const view = this.view as AnalysisCommitPlan;
|
||||
const rest = view.dropped.length > 0 ? " The rest of the line is discarded with it." : "";
|
||||
// §13: the other lines go too, and the footer has to say so - they were alternatives to the
|
||||
// move about to be played for real, so leaving them would leave tabs describing a board the
|
||||
// game has left. Saying "this line" while silently clearing five would be the worse surprise.
|
||||
const lines = this.lineCount as number;
|
||||
const cleared = lines > 1 ? `clears all ${lines} of your lines` : "clears this line";
|
||||
return `Committing leaves the sandbox and ${cleared}.${rest} A queued premove can still be edited or cancelled from the premove bar until it plays.`;
|
||||
},
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -19,59 +19,42 @@ describe("AnalysisHeaderControls", () => {
|
|||
) as HTMLButtonElement;
|
||||
}
|
||||
|
||||
it("counts the line, in singular and plural", () => {
|
||||
expect(controls({ moveCount: 1 }).container.textContent).to.contain("1 move");
|
||||
expect(controls({ moveCount: 3 }).container.textContent).to.contain("3 moves");
|
||||
});
|
||||
|
||||
it("shows nothing about resources while the line stays affordable - the player board has them", () => {
|
||||
const { container } = controls({ moveCount: 2, status: { overdrawn: [], assumedPower: 0 } });
|
||||
expect(container.querySelector(".analysis-controls__overdrawn")).to.equal(null);
|
||||
expect(container.querySelector(".analysis-controls__assumed")).to.equal(null);
|
||||
});
|
||||
|
||||
it("summarises an overdraft, since the board scrolls off screen on mobile", () => {
|
||||
it("shows plan deltas rather than the negative balance, with a separate shortfall warning", () => {
|
||||
const { container } = controls({
|
||||
moveCount: 2,
|
||||
moveCount: 1,
|
||||
status: {
|
||||
overdrawn: [
|
||||
{ kind: "c", amount: -7 },
|
||||
{ kind: "o", amount: -1 },
|
||||
changes: [
|
||||
{ kind: "o", amount: -4 },
|
||||
{ kind: "vp", amount: 5 },
|
||||
],
|
||||
overdrawn: [{ kind: "o", amount: -2 }],
|
||||
assumedPower: 0,
|
||||
},
|
||||
});
|
||||
expect(container.querySelector(".analysis-controls__overdrawn").textContent.replace(/\s+/g, "")).to.equal("-7c-1o");
|
||||
expect(container.querySelector(".analysis-controls__resource").getAttribute("aria-label")).to.equal("-4 ore");
|
||||
expect(container.querySelector(".analysis-controls__shortfall").getAttribute("title")).to.contain("2 ore");
|
||||
expect(container.querySelectorAll(".analysis-controls__resource")[1].getAttribute("aria-label")).to.equal(
|
||||
"+5 victory points"
|
||||
);
|
||||
});
|
||||
|
||||
it("reports power the sandbox assumed was charged", () => {
|
||||
const { container } = controls({ moveCount: 1, status: { overdrawn: [], assumedPower: 3 } });
|
||||
expect(container.querySelector(".analysis-controls__assumed").textContent).to.contain("+3 power");
|
||||
});
|
||||
|
||||
it("keeps a running total of the Charge 1 presses, separately from the topped-up power", () => {
|
||||
// The two are different fictions - one the player asked for, one the sandbox did on its own - so
|
||||
// they get their own chips rather than being added together into one number.
|
||||
const { container } = controls({ moveCount: 2, status: { overdrawn: [], assumedPower: 3, chargedPower: 2 } });
|
||||
expect(container.querySelector(".analysis-controls__charged").textContent).to.contain("+2 charged");
|
||||
expect(container.querySelector(".analysis-controls__assumed").textContent).to.contain("+3 power");
|
||||
|
||||
const none = controls({ moveCount: 2, status: { overdrawn: [], assumedPower: 0, chargedPower: 0 } });
|
||||
expect(none.container.querySelector(".analysis-controls__charged")).to.equal(null);
|
||||
});
|
||||
|
||||
it("no longer carries Undo/Reset - they are map-corner icons beside the sandbox toggle now", () => {
|
||||
const { container } = controls({ moveCount: 2 });
|
||||
expect(button(container, "Undo")).to.equal(undefined);
|
||||
expect(button(container, "Reset")).to.equal(undefined);
|
||||
it("undoes and clears a plan through explicit controls, disabled for an empty plan", async () => {
|
||||
const { container, emitted } = controls({ canEdit: true });
|
||||
await fireEvent.click(button(container, "Undo"));
|
||||
await fireEvent.click(button(container, "Clear plan"));
|
||||
expect(emitted().undo).to.have.length(1);
|
||||
expect(emitted().reset).to.have.length(1);
|
||||
const empty = controls();
|
||||
expect(button(empty.container, "Undo").disabled).to.equal(true);
|
||||
expect(button(empty.container, "Clear plan").disabled).to.equal(true);
|
||||
});
|
||||
|
||||
it("only offers Commit once there is a line, and disables it while nothing in it is committable", async () => {
|
||||
expect(button(controls({ moveCount: 0 }).container, "Commit")).to.equal(undefined);
|
||||
expect(button(controls({ moveCount: 2, committableMoves: 0 }).container, "Commit").disabled).to.equal(true);
|
||||
expect(button(controls({ moveCount: 0 }).container, "Queue moves")).to.equal(undefined);
|
||||
expect(button(controls({ moveCount: 2, committableMoves: 0 }).container, "Queue moves").disabled).to.equal(true);
|
||||
|
||||
const { container, emitted } = controls({ moveCount: 2, committableMoves: 2 });
|
||||
const commit = button(container, "Commit");
|
||||
const commit = button(container, "Queue moves");
|
||||
expect(commit.disabled).to.equal(false);
|
||||
|
||||
await fireEvent.click(commit);
|
||||
|
|
|
|||
|
|
@ -1,44 +1,29 @@
|
|||
<template>
|
||||
<!-- Analysis mode's whole control surface (ANALYSIS_MODE_PLAN.md §12). It lives in the striped
|
||||
header because that header already exists, already says "not live", and is already the one
|
||||
thing still on screen on a phone once the map has scrolled away - so the separate panel above
|
||||
the map was a second container carrying nothing this one could not.
|
||||
@click.stop: a press on these controls must not read as a press on the header behind them. -->
|
||||
<div class="analysis-controls" @click.stop>
|
||||
<span class="analysis-controls__moves">{{ moveCount }} {{ moveCount === 1 ? "move" : "moves" }}</span>
|
||||
|
||||
<!-- The only numbers left. Everything per-resource is on the player board now, live, in the place
|
||||
players already read it; these three are what the board cannot say for itself. -->
|
||||
<span
|
||||
v-if="overdrawn.length > 0"
|
||||
class="analysis-controls__overdrawn"
|
||||
title="This line spends more than you have - the player board shows the same numbers in red"
|
||||
v-if="changes.length"
|
||||
class="analysis-controls__changes"
|
||||
title="Net resource and VP changes since this plan started"
|
||||
>
|
||||
<span v-for="item in overdrawn" :key="item.kind">{{ item.amount }}{{ item.kind }}</span>
|
||||
<span class="analysis-controls__label">Plan:</span>
|
||||
<span
|
||||
v-for="item in changes"
|
||||
:key="item.kind"
|
||||
class="analysis-controls__resource"
|
||||
:class="{ 'analysis-controls__resource--gain': item.amount > 0 }"
|
||||
:aria-label="`${item.amount > 0 ? '+' : ''}${item.amount} ${resourceName(item.kind)}`"
|
||||
>
|
||||
{{ item.amount > 0 ? "+" : "−" }}{{ Math.abs(item.amount) }}
|
||||
<svg width="18" height="18" viewBox="-10 -10 20 20" aria-hidden="true"><Resource :kind="item.kind" /></svg>
|
||||
</span>
|
||||
</span>
|
||||
<!-- The running total of Charge 1 presses. A charge and a later power spend both just move
|
||||
tokens between bowls, so once the line has spent it the board can read exactly as it did
|
||||
before - which made "did my charge land?" unanswerable from the board and left the player
|
||||
counting presses in their head. -->
|
||||
<span
|
||||
v-if="chargedPower > 0"
|
||||
class="analysis-controls__charged"
|
||||
title="Power you have told the sandbox to assume you charge (the Charge 1 button)"
|
||||
<span v-if="overdrawn.length || assumedPower" class="analysis-controls__shortfall" :title="shortfallTitle"
|
||||
>Needs resources</span
|
||||
>
|
||||
+{{ chargedPower }} charged
|
||||
</span>
|
||||
<span
|
||||
v-if="assumedPower > 0"
|
||||
class="analysis-controls__assumed"
|
||||
title="A power cost was more than this seat had, so the sandbox assumed that much was charged first"
|
||||
>
|
||||
+{{ assumedPower }} power
|
||||
</span>
|
||||
|
||||
<!-- Undo/Reset used to sit here. They are icons in the map's bottom-right corner now
|
||||
(SpaceMap.vue), beside the sandbox toggle itself, so the whole sandbox control cluster is in
|
||||
one place; Commit stays because it is the one control that leaves the sandbox for the real
|
||||
game, and it belongs next to the counts it acts on. -->
|
||||
<button class="analysis-controls__edit" :disabled="!canEdit" @click="$emit('undo')">Undo</button>
|
||||
<button class="analysis-controls__edit" :disabled="!canEdit" @click="$emit('reset')">Clear plan</button>
|
||||
<b-button
|
||||
v-if="moveCount > 0"
|
||||
size="sm"
|
||||
|
|
@ -48,7 +33,7 @@
|
|||
:title="commitTitle"
|
||||
@click="$emit('commit')"
|
||||
>
|
||||
Commit
|
||||
{{ playsNow ? "Play moves" : "Queue moves" }}
|
||||
</b-button>
|
||||
<!-- The modal itself is rendered once by Commands.vue (AnalysisModeInfo.vue) - see its comment for
|
||||
why it must not live in this twice-rendered component. -->
|
||||
|
|
@ -56,8 +41,8 @@
|
|||
variant="link"
|
||||
size="sm"
|
||||
class="analysis-controls__info"
|
||||
aria-label="How sandbox mode works"
|
||||
title="How sandbox mode works"
|
||||
aria-label="How planning works"
|
||||
title="How planning works"
|
||||
@click="$bvModal.show('analysis-mode-info')"
|
||||
>
|
||||
<b-badge variant="info" pill>i</b-badge>
|
||||
|
|
@ -67,30 +52,44 @@
|
|||
|
||||
<script lang="ts">
|
||||
import Vue from "vue";
|
||||
import type { AnalysisOverdraft, AnalysisStatus } from "../logic/analysis";
|
||||
import type { AnalysisOverdraft, AnalysisResourceChange, AnalysisStatus } from "../logic/analysis";
|
||||
import Resource from "./Resource.vue";
|
||||
|
||||
export default Vue.extend({
|
||||
name: "AnalysisHeaderControls",
|
||||
components: { Resource },
|
||||
methods: {
|
||||
resourceName(kind: string): string {
|
||||
return { c: "credits", o: "ore", k: "knowledge", q: "QIC", vp: "victory points" }[kind];
|
||||
},
|
||||
},
|
||||
props: {
|
||||
playsNow: Boolean,
|
||||
canEdit: Boolean,
|
||||
moveCount: { type: Number, default: 0 },
|
||||
status: { type: Object as () => AnalysisStatus | null, default: null },
|
||||
committableMoves: { type: Number, default: 0 },
|
||||
},
|
||||
computed: {
|
||||
changes(): AnalysisResourceChange[] {
|
||||
return this.status?.changes ?? [];
|
||||
},
|
||||
shortfallTitle(): string {
|
||||
const missing = this.overdrawn.map((item) => `${-item.amount} ${this.resourceName(item.kind)}`);
|
||||
if (this.assumedPower) missing.push(`${this.assumedPower} power`);
|
||||
return `This preview needs ${missing.join(", ")} beyond your current resources.`;
|
||||
},
|
||||
overdrawn(): AnalysisOverdraft[] {
|
||||
return (this.status as AnalysisStatus | null)?.overdrawn ?? [];
|
||||
},
|
||||
assumedPower(): number {
|
||||
return (this.status as AnalysisStatus | null)?.assumedPower ?? 0;
|
||||
},
|
||||
chargedPower(): number {
|
||||
return (this.status as AnalysisStatus | null)?.chargedPower ?? 0;
|
||||
},
|
||||
commitTitle(): string {
|
||||
const n = this.committableMoves as number;
|
||||
return n === 0
|
||||
? "Nothing in this line can be played for real yet"
|
||||
: `Play ${n} move${n === 1 ? "" : "s"} for real (first live, rest queued as premoves)`;
|
||||
? "Nothing in this plan can be played for real yet"
|
||||
: `Review ${n} move${n === 1 ? "" : "s"} before ${this.playsNow ? "playing" : "queuing"}`;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
@ -100,55 +99,56 @@ export default Vue.extend({
|
|||
.analysis-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
gap: 0.55rem;
|
||||
flex-wrap: wrap;
|
||||
margin-left: auto;
|
||||
font-size: 0.8rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
// The header behind these sits under yellow/black hazard stripes, so every text run needs its own
|
||||
// backing to stay legible (§5.1's "solid or scrimmed text backing, not raw text on stripes") - and
|
||||
// that backing has to be OPAQUE (owner report, 2026-08-20: "the 8 moves label is transparent making
|
||||
// it hard to read"). At rgba(0,0,0,0.55) the diagonals ran straight through the chip behind the
|
||||
// digits; the measured contrast was fine either way, but text on a moving pattern reads as a smear
|
||||
// regardless of its ratio. Same solid fill as Commands.vue's $analysis-scrim, kept in sync by eye
|
||||
// rather than by import - these are scoped styles and the variable lives in another component.
|
||||
.analysis-controls__moves,
|
||||
.analysis-controls__overdrawn,
|
||||
.analysis-controls__charged,
|
||||
.analysis-controls__assumed {
|
||||
white-space: nowrap;
|
||||
background: #1b1b20;
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.05rem 0.35rem;
|
||||
.analysis-controls__label {
|
||||
color: var(--ui-text-muted);
|
||||
}
|
||||
|
||||
.analysis-controls__moves {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.analysis-controls__overdrawn {
|
||||
display: flex;
|
||||
.analysis-controls__changes,
|
||||
.analysis-controls__resource {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
color: #ff8a80;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.analysis-controls__assumed {
|
||||
color: #ffe082;
|
||||
font-weight: 600;
|
||||
.analysis-controls__changes {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
// Deliberately a different colour from the assumed-power chip beside it: one is power the PLAYER
|
||||
// asked the sandbox to pretend they charged, the other is power the sandbox topped up on its own.
|
||||
.analysis-controls__charged {
|
||||
color: #80d8ff;
|
||||
font-weight: 600;
|
||||
.analysis-controls__resource {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.analysis-controls__resource--gain {
|
||||
color: var(--ui-success-text);
|
||||
}
|
||||
.analysis-controls__shortfall {
|
||||
color: var(--ui-warning-text);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.analysis-controls__edit {
|
||||
border: 0;
|
||||
border-left: 1px solid var(--ui-border);
|
||||
padding: 0.2rem 0.5rem;
|
||||
background: transparent;
|
||||
color: var(--ui-text);
|
||||
font: inherit;
|
||||
&:hover:enabled {
|
||||
color: var(--ui-info-text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
&:disabled {
|
||||
color: var(--ui-text-muted);
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.analysis-controls__btn {
|
||||
padding: 0.05rem 0.35rem;
|
||||
line-height: 1.2;
|
||||
padding: 0.25rem 0.6rem;
|
||||
line-height: 1.3;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
|
|
@ -165,7 +165,7 @@ export default Vue.extend({
|
|||
}
|
||||
|
||||
.analysis-controls__btn.btn-success {
|
||||
border-radius: 10px;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 1px 2px var(--ui-shadow-soft);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ Vue.use(BootstrapVue);
|
|||
// presses, which is what keeps the two copies from ever disagreeing about which tab is open.
|
||||
describe("AnalysisLineTabs", () => {
|
||||
const line = (over: Partial<AnalysisLineSummary> = {}): AnalysisLineSummary => ({
|
||||
label: "Line 1",
|
||||
label: "Plan A",
|
||||
moves: 0,
|
||||
victoryPoints: 0,
|
||||
overdrawn: false,
|
||||
|
|
@ -39,27 +39,26 @@ describe("AnalysisLineTabs", () => {
|
|||
.trim();
|
||||
}
|
||||
|
||||
it("numbers the tabs rather than naming them", () => {
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 0 });
|
||||
expect(tabButtons(container).map(tabText)).to.deep.equal(["Line 1", "Line 2"]);
|
||||
it("labels alternative plans alphabetically", () => {
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 0 });
|
||||
expect(tabButtons(container).map(tabText)).to.deep.equal(["Plan A", "Plan B"]);
|
||||
});
|
||||
|
||||
it("marks the open tab, and only it", () => {
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 1 });
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 1 });
|
||||
const marked = tabButtons(container).map((b) => b.classList.contains("analysis-tabs__tab--active"));
|
||||
expect(marked).to.deep.equal([false, true]);
|
||||
});
|
||||
|
||||
// The reason the strip is a comparison and not a bookmark list: switching replaces the board, so
|
||||
// every line's outcome has to be readable without switching to it.
|
||||
it("puts each line's own VP on its own tab", () => {
|
||||
it("keeps VP changes out of the tabs", () => {
|
||||
const { container } = tabs({
|
||||
lines: [line({ moves: 3, victoryPoints: 7 }), line({ label: "Line 2", moves: 2, victoryPoints: -2 })],
|
||||
lines: [
|
||||
line({ moves: 3, applied: 3, victoryPoints: 7 }),
|
||||
line({ label: "Plan B", moves: 2, applied: 2, victoryPoints: -2 }),
|
||||
],
|
||||
active: 0,
|
||||
});
|
||||
const text = tabButtons(container).map(tabText);
|
||||
expect(text[0]).to.contain("+7");
|
||||
expect(text[1]).to.contain("-2");
|
||||
expect(tabButtons(container).map(tabText)).to.deep.equal(["Plan A", "Plan B"]);
|
||||
});
|
||||
|
||||
it("says nothing about VP for a line with nothing played yet", () => {
|
||||
|
|
@ -80,7 +79,7 @@ describe("AnalysisLineTabs", () => {
|
|||
});
|
||||
|
||||
it("reports a press on a tab as a line to open", async () => {
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 0 });
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 0 });
|
||||
await fireEvent.click(tabButtons(container)[1]);
|
||||
expect(emitted().select[0]).to.deep.equal([1]);
|
||||
});
|
||||
|
|
@ -96,15 +95,17 @@ describe("AnalysisLineTabs", () => {
|
|||
it("says the plus carries the open line on, once that line has something in it", () => {
|
||||
const withMoves = tabs({ lines: [line({ moves: 3, victoryPoints: 5, applied: 3 })], active: 0 });
|
||||
expect(withMoves.container.querySelector(".analysis-tabs__add").getAttribute("title")).to.contain(
|
||||
"Carry on from here"
|
||||
"Try a variation of Plan A"
|
||||
);
|
||||
|
||||
const empty = tabs({ lines: [line()], active: 0 });
|
||||
expect(empty.container.querySelector(".analysis-tabs__add").getAttribute("title")).to.contain("Start another line");
|
||||
expect(empty.container.querySelector(".analysis-tabs__add").getAttribute("title")).to.contain("Start another plan");
|
||||
});
|
||||
|
||||
it("stops offering new lines at the cap", () => {
|
||||
const lines = Array.from({ length: MAX_ANALYSIS_LINES }, (_, i) => line({ label: `Line ${i + 1}` }));
|
||||
const lines = Array.from({ length: MAX_ANALYSIS_LINES }, (_, i) =>
|
||||
line({ label: `Plan ${String.fromCharCode(65 + i)}` })
|
||||
);
|
||||
const { container } = tabs({ lines, active: 0 });
|
||||
expect((container.querySelector(".analysis-tabs__add") as HTMLButtonElement).disabled).to.equal(true);
|
||||
});
|
||||
|
|
@ -117,21 +118,21 @@ describe("AnalysisLineTabs", () => {
|
|||
});
|
||||
|
||||
it("puts delete inside the open tab, and nowhere else", () => {
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 1 });
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 1 });
|
||||
const closes = container.querySelectorAll(".analysis-tabs__close");
|
||||
expect(closes.length).to.equal(1);
|
||||
expect(tabButtons(container)[1].contains(closes[0])).to.equal(true);
|
||||
});
|
||||
|
||||
it("reports delete against the open line, without also selecting it", async () => {
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 1 });
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 1 });
|
||||
await fireEvent.click(container.querySelector(".analysis-tabs__close"));
|
||||
expect(emitted().close[0]).to.deep.equal([1]);
|
||||
expect(emitted().select).to.equal(undefined);
|
||||
});
|
||||
|
||||
it("opens a line from the keyboard", async () => {
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 0 });
|
||||
const { container, emitted } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 0 });
|
||||
await fireEvent.keyDown(tabButtons(container)[1], { key: "Enter", code: "Enter" });
|
||||
expect(emitted().select[0]).to.deep.equal([1]);
|
||||
});
|
||||
|
|
@ -139,7 +140,7 @@ describe("AnalysisLineTabs", () => {
|
|||
// Load-bearing: the striped header these sit on is click-to-exit, so a press that reached it would
|
||||
// close the sandbox instead of switching lines.
|
||||
it("keeps a press on the strip off the header behind it", async () => {
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Line 2" })], active: 0 });
|
||||
const { container } = tabs({ lines: [line(), line({ label: "Plan B" })], active: 0 });
|
||||
const host = document.createElement("div");
|
||||
let reachedHeader = false;
|
||||
host.addEventListener("click", () => (reachedHeader = true));
|
||||
|
|
|
|||
|
|
@ -1,20 +1,5 @@
|
|||
<template>
|
||||
<!--
|
||||
The sandbox's line strip (ANALYSIS_MODE_PLAN.md §13) - one tab per line you are working out,
|
||||
sitting on top of the striped header like browser tabs on a toolbar.
|
||||
|
||||
There is no Save button. Every line autosaves on every completed turn, exactly as the single line
|
||||
always has (Game.vue's setAnalysisEntries), so "saving" was never a thing the player had to do -
|
||||
a Save button would only have introduced a second meaning of saved and, with it, the question of
|
||||
whether unsaved work could be lost. Line 1 therefore exists from the moment the sandbox opens and
|
||||
`+` adds the next one; there is no zero state.
|
||||
|
||||
@click.stop on the root is load-bearing, not defensive: the striped header this sits on is
|
||||
click-to-exit (§5.4, Commands.vue's .sticky-bar-title--analysis / #move-title.move-title--analysis
|
||||
both bind it), so without it every press on a tab would also close the sandbox - and the press
|
||||
would land as "exit" rather than "switch line", which is the worst possible reading of it.
|
||||
-->
|
||||
<div class="analysis-tabs" @click.stop>
|
||||
<div class="analysis-tabs" role="tablist" aria-label="Alternative plans" @click.stop>
|
||||
<!-- A div rather than a <button>, because the delete control lives INSIDE the open tab and a
|
||||
button inside a button is invalid markup that browsers silently un-nest. It was a sibling
|
||||
after the last tab first, which put the ✕ visually against whichever line happened to be
|
||||
|
|
@ -35,12 +20,19 @@
|
|||
@keydown.space.prevent="$emit('select', index)"
|
||||
>
|
||||
<span class="analysis-tabs__label">{{ line.label }}</span>
|
||||
<!-- The outcome, on the tab itself. Without it the strip would only let you SWITCH between
|
||||
lines, and switching replaces the board - so comparing would mean holding line A in your
|
||||
head while reading line B, which is the exact job the sandbox exists to take off you. -->
|
||||
<span v-if="line.moves > 0" class="analysis-tabs__vp" :class="vpClass(line)">{{ vpLabel(line) }}</span>
|
||||
<span v-if="line.overdrawn" class="analysis-tabs__flag analysis-tabs__flag--overdrawn" aria-hidden="true">!</span>
|
||||
<span v-else-if="line.applied < line.moves" class="analysis-tabs__flag" aria-hidden="true">~</span>
|
||||
<span
|
||||
v-if="line.overdrawn || line.applied < line.moves"
|
||||
class="analysis-tabs__flag"
|
||||
:class="{ 'analysis-tabs__flag--overdrawn': line.overdrawn }"
|
||||
role="img"
|
||||
:aria-label="line.overdrawn ? 'Needs resources' : 'Some moves no longer apply'"
|
||||
:title="line.overdrawn ? 'Needs resources' : 'Some moves no longer apply'"
|
||||
>
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<rect x="7" y="3.5" width="2" height="5.5" rx="1" />
|
||||
<circle cx="8" cy="11.5" r="1" />
|
||||
</svg>
|
||||
</span>
|
||||
<!-- Offered on the open tab only, and never on the last line. Both restrictions are about the
|
||||
strip staying a comparison rather than becoming a file manager: an ✕ on every tab is five
|
||||
ways to lose work sitting one mis-tap from the control used to switch between them.
|
||||
|
|
@ -68,7 +60,7 @@
|
|||
:aria-label="addTitle"
|
||||
@click="$emit('add')"
|
||||
>
|
||||
+
|
||||
<span aria-hidden="true">+</span> Variation
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -91,35 +83,21 @@ export default Vue.extend({
|
|||
addTitle(): string {
|
||||
const lines = this.lines as AnalysisLineSummary[];
|
||||
if (lines.length >= MAX_ANALYSIS_LINES) {
|
||||
return `${MAX_ANALYSIS_LINES} lines is the most that fits - delete one to start another`;
|
||||
return `You can compare up to ${MAX_ANALYSIS_LINES} plans. Delete one to try another.`;
|
||||
}
|
||||
const open = lines[this.active as number];
|
||||
// An empty line has nothing to fork, so the copy wording would only be confusing there.
|
||||
return open && open.moves > 0
|
||||
? "Carry on from here in a new line - this one is kept as it is"
|
||||
: "Start another line from the same board";
|
||||
? `Try a variation of ${open.label}; the original plan is kept`
|
||||
: "Start another plan from the same board";
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
vpLabel(line: AnalysisLineSummary): string {
|
||||
return `${line.victoryPoints >= 0 ? "+" : ""}${line.victoryPoints}`;
|
||||
},
|
||||
vpClass(line: AnalysisLineSummary): string | null {
|
||||
return line.victoryPoints > 0
|
||||
? "analysis-tabs__vp--gain"
|
||||
: line.victoryPoints < 0
|
||||
? "analysis-tabs__vp--loss"
|
||||
: null;
|
||||
},
|
||||
tabTitle(line: AnalysisLineSummary, index: number): string {
|
||||
if (line.moves === 0) {
|
||||
return `${line.label} - nothing played yet`;
|
||||
}
|
||||
const parts = [
|
||||
`${line.label}: ${line.moves} move${line.moves === 1 ? "" : "s"}, ${this.vpLabel(
|
||||
line
|
||||
)} VP against where the sandbox started`,
|
||||
];
|
||||
const parts = [`${line.label}: ${line.moves} move${line.moves === 1 ? "" : "s"}`];
|
||||
if (line.overdrawn) {
|
||||
parts.push("spends more than this seat has");
|
||||
}
|
||||
|
|
@ -136,123 +114,80 @@ export default Vue.extend({
|
|||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
// Sits directly on the yellow/black hazard stripes, so - like every other text run up there - each
|
||||
// tab carries its own OPAQUE fill rather than a scrim (see AnalysisHeaderControls.vue's note on why
|
||||
// an alpha is not good enough here, however good its contrast ratio measures).
|
||||
$tab-active: #1b1b20;
|
||||
$tab-idle: #3d3d46;
|
||||
|
||||
.analysis-tabs {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 0.2rem;
|
||||
// No rail of its own: the striped banner the strip rests on IS the rail, and the tabs overlap its
|
||||
// top edge by a few pixels (Commands.vue's negative bottom margin) to join the two. A rail here
|
||||
// used to stand in for that while the strip lived inside the banner, and it now only drew a dark
|
||||
// line across the banner's top edge.
|
||||
// Five tabs plus the two controls do not fit one row on a narrow phone. Scrolling the strip is the
|
||||
// only option that keeps the header one row tall; wrapping would grow the mobile sticky sheet by a
|
||||
// whole line every time a tab was added.
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
border-bottom: 1px solid var(--ui-border);
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none;
|
||||
max-width: 100%;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.analysis-tabs__tab {
|
||||
.analysis-tabs__tab,
|
||||
.analysis-tabs__add {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
gap: 0.4rem;
|
||||
border: 0;
|
||||
user-select: none;
|
||||
// The "half dome" - rounded on top, square where it meets the rail.
|
||||
border-radius: 0.55rem 0.55rem 0 0;
|
||||
padding: 0.1rem 0.45rem;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 0;
|
||||
padding: 0.55rem 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
background: $tab-idle;
|
||||
color: #d8d8e0;
|
||||
background: transparent;
|
||||
color: var(--ui-text-muted);
|
||||
}
|
||||
|
||||
.analysis-tabs__tab--active {
|
||||
background: $tab-active;
|
||||
color: #fff;
|
||||
// Picks up the stripe's own amber so the open tab is identifiable at a glance rather than by
|
||||
// comparing two dark greys.
|
||||
box-shadow: inset 0 2px 0 #c2a233;
|
||||
border-bottom-color: var(--ui-info-text);
|
||||
font-weight: 600;
|
||||
color: var(--ui-info-text);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.analysis-tabs__vp {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 700;
|
||||
color: #b9b9c4;
|
||||
}
|
||||
|
||||
.analysis-tabs__vp--gain {
|
||||
color: #a5d6a7;
|
||||
}
|
||||
|
||||
.analysis-tabs__vp--loss {
|
||||
color: #ff8a80;
|
||||
}
|
||||
|
||||
// Overdrawn: the VP on this tab was bought with resources the seat does not have, so it is not
|
||||
// comparable to a payable line without saying so. Same red as the header's overdraft chip.
|
||||
.analysis-tabs__flag {
|
||||
font-weight: 700;
|
||||
color: #ffe082;
|
||||
}
|
||||
|
||||
.analysis-tabs__flag--overdrawn {
|
||||
color: #ff8a80;
|
||||
}
|
||||
|
||||
.analysis-tabs__add {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
border: 0;
|
||||
border-radius: 0.55rem 0.55rem 0 0;
|
||||
padding: 0.1rem 0.45rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.45;
|
||||
cursor: pointer;
|
||||
background: $tab-idle;
|
||||
color: #fff;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
border-radius: 50%;
|
||||
background: var(--ui-warning-text);
|
||||
color: var(--ui-warning-bg);
|
||||
svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
fill: currentColor;
|
||||
}
|
||||
}
|
||||
.analysis-tabs__add {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 400;
|
||||
&:hover:enabled {
|
||||
color: var(--ui-info-text);
|
||||
}
|
||||
}
|
||||
|
||||
.analysis-tabs__add:disabled {
|
||||
// Full opacity on purpose - a faded control on diagonal stripes is the unreadable state, the same
|
||||
// trap the Commit button's own disabled styling had to be written around.
|
||||
opacity: 1;
|
||||
color: #8b8b96;
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
// Sits inside the open tab, so it is deliberately quiet until pointed at: it is the one control up
|
||||
// here that destroys something, and it shares its tap target's neighbourhood with the control used
|
||||
// to switch lines.
|
||||
.analysis-tabs__close {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #8f8f9b;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
padding: 0.1rem 0.1rem 0.1rem 0.15rem;
|
||||
color: var(--ui-text-muted);
|
||||
font-size: 0.65rem;
|
||||
padding: 0.15rem;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover,
|
||||
&:focus {
|
||||
color: #ff8a80;
|
||||
color: var(--ui-danger-text);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -5,51 +5,41 @@
|
|||
AnalysisHeaderControls.vue - that component is rendered twice (desktop title and mobile sticky
|
||||
bar), and two copies of one b-modal id make the button open whichever Bootstrap-Vue registered
|
||||
first, which is the bug SetupStatus.vue's own comment warns about. -->
|
||||
<b-modal id="analysis-mode-info" size="lg" title="How sandbox mode works" ok-only dialog-class="gaia-viewer-modal">
|
||||
<b-modal id="analysis-mode-info" size="lg" title="How planning works" ok-only dialog-class="gaia-viewer-modal">
|
||||
<p>
|
||||
The board is yours to play with. Nothing here is saved and nobody else can see it — leave with the button at the
|
||||
bottom right of the map and the real game is exactly as you left it.
|
||||
Try moves using the normal game controls. This is a private simulation: nothing is played in the real game until
|
||||
you confirm.
|
||||
</p>
|
||||
<h6>Compare plans</h6>
|
||||
<p>
|
||||
Each tab is an alternative plan: <strong>Plan A</strong>, <strong>Plan B</strong>, and so on. Use
|
||||
<strong>+</strong> to copy the current plan and try a variation. The selected plan shows its resource and VP
|
||||
changes together. Undo removes the last move; Clear starts that plan again. Drafts are saved in this browser.
|
||||
Saving a queue keeps all your plans. When you play a matching move, manually or by premove, it is removed from
|
||||
each plan so you can continue with the remaining moves.
|
||||
</p>
|
||||
<h6>Try future possibilities</h6>
|
||||
<p>
|
||||
Each move must be affordable with the resources shown on your faction board. Income and conversions update the
|
||||
available choices.
|
||||
<strong>Simulate charge +1</strong> previews receiving a power charge. This is not a game action and does not add
|
||||
a condition to your premoves. Simulated resources never change the real game.
|
||||
</p>
|
||||
<p>
|
||||
You are not limited to what you can afford. Spend past your resources and the player board shows the shortfall as
|
||||
a negative number, which is the answer to "can I actually do this?". Power is the exception: its bowls hold tokens
|
||||
rather than a balance, so a power cost you cannot cover is topped up and counted in the header as assumed power.
|
||||
<strong>Simulate neighbour</strong> previews the lower Trading Station price. Queuing it keeps a 3-credit limit,
|
||||
plus ore. If that price is unavailable on your turn, the premoves stop instead of spending 6 credits.
|
||||
</p>
|
||||
<p>
|
||||
Charge 1 hands you one charged power, as many times as you like, for the leech an opponent would realistically
|
||||
have offered you. The header keeps a running total of what you have charged that way, because once a later move
|
||||
spends it the bowls can read exactly as they did before. Undo Charge takes the last one back.
|
||||
</p>
|
||||
<p>
|
||||
Every move is added to the line as soon as it is complete — there is no confirmation step. Undo removes the last
|
||||
one, Reset clears them all.
|
||||
</p>
|
||||
<p>
|
||||
The tabs along the top of this header are your lines. Line 1 is there from the start;
|
||||
<strong>+</strong> carries the line you are on into a new tab so you can take it somewhere else from here, leaving
|
||||
the old one exactly as it was — Reset blanks the new one if you would rather start over. Clicking a tab opens that
|
||||
line to carry on, undo or reset exactly as you would any other. Nothing needs saving — each line is kept as you
|
||||
play it, and is still there when you come back. Each tab carries its own result, so you can read what a line came
|
||||
to without opening it: how many points ahead of where the sandbox started it ends, a red <strong>!</strong> if it
|
||||
spends more than you have, and a <strong>~</strong> if the board has since moved on and part of that line no
|
||||
longer applies.
|
||||
</p>
|
||||
<p>
|
||||
Opponents never move, apart from the starting mines you place for them yourself during setup. Their round boosters
|
||||
are picked for them, and any power they would be offered is declined automatically, so a build never pauses on
|
||||
somebody else's decision. If someone takes their turn in the real game while you are in here, your line is
|
||||
replayed against the new board rather than thrown away — you are only told about it if part of it stops working.
|
||||
</p>
|
||||
<p>
|
||||
A line runs to the end of the round after the one it started in. Board actions, tech tiles, boosters and
|
||||
federation tiles are all shown as available, so a line assumes nobody beats you to any of them.
|
||||
Other players stay still in the simulation. A plan can continue across rounds and assumes nobody takes the actions
|
||||
or tiles you need. Live opponent moves and auto-charge update the position underneath your plan.
|
||||
</p>
|
||||
<h6>Save premoves</h6>
|
||||
<p class="mb-0">
|
||||
Commit plays the line for real: the first move goes live and the rest queue as premoves, up to four moves in all
|
||||
(one live plus the premove queue's three rows). It asks first, listing exactly what will be played and what will
|
||||
be left behind — nothing leaves the sandbox until you confirm. Only moves that are your own and affordable without
|
||||
overspending are offered, so a move that needed assumed power ends the list there. Committing clears every line,
|
||||
not just the one it played: the others were alternatives to the move you have now actually made.
|
||||
Finish a simulated turn, then choose <strong>Queue moves</strong>. Only the selected plan is submitted, with up to
|
||||
three complete turns. If it is your turn, <strong>Play moves</strong> plays the first immediately. The rest run on
|
||||
your following turns, even with the browser closed. Moves for later rounds wait for their round and phase. You can
|
||||
view or cancel them at any time. If a move cannot be played with your actual resources when your turn arrives, the
|
||||
queue stops. It does not wait for a charge or another player's move.
|
||||
</p>
|
||||
</b-modal>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ describe("AnalysisPanel", () => {
|
|||
};
|
||||
const { container } = render(AnalysisPanel, { props: { active: true, pendingRestore } });
|
||||
const text = container.querySelector(".analysis-strip").textContent;
|
||||
expect(text).to.contain("3 saved sandbox lines");
|
||||
expect(text).to.contain("3 saved plans");
|
||||
expect(text).to.contain("2 moves in total");
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,31 +1,13 @@
|
|||
<template>
|
||||
<!--
|
||||
What is left of analysis mode's own surface once §12 moved every control into the striped header
|
||||
and every number onto the player board: the two things that genuinely cannot live in either.
|
||||
|
||||
Staleness notices and the "a saved line exists" prompt (§3.5), and nothing else. Both have to be
|
||||
readable while sandbox mode is NOT active, which is exactly why they cannot live in Commands.vue:
|
||||
it is not rendered then.
|
||||
|
||||
Round 0's faction picker used to be here too. It moved into Commands.vue's action area on owner
|
||||
instruction - every press the player makes inside the sandbox belongs on that one surface, and a
|
||||
second container above the map is nowhere near it on a phone.
|
||||
|
||||
Deliberately NOT a container announcing sandbox mode: the hazard-striped header and map already
|
||||
do that, and the yellow box that used to sit here said it a third time while carrying resource
|
||||
rows the player board now shows live.
|
||||
-->
|
||||
<!-- Planning notices and recovery after a rollback. -->
|
||||
<div v-if="notice || pendingRestore" class="analysis-strip">
|
||||
<div v-if="notice" class="analysis-strip__banner">
|
||||
<span class="flex-grow-1">{{ notice }}</span>
|
||||
<button type="button" class="analysis-strip__banner-x" @click="$emit('dismiss-notice')">✕</button>
|
||||
</div>
|
||||
|
||||
<!-- The "own seat moved since this was saved" row of §3.5's table - prompts instead of silently
|
||||
replaying, mirroring PremoveBar.vue's inline mode-switch confirm rather than a raw
|
||||
window.confirm. -->
|
||||
<div v-if="active && pendingRestore" class="analysis-strip__banner analysis-strip__banner--confirm">
|
||||
<span class="flex-grow-1"> {{ pendingRestoreLabel }} from before your last move. </span>
|
||||
<span class="flex-grow-1"> {{ pendingRestoreLabel }} from a different board position. </span>
|
||||
<b-button size="sm" variant="outline-secondary" class="mr-1" @click="$emit('restore')">Restore anyway</b-button>
|
||||
<b-button size="sm" variant="outline-secondary" @click="$emit('discard-restore')">Discard</b-button>
|
||||
</div>
|
||||
|
|
@ -56,8 +38,8 @@ export default Vue.extend({
|
|||
const moves = analysisLineSetSize(set);
|
||||
const moveText = `${moves} move${moves === 1 ? "" : "s"}`;
|
||||
return set.lines.length > 1
|
||||
? `${set.lines.length} saved sandbox lines (${moveText} in total) exist`
|
||||
: `A saved sandbox line (${moveText}) exists`;
|
||||
? `${set.lines.length} saved plans (${moveText} in total) exist`
|
||||
: `A saved plan (${moveText}) exists`;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
|
|||
52
viewer/src/components/AutoChargeControl.spec.ts
Normal file
52
viewer/src/components/AutoChargeControl.spec.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import Engine, { PlayerEnum } from "@gaia-project/engine";
|
||||
import { fireEvent, render } from "@testing-library/vue";
|
||||
import BootstrapVue from "bootstrap-vue";
|
||||
import { expect } from "chai";
|
||||
import Vue from "vue";
|
||||
import { makeStore } from "../store";
|
||||
import AutoChargeControl from "./AutoChargeControl.vue";
|
||||
Vue.use(BootstrapVue);
|
||||
|
||||
describe("AutoChargeControl", () => {
|
||||
it("displays server settings and requests changes without overwriting local preferences", async () => {
|
||||
const store = makeStore();
|
||||
store.commit("hosted", true);
|
||||
store.commit("preferences", { autoChargePower: "1" });
|
||||
store.commit("playerSettings", { autoCharge: "3" });
|
||||
let update: unknown;
|
||||
store.subscribeAction(({ type, payload }) => {
|
||||
if (type === "updatePlayerSetting") update = payload;
|
||||
});
|
||||
const control = render(AutoChargeControl, { store });
|
||||
expect(control.container.textContent).to.contain("Charge: 3");
|
||||
await fireEvent.click(control.getByText("Auto-charge: up to 4 power"));
|
||||
expect(update).to.deep.equal({ name: "autoCharge", value: "4" });
|
||||
expect(store.state.preferences.autoChargePower).to.equal("1");
|
||||
expect(control.container.textContent).to.contain("Charge: 3");
|
||||
store.commit("playerSettings", { autoCharge: "4" });
|
||||
await Vue.nextTick();
|
||||
expect(control.container.textContent).to.contain("Charge: 4");
|
||||
});
|
||||
|
||||
it("offers the passed cap for the viewing seat outside its turn", async () => {
|
||||
const store = makeStore();
|
||||
const engine = new Engine(["init 2 auto-charge-control"]);
|
||||
engine.currentPlayer = PlayerEnum.Player1;
|
||||
engine.passedPlayers = [PlayerEnum.Player2];
|
||||
store.commit("receiveData", engine);
|
||||
store.commit("hosted", true);
|
||||
store.commit("player", { index: PlayerEnum.Player2 });
|
||||
store.commit("playerSettings", { autoCharge: "4", autoChargeMaxPassedRoundLeech: "3" });
|
||||
const control = render(AutoChargeControl, { store });
|
||||
expect(control.container.textContent).to.contain("Charge: 4 cap 3");
|
||||
expect(control.queryByText("After passing: max 5 total power")).to.not.equal(null);
|
||||
expect(control.queryByText("After passing: max 6 total power")).to.equal(null);
|
||||
});
|
||||
|
||||
it("keeps standalone auto-charge working locally", async () => {
|
||||
const store = makeStore();
|
||||
const control = render(AutoChargeControl, { store });
|
||||
await fireEvent.click(control.getByText("Auto-charge: up to 2 power"));
|
||||
expect(store.state.preferences.autoChargePower).to.equal("2");
|
||||
});
|
||||
});
|
||||
155
viewer/src/components/AutoChargeControl.vue
Normal file
155
viewer/src/components/AutoChargeControl.vue
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
<template>
|
||||
<b-dropdown
|
||||
size="sm"
|
||||
variant="outline-secondary"
|
||||
right
|
||||
:dropup="dropup"
|
||||
boundary="window"
|
||||
:popper-opts="{ positionFixed: true }"
|
||||
class="auto-leech-select"
|
||||
title="Auto-charge: automatically accept or decline power-charge offers up to this amount, instead of asking every time"
|
||||
>
|
||||
<template #button-content>
|
||||
<span class="auto-leech-dot" :class="autoChargePowerActive ? 'active' : 'inactive'"></span>
|
||||
{{ autoChargePowerShortLabel }}
|
||||
</template>
|
||||
<b-dropdown-item
|
||||
v-for="opt in autoChargePowerOptions"
|
||||
:key="opt.value"
|
||||
:active="opt.value === autoChargePower"
|
||||
@click="setAutoChargePower(opt.value)"
|
||||
>
|
||||
{{ opt.text }}
|
||||
</b-dropdown-item>
|
||||
<template v-if="showAutoChargePassedCapOptions">
|
||||
<b-dropdown-divider />
|
||||
<b-dropdown-item
|
||||
v-for="opt in autoChargePassedCapOptions"
|
||||
:key="`passed-${opt.value}`"
|
||||
:active="opt.value === autoChargeMaxPassedRoundLeech"
|
||||
@click="setAutoChargeMaxPassedRoundLeech(opt.value)"
|
||||
>
|
||||
{{ opt.text }}
|
||||
</b-dropdown-item>
|
||||
</template>
|
||||
</b-dropdown>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-property-decorator";
|
||||
@Component
|
||||
export default class AutoChargeControl extends Vue {
|
||||
@Prop({ default: false }) dropup: boolean;
|
||||
get autoChargePower(): string {
|
||||
return String(
|
||||
this.$store.state.hosted
|
||||
? (this.$store.state.playerSettings?.autoCharge ?? "ask")
|
||||
: (this.$store.state.preferences.autoChargePower ?? "ask")
|
||||
);
|
||||
}
|
||||
|
||||
get autoChargeMaxPassedRoundLeech(): string {
|
||||
return String(
|
||||
this.$store.state.hosted
|
||||
? (this.$store.state.playerSettings?.autoChargeMaxPassedRoundLeech ?? "0")
|
||||
: (this.$store.state.preferences.autoChargeMaxPassedRoundLeech ?? "0")
|
||||
);
|
||||
}
|
||||
|
||||
get autoChargePowerOptions() {
|
||||
return [
|
||||
{ value: "ask", text: "Auto-charge: off (ask every time)" },
|
||||
{ value: "decline-cost", text: "Auto-charge: free only (decline anything with a cost)" },
|
||||
{ value: "1", text: "Auto-charge: up to 1 power" },
|
||||
{ value: "2", text: "Auto-charge: up to 2 power" },
|
||||
{ value: "3", text: "Auto-charge: up to 3 power" },
|
||||
{ value: "4", text: "Auto-charge: up to 4 power" },
|
||||
{ value: "5", text: "Auto-charge: up to 5 power" },
|
||||
];
|
||||
}
|
||||
|
||||
get autoChargePassedCapOptions() {
|
||||
return [
|
||||
{ value: "0", text: "After passing: no total cap" },
|
||||
{ value: "1", text: "After passing: max 1 total power" },
|
||||
{ value: "2", text: "After passing: max 2 total power" },
|
||||
{ value: "3", text: "After passing: max 3 total power" },
|
||||
{ value: "4", text: "After passing: max 4 total power" },
|
||||
{ value: "5", text: "After passing: max 5 total power" },
|
||||
];
|
||||
}
|
||||
|
||||
get showAutoChargePassedCapOptions(): boolean {
|
||||
const player = this.$store.state.player?.index ?? this.$store.state.data.currentPlayer;
|
||||
return player !== undefined && (this.$store.state.data.passedPlayers ?? []).includes(player);
|
||||
}
|
||||
|
||||
setAutoChargePower(value: string) {
|
||||
if (this.$store.state.hosted) this.$store.dispatch("updatePlayerSetting", { name: "autoCharge", value });
|
||||
else this.$store.commit("preferences", { autoChargePower: value });
|
||||
}
|
||||
|
||||
setAutoChargeMaxPassedRoundLeech(value: string) {
|
||||
if (this.$store.state.hosted)
|
||||
this.$store.dispatch("updatePlayerSetting", { name: "autoChargeMaxPassedRoundLeech", value });
|
||||
else this.$store.commit("preferences", { autoChargeMaxPassedRoundLeech: value });
|
||||
}
|
||||
|
||||
get autoChargePowerActive(): boolean {
|
||||
return this.autoChargePower !== "ask";
|
||||
}
|
||||
|
||||
/** Short label for the auto-leech dropdown button itself - the full sentence lives in the menu
|
||||
* options (autoChargePowerOptions), not on the button, so the button doesn't force the status
|
||||
* line next to it to wrap. */
|
||||
get autoChargePowerShortLabel(): string {
|
||||
const cap = this.showAutoChargePassedCapOptions ? this.autoChargeMaxPassedRoundLeech : "0";
|
||||
switch (this.autoChargePower) {
|
||||
case "ask":
|
||||
return "Charge: off";
|
||||
case "decline-cost":
|
||||
return cap === "0" ? "Charge: free" : `Charge: free cap ${cap}`;
|
||||
default:
|
||||
return cap === "0" ? `Charge: ${this.autoChargePower}` : `Charge: ${this.autoChargePower} cap ${cap}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.auto-leech-select ::v-deep(.dropdown-menu) {
|
||||
max-width: calc(100vw - 16px);
|
||||
min-width: min(24rem, calc(100vw - 16px));
|
||||
}
|
||||
.auto-leech-select ::v-deep(.dropdown-item) {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.auto-leech-dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin-right: 0.3rem;
|
||||
border-radius: 50%;
|
||||
|
||||
&.inactive {
|
||||
background: var(--oxide, #ff160a);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--highlighted, #2c4);
|
||||
animation: auto-leech-pulse 1.6s infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes auto-leech-pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(var(--highlighted-rgb, 32, 204, 68), 0.7);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 5px rgba(var(--highlighted-rgb, 32, 204, 68), 0);
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(var(--highlighted-rgb, 32, 204, 68), 0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -8,7 +8,7 @@
|
|||
variant="outline-secondary"
|
||||
class="auto-leech-fab__menu"
|
||||
v-b-tooltip.hover
|
||||
title="Auto leech: automatically accept or decline power-charge offers up to this amount, instead of asking every time"
|
||||
title="Auto-charge: automatically accept or decline power-charge offers up to this amount, instead of asking every time"
|
||||
>
|
||||
<template #button-content>
|
||||
<span class="auto-leech-dot" :class="autoChargePowerActive ? 'active' : 'inactive'"></span>
|
||||
|
|
@ -55,13 +55,13 @@ export default Vue.extend({
|
|||
},
|
||||
autoChargePowerOptions(): Array<{ value: string; text: string }> {
|
||||
return [
|
||||
{ value: "ask", text: "Auto leech: off (ask every time)" },
|
||||
{ value: "decline-cost", text: "Auto leech: free only (decline anything with a cost)" },
|
||||
{ value: "1", text: "Auto leech: up to 1 power" },
|
||||
{ value: "2", text: "Auto leech: up to 2 power" },
|
||||
{ value: "3", text: "Auto leech: up to 3 power" },
|
||||
{ value: "4", text: "Auto leech: up to 4 power" },
|
||||
{ value: "5", text: "Auto leech: up to 5 power" },
|
||||
{ value: "ask", text: "Auto-charge: off (ask every time)" },
|
||||
{ value: "decline-cost", text: "Auto-charge: free only (decline anything with a cost)" },
|
||||
{ value: "1", text: "Auto-charge: up to 1 power" },
|
||||
{ value: "2", text: "Auto-charge: up to 2 power" },
|
||||
{ value: "3", text: "Auto-charge: up to 3 power" },
|
||||
{ value: "4", text: "Auto-charge: up to 4 power" },
|
||||
{ value: "5", text: "Auto-charge: up to 5 power" },
|
||||
];
|
||||
},
|
||||
autoChargePassedCapOptions(): Array<{ value: string; text: string }> {
|
||||
|
|
@ -82,13 +82,13 @@ export default Vue.extend({
|
|||
const cap = (this as any).showPassedCapOptions ? (this as any).autoChargeMaxPassedRoundLeech : "0";
|
||||
switch ((this as any).autoChargePower) {
|
||||
case "ask":
|
||||
return "Leech: off";
|
||||
return "Charge: off";
|
||||
case "decline-cost":
|
||||
return cap === "0" ? "Leech: free" : `Leech: free cap ${cap}`;
|
||||
return cap === "0" ? "Charge: free" : `Charge: free cap ${cap}`;
|
||||
default:
|
||||
return cap === "0"
|
||||
? `Leech: ${(this as any).autoChargePower}`
|
||||
: `Leech: ${(this as any).autoChargePower} cap ${cap}`;
|
||||
? `Charge: ${(this as any).autoChargePower}`
|
||||
: `Charge: ${(this as any).autoChargePower} cap ${cap}`;
|
||||
}
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,112 +0,0 @@
|
|||
<template>
|
||||
<div class="cancel-trigger-leech-config">
|
||||
<div class="mb-2">
|
||||
<label class="d-block mb-1">
|
||||
<input type="radio" value="offered" v-model="mode" class="mr-1" />
|
||||
offered to me
|
||||
</label>
|
||||
<label class="d-block mb-1">
|
||||
<input type="radio" value="gained" v-model="mode" class="mr-1" />
|
||||
taken by me
|
||||
</label>
|
||||
</div>
|
||||
<div class="mb-2 d-flex align-items-center">
|
||||
at least
|
||||
<input type="number" min="1" class="mx-2 cancel-trigger-leech-config__amount" v-model.number="minPower" />
|
||||
power
|
||||
</div>
|
||||
|
||||
<div class="cancel-trigger-leech-config__preview text-muted small">{{ previewText }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import Engine from "@gaia-project/engine";
|
||||
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
|
||||
import { moveAtoms } from "../logic/premove-cancel-trigger";
|
||||
|
||||
// §2.6/§8.4 - no composing, no refine: the config IS the trigger. Default mode 'gained' with
|
||||
// minPower 2 (charging N power costs N-1 VP, so 2 is the first threshold that costs anything -
|
||||
// owner decision, not optional, see §2.6).
|
||||
//
|
||||
// Body-only: the sheet that hosts this step (PremoveBar) draws the title in its header band and the
|
||||
// Arm/Back pair in its footer, so every step of the cancel-trigger flow confirms from the same spot
|
||||
// instead of each one growing its own buttons wherever it happens to be rendered. This component
|
||||
// therefore just reports its current value upward via `input` and never arms anything itself.
|
||||
@Component
|
||||
export default class CancelTriggerLeechConfig extends Vue {
|
||||
@Prop()
|
||||
seat: number;
|
||||
|
||||
/** Editing an already-armed trigger seeds the form with its current config. */
|
||||
@Prop({ default: null })
|
||||
initialConfig: { mode: "gained" | "offered"; minPower: number } | null;
|
||||
|
||||
mode: "gained" | "offered" = "gained";
|
||||
minPower = 2;
|
||||
|
||||
created() {
|
||||
if (this.initialConfig) {
|
||||
this.mode = this.initialConfig.mode;
|
||||
this.minPower = this.initialConfig.minPower;
|
||||
}
|
||||
}
|
||||
|
||||
get engine(): Engine {
|
||||
return this.$store.state.data;
|
||||
}
|
||||
|
||||
get ownMoves(): string[] {
|
||||
const faction = this.engine.players[this.seat]?.faction;
|
||||
if (!faction) {
|
||||
return [];
|
||||
}
|
||||
return this.engine.moveHistory.slice(1).filter((line) => line.startsWith(`${faction} `));
|
||||
}
|
||||
|
||||
get wouldHaveFiredCount(): number {
|
||||
const map = this.engine.map as any;
|
||||
let count = 0;
|
||||
for (const line of this.ownMoves) {
|
||||
const atoms = moveAtoms(line, map);
|
||||
const hit = atoms.some((atom) => {
|
||||
const [command, arg] = atom.split(":");
|
||||
if (command !== "charge" && (command !== "decline" || this.mode !== "offered")) {
|
||||
return false;
|
||||
}
|
||||
const amount = parseInt(arg ?? "", 10);
|
||||
return !Number.isNaN(amount) && amount >= this.minPower;
|
||||
});
|
||||
if (hit) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
get previewText(): string {
|
||||
return `This would have fired ${this.wouldHaveFiredCount} time${
|
||||
this.wouldHaveFiredCount === 1 ? "" : "s"
|
||||
} so far this game.`;
|
||||
}
|
||||
|
||||
mounted() {
|
||||
this.emitState();
|
||||
}
|
||||
|
||||
/** Reports the current config to the host sheet, or `null` while it isn't armable - the footer's
|
||||
* "Arm rule" button is disabled on exactly that null. */
|
||||
@Watch("mode")
|
||||
@Watch("minPower")
|
||||
emitState() {
|
||||
this.$emit("input", this.minPower >= 1 ? { mode: this.mode, minPower: this.minPower } : null);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.cancel-trigger-leech-config__amount {
|
||||
width: 3.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
import Engine, { PlayerEnum } from "@gaia-project/engine";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { expect } from "chai";
|
||||
import { makeStore } from "../store";
|
||||
import CancelTriggerPicker from "./CancelTriggerPicker.vue";
|
||||
|
||||
const SETUP_MOVES = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
"p2 faction nevlas",
|
||||
"terrans build m -1x2",
|
||||
"nevlas build m -1x0",
|
||||
];
|
||||
|
||||
/**
|
||||
* The picker reads exactly three things off the engine - each player's faction, `playerToMove` and
|
||||
* `passedPlayers` - so these tests set the last two directly rather than driving a real game into
|
||||
* the shape being tested. That keeps them about the mapping that actually regressed (which engine
|
||||
* state produces which badge) instead of about which hex is buildable under a given seed.
|
||||
*/
|
||||
function mountPicker(seat: number, state: { onTurn?: number; passed?: number[] } = {}) {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
if (state.onTurn !== undefined) {
|
||||
engine.currentPlayer = state.onTurn as PlayerEnum;
|
||||
engine.tempCurrentPlayer = undefined;
|
||||
}
|
||||
engine.passedPlayers = (state.passed ?? []) as PlayerEnum[];
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", engine);
|
||||
return mount(CancelTriggerPicker, { propsData: { seat }, store });
|
||||
}
|
||||
|
||||
describe("CancelTriggerPicker", () => {
|
||||
/**
|
||||
* The regression this component was rewritten for. `passed` used to be derived from
|
||||
* `previewAvailableCommandsFor(seat) === null`, which is also null when it is that seat's turn -
|
||||
* so the opponent the game was currently waiting on rendered as a DISABLED chip labelled
|
||||
* "passed". That is the opponent you are most likely to want to watch (you are sitting off-turn
|
||||
* precisely because they are thinking), and it was the only one you could not pick.
|
||||
*/
|
||||
it("marks the opponent who is on turn as 'on turn', not 'passed', and keeps them pickable", async () => {
|
||||
const wrapper = mountPicker(0, { onTurn: 1 });
|
||||
|
||||
try {
|
||||
const chips = wrapper.findAll(".cancel-trigger-picker__chip");
|
||||
// One opponent chip plus the "⚡ I gain power" condition chip.
|
||||
expect(chips).to.have.length(2);
|
||||
|
||||
const opponent = chips.at(0);
|
||||
expect(opponent.text()).to.contain("Nevlas");
|
||||
expect(opponent.text()).to.contain("on turn");
|
||||
expect(opponent.text()).to.not.contain("passed");
|
||||
expect(opponent.attributes("disabled")).to.equal(undefined);
|
||||
|
||||
await opponent.trigger("click");
|
||||
expect(wrapper.emitted("pick-opponent")).to.deep.equal([[1]]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("marks a genuinely passed opponent as 'passed', and still lets them be picked", async () => {
|
||||
const wrapper = mountPicker(0, { onTurn: 0, passed: [1] });
|
||||
|
||||
try {
|
||||
const opponent = wrapper.findAll(".cancel-trigger-picker__chip").at(0);
|
||||
expect(opponent.text()).to.contain("passed");
|
||||
// Pickable on purpose: a rule armed now is still live next round, and so is the queue it
|
||||
// guards.
|
||||
expect(opponent.attributes("disabled")).to.equal(undefined);
|
||||
|
||||
await opponent.trigger("click");
|
||||
expect(wrapper.emitted("pick-opponent")).to.deep.equal([[1]]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves an opponent who is neither on turn nor passed unbadged", () => {
|
||||
const wrapper = mountPicker(0, { onTurn: 0 });
|
||||
|
||||
try {
|
||||
const opponent = wrapper.findAll(".cancel-trigger-picker__chip").at(0);
|
||||
expect(opponent.text()).to.contain("Nevlas");
|
||||
expect(opponent.text()).to.not.contain("on turn");
|
||||
expect(opponent.text()).to.not.contain("passed");
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
<template>
|
||||
<div class="cancel-trigger-picker">
|
||||
<div class="cancel-trigger-picker__hint">Pick whose move you want to watch.</div>
|
||||
<div class="cancel-trigger-picker__row d-flex flex-wrap">
|
||||
<button
|
||||
v-for="opponent in opponents"
|
||||
:key="opponent.seat"
|
||||
type="button"
|
||||
class="cancel-trigger-picker__chip"
|
||||
:class="{ 'cancel-trigger-picker__chip--dim': opponent.status === 'passed' }"
|
||||
:style="{ '--chip-color': opponent.color }"
|
||||
@click="$emit('pick-opponent', opponent.seat)"
|
||||
>
|
||||
{{ opponent.label }}
|
||||
<small v-if="opponent.status">{{ opponent.status === "on-turn" ? "on turn" : "passed" }}</small>
|
||||
</button>
|
||||
</div>
|
||||
<div class="cancel-trigger-picker__rule"></div>
|
||||
<div class="d-flex flex-wrap">
|
||||
<button
|
||||
type="button"
|
||||
class="cancel-trigger-picker__chip cancel-trigger-picker__chip--leech"
|
||||
@click="$emit('pick-leech')"
|
||||
>
|
||||
⚡ I gain power
|
||||
<small>from leech</small>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import Engine, { PlayerEnum } from "@gaia-project/engine";
|
||||
import { Component, Prop, Vue } from "vue-property-decorator";
|
||||
import { factionName } from "../data/factions";
|
||||
import { factionColor } from "../graphics/utils";
|
||||
|
||||
type OpponentChip = {
|
||||
seat: number;
|
||||
label: string;
|
||||
color: string;
|
||||
status: "on-turn" | "passed" | null;
|
||||
};
|
||||
|
||||
// §8.2 - the picker step, rendered inside the premove sheet's body (it used to be a b-modal, which
|
||||
// bounced the player from the bottom of the screen to the middle mid-flow). One chip per opponent in
|
||||
// faction colours, plus the "⚡ I gain power" condition chip below the divider, visually distinct
|
||||
// since it watches the owner's own state rather than an opponent.
|
||||
//
|
||||
// EVERY chip stays clickable. The status badge is informational only:
|
||||
//
|
||||
// - "on turn" - this opponent is the one the game is currently waiting on. That used to be read off
|
||||
// `previewAvailableCommandsFor(seat) === null` and rendered as a DISABLED chip labelled "passed",
|
||||
// which was wrong twice over. That method answers "can *I* premove?", where "it is already this
|
||||
// seat's turn" correctly means no; reused here it silently turned into "this opponent has
|
||||
// passed". The result was that the opponent you are most likely to want to watch - the one you
|
||||
// are sitting off-turn waiting for - was the only one you could not pick, and the UI lied about
|
||||
// why. `pickCancelTriggerOpponent` composes against its own clone with `forcePremovePreviewTurn`,
|
||||
// so an on-turn opponent works fine; the lockout was purely cosmetic.
|
||||
// - "passed" - genuinely passed this round (`passedPlayers`). Still pickable on purpose: a trigger
|
||||
// armed now is still live next round, and so is the queue it guards.
|
||||
@Component
|
||||
export default class CancelTriggerPicker extends Vue {
|
||||
@Prop()
|
||||
seat: number;
|
||||
|
||||
get engine(): Engine {
|
||||
return this.$store.state.data;
|
||||
}
|
||||
|
||||
get opponents(): OpponentChip[] {
|
||||
const passed: PlayerEnum[] = this.engine.passedPlayers ?? [];
|
||||
const onTurn = this.engine.playerToMove;
|
||||
return this.engine.players
|
||||
.map((pl) => pl.player)
|
||||
.filter((seat) => seat !== this.seat && !!this.engine.players[seat]?.faction)
|
||||
.map((seat) => {
|
||||
const faction = this.engine.players[seat].faction;
|
||||
return {
|
||||
seat,
|
||||
label: factionName(faction),
|
||||
color: factionColor(faction),
|
||||
status: passed.includes(seat) ? "passed" : seat === onTurn ? "on-turn" : null,
|
||||
} as OpponentChip;
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.cancel-trigger-picker {
|
||||
&__hint {
|
||||
font-size: 0.78rem;
|
||||
color: var(--ui-text-muted);
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
&__row {
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
&__rule {
|
||||
height: 1px;
|
||||
background: var(--ui-border);
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
&__chip {
|
||||
border: 2px solid var(--chip-color, var(--ui-border-strong));
|
||||
border-radius: 10px;
|
||||
padding: 0.3rem 0.7rem;
|
||||
background: linear-gradient(180deg, var(--ui-keycap-gradient-start) 0%, var(--ui-keycap-gradient-end) 100%);
|
||||
color: var(--ui-secondary-text);
|
||||
font-weight: 600;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.2;
|
||||
text-align: center;
|
||||
box-shadow: 0 1px 2px var(--ui-shadow-soft);
|
||||
cursor: pointer;
|
||||
|
||||
small {
|
||||
display: block;
|
||||
font-size: 0.6rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ui-text-muted);
|
||||
}
|
||||
|
||||
// Passed opponents read as secondary but stay fully clickable - see the class comment above.
|
||||
&--dim {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
&--leech {
|
||||
border-style: dashed;
|
||||
border-color: var(--ui-border-strong);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
var(--ui-warning-gradient-start, #fff3cd) 0%,
|
||||
var(--ui-warning-gradient-end, #ffe9a8) 100%
|
||||
);
|
||||
color: #7a5b00;
|
||||
|
||||
small {
|
||||
color: #7a5b00;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
import Engine from "@gaia-project/engine";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { expect } from "chai";
|
||||
import { makeStore } from "../store";
|
||||
import CancelTriggerRefine from "./CancelTriggerRefine.vue";
|
||||
|
||||
const SETUP_MOVES = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
"p2 faction nevlas",
|
||||
"terrans build m -1x2",
|
||||
"nevlas build m -1x0",
|
||||
];
|
||||
|
||||
function mountRefine(move: string) {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
return mount(CancelTriggerRefine, {
|
||||
propsData: { move, watchedSeat: 0 },
|
||||
store,
|
||||
});
|
||||
}
|
||||
|
||||
describe("CancelTriggerRefine", () => {
|
||||
it("pre-selects nothing on a multi-atom move", () => {
|
||||
const wrapper = mountRefine("terrans build lab 7A6. tech eco. up eco");
|
||||
try {
|
||||
const inner = wrapper.vm as any;
|
||||
expect(inner.candidates.length).to.be.greaterThan(1);
|
||||
expect(inner.selected.every((s: boolean) => s === false)).to.equal(true);
|
||||
expect(inner.selectedAtoms).to.deep.equal([]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("pre-selects the single candidate on a one-atom move", () => {
|
||||
const wrapper = mountRefine("terrans pass booster3");
|
||||
try {
|
||||
const inner = wrapper.vm as any;
|
||||
expect(inner.candidates.length).to.equal(1);
|
||||
expect(inner.selected).to.deep.equal([true]);
|
||||
expect(inner.selectedAtoms).to.deep.equal(["pass:booster3"]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// The host sheet's footer disables "Arm rule" on exactly an empty selection, so what this asserts
|
||||
// is that the empty->non-empty transition is reported upward at all.
|
||||
it("reports the selection upward as it changes, so the sheet's Arm button can follow it", async () => {
|
||||
const wrapper = mountRefine("terrans build lab 7A6. tech eco. up eco");
|
||||
try {
|
||||
const inner = wrapper.vm as any;
|
||||
expect(wrapper.emitted("input")).to.deep.equal([[[]]]);
|
||||
|
||||
inner.selected = [true, false, false];
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(inner.selectedAtoms.length).to.equal(1);
|
||||
expect(wrapper.emitted("input")!.slice(-1)).to.deep.equal([[["build:lab:7A6"]]]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggling exact/any changes the stored atom for that selection", async () => {
|
||||
const wrapper = mountRefine("terrans build lab 7A6.");
|
||||
try {
|
||||
const inner = wrapper.vm as any;
|
||||
inner.selected = [true];
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(inner.selectedAtoms).to.deep.equal(["build:lab:7A6"]);
|
||||
|
||||
inner.loose = [true];
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(inner.selectedAtoms).to.deep.equal(["build:lab:*"]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// The component no longer draws its own Arm/Cancel pair - the sheet that hosts it owns the footer,
|
||||
// so every step of the flow confirms from the same place. Its contract is the `input` it reports.
|
||||
it("emits the pre-selected atom on mount, without an Arm button of its own", async () => {
|
||||
const wrapper = mountRefine("terrans pass booster3");
|
||||
try {
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.emitted("input")).to.deep.equal([[["pass:booster3"]]]);
|
||||
expect(wrapper.find("button.btn-warning").exists()).to.equal(false);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
<template>
|
||||
<div class="cancel-trigger-refine">
|
||||
<div class="cancel-trigger-refine__hint">Which part of this should cancel my queue?</div>
|
||||
<div v-for="(candidate, i) in candidates" :key="candidate.exact" class="cancel-trigger-refine__row mb-2">
|
||||
<label class="d-flex align-items-center mb-1">
|
||||
<input type="checkbox" class="mr-2" v-model="selected[i]" />
|
||||
{{ candidate.label }}
|
||||
</label>
|
||||
<div v-if="selected[i] && candidate.any" class="cancel-trigger-refine__toggle btn-group btn-group-sm ml-4">
|
||||
<button
|
||||
type="button"
|
||||
class="btn"
|
||||
:class="loose[i] ? 'btn-outline-secondary' : 'btn-secondary'"
|
||||
@click="loose[i] = false"
|
||||
>
|
||||
exact
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn"
|
||||
:class="loose[i] ? 'btn-secondary' : 'btn-outline-secondary'"
|
||||
@click="loose[i] = true"
|
||||
>
|
||||
any
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cancel-trigger-refine__preview text-muted small mt-2">{{ previewText }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import Engine from "@gaia-project/engine";
|
||||
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
|
||||
import { atomMatches, candidateAtoms, moveAtoms } from "../logic/premove-cancel-trigger";
|
||||
|
||||
// §2.3/§8.3 - the refine step, the most important UI decision in the feature: nothing is
|
||||
// pre-selected (Arm stays disabled until at least one atom is chosen) UNLESS the composed move
|
||||
// produced exactly one candidate atom, which pre-selects itself since there's no ambiguity to ask
|
||||
// about. Each selection can be loosened to its "any" form where one exists (§2.4).
|
||||
//
|
||||
// Body-only, same split as CancelTriggerLeechConfig: the host sheet (PremoveBar) owns the header
|
||||
// band and the Arm/Back footer, so this component only reports its current atom selection upward via
|
||||
// `input` and never arms anything itself.
|
||||
@Component
|
||||
export default class CancelTriggerRefine extends Vue {
|
||||
@Prop()
|
||||
move: string;
|
||||
|
||||
@Prop()
|
||||
watchedSeat: number;
|
||||
|
||||
/** Editing an already-armed trigger (PremoveBar's "Edit") seeds the current selection instead of
|
||||
* the fresh-compose default below, rather than making the player re-pick from scratch. */
|
||||
@Prop({ default: () => [] })
|
||||
initialAtoms: string[];
|
||||
|
||||
selected: boolean[] = [];
|
||||
loose: boolean[] = [];
|
||||
|
||||
get engine(): Engine {
|
||||
return this.$store.state.data;
|
||||
}
|
||||
|
||||
get candidates() {
|
||||
return candidateAtoms(this.move, this.engine.map as any);
|
||||
}
|
||||
|
||||
@Watch("move", { immediate: true })
|
||||
onMoveChanged() {
|
||||
const candidates = this.candidates;
|
||||
if (this.initialAtoms.length > 0) {
|
||||
this.selected = candidates.map(
|
||||
(c) => this.initialAtoms.includes(c.exact) || (!!c.any && this.initialAtoms.includes(c.any))
|
||||
);
|
||||
this.loose = candidates.map((c) => !!c.any && this.initialAtoms.includes(c.any));
|
||||
return;
|
||||
}
|
||||
// Exception (§2.3): a move producing exactly one atom pre-selects it - no point asking a
|
||||
// one-answer question. Everything else starts fully unselected.
|
||||
this.selected = candidates.map((_, i) => candidates.length === 1);
|
||||
this.loose = candidates.map(() => false);
|
||||
}
|
||||
|
||||
get selectedAtoms(): string[] {
|
||||
return this.candidates
|
||||
.map((candidate, i) =>
|
||||
this.selected[i] ? (this.loose[i] && candidate.any ? candidate.any : candidate.exact) : null
|
||||
)
|
||||
.filter((atom): atom is string => atom !== null);
|
||||
}
|
||||
|
||||
mounted() {
|
||||
this.emitState();
|
||||
}
|
||||
|
||||
/** Reports the current selection to the host sheet. Watching the computed rather than emitting
|
||||
* from each control keeps the "exact/any" toggle and the checkboxes on one path. Not `immediate`:
|
||||
* `onMoveChanged` seeds `selected`/`loose` from its own immediate watcher, and the two would race
|
||||
* on first render - `mounted()` above covers the initial value instead. */
|
||||
@Watch("selectedAtoms")
|
||||
emitState() {
|
||||
this.$emit("input", this.selectedAtoms);
|
||||
}
|
||||
|
||||
/** The watched opponent's own committed move lines so far (moveHistory carries the faction name,
|
||||
* not the numeric seat, so lines are matched by that faction's prefix). */
|
||||
get watchedMoves(): string[] {
|
||||
const faction = this.engine.players[this.watchedSeat]?.faction;
|
||||
if (!faction) {
|
||||
return [];
|
||||
}
|
||||
return this.engine.moveHistory.slice(1).filter((line) => line.startsWith(`${faction} `));
|
||||
}
|
||||
|
||||
get wouldHaveFiredCount(): number {
|
||||
const atoms = this.selectedAtoms;
|
||||
if (atoms.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const map = this.engine.map as any;
|
||||
return this.watchedMoves.filter((line) => {
|
||||
const actual = moveAtoms(line, map);
|
||||
return atoms.some((stored) => actual.some((a) => atomMatches(stored, a)));
|
||||
}).length;
|
||||
}
|
||||
|
||||
get previewText(): string {
|
||||
const total = this.watchedMoves.length;
|
||||
if (total === 0) {
|
||||
return "This opponent hasn't moved yet this game.";
|
||||
}
|
||||
if (this.selectedAtoms.length === 0) {
|
||||
return `Select at least one row to see how often it would have fired (out of ${total} move${
|
||||
total === 1 ? "" : "s"
|
||||
} so far).`;
|
||||
}
|
||||
return `This would have fired on ${this.wouldHaveFiredCount} of this opponent's last ${total} move${
|
||||
total === 1 ? "" : "s"
|
||||
}.`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.cancel-trigger-refine__toggle .btn {
|
||||
padding: 0.1rem 0.5rem;
|
||||
}
|
||||
|
||||
.cancel-trigger-refine__hint {
|
||||
font-size: 0.78rem;
|
||||
color: var(--ui-text-muted);
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -689,15 +689,22 @@ describe("Commands", () => {
|
|||
function sandbox(engine: Engine) {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", engine);
|
||||
const { container } = render(Commands, { props: { currentMove: "", analysisMode: true }, store });
|
||||
const { container } = render(Commands, {
|
||||
props: { currentMove: "", analysisMode: true, analysisCanUndoCharge: true },
|
||||
store,
|
||||
});
|
||||
const labels = () =>
|
||||
Array.from(container.querySelectorAll<HTMLButtonElement>("#move-buttons button.move-button")).map(
|
||||
(button) => button.textContent?.trim() ?? ""
|
||||
);
|
||||
Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>(
|
||||
"#move-buttons button.move-button, .analysis-simulation__button"
|
||||
)
|
||||
).map((button) => button.textContent?.trim() ?? "");
|
||||
const button = (label: string) =>
|
||||
Array.from(container.querySelectorAll<HTMLButtonElement>("#move-buttons button.move-button")).find(
|
||||
(candidate) => candidate.textContent?.trim() === label
|
||||
);
|
||||
Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>(
|
||||
"#move-buttons button.move-button, .analysis-simulation__button"
|
||||
)
|
||||
).find((candidate) => candidate.textContent?.trim() === label);
|
||||
return { container, labels, button };
|
||||
}
|
||||
|
||||
|
|
@ -707,8 +714,8 @@ describe("Commands", () => {
|
|||
const { labels } = sandbox(roundMoveMenu());
|
||||
|
||||
expect(labels()).to.include("Research"); // a real menu, not an empty one
|
||||
expect(labels()).to.include("Charge 1");
|
||||
expect(labels()).to.include("Undo Charge");
|
||||
expect(labels()).to.include("Simulate charge +1");
|
||||
expect(labels()).to.include("Undo charge");
|
||||
});
|
||||
|
||||
it("hides them on the round-0 booster pick, which is not that menu", () => {
|
||||
|
|
@ -725,30 +732,20 @@ describe("Commands", () => {
|
|||
const { labels } = sandbox(engine);
|
||||
|
||||
expect(labels().length, "expected the booster buttons themselves").to.be.greaterThan(0);
|
||||
expect(labels()).to.not.include("Charge 1");
|
||||
expect(labels()).to.not.include("Undo Charge");
|
||||
expect(labels()).to.not.include("Simulate charge +1");
|
||||
expect(labels()).to.not.include("Undo charge");
|
||||
});
|
||||
|
||||
it("hides them once a button is drilled into (a sub-menu is not the main menu)", async () => {
|
||||
const { labels, button } = sandbox(roundMoveMenu());
|
||||
expect(labels()).to.include("Charge 1");
|
||||
expect(labels()).to.include("Simulate charge +1");
|
||||
|
||||
const research = button("Research");
|
||||
expect(research, "expected a Research button to drill into").to.not.equal(undefined);
|
||||
await fireEvent.click(research!);
|
||||
|
||||
expect(labels()).to.not.include("Charge 1");
|
||||
expect(labels()).to.not.include("Undo Charge");
|
||||
});
|
||||
|
||||
// The keycap styling in the sticky bar is a `.move-button .btn` DESCENDANT rule, so these have to
|
||||
// sit inside a `.move-button` wrapper like MoveButton.vue's own root or they render with square
|
||||
// corners next to properly rounded neighbours.
|
||||
it("wraps them the same way MoveButton does, so they pick up the same button styling", () => {
|
||||
const { button } = sandbox(roundMoveMenu());
|
||||
|
||||
expect(button("Charge 1")?.parentElement?.classList.contains("move-button")).to.equal(true);
|
||||
expect(button("Undo Charge")?.parentElement?.classList.contains("move-button")).to.equal(true);
|
||||
expect(labels()).to.not.include("Simulate charge +1");
|
||||
expect(labels()).to.not.include("Undo charge");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -762,32 +759,11 @@ describe("Commands", () => {
|
|||
expect(container.querySelector(".auto-leech-select")).to.equal(null);
|
||||
});
|
||||
|
||||
// Owner decision (2026-09): the auto-leech control moved to the platform's sidebar, so the
|
||||
// viewer no longer renders it at all - showAutoLeechSelect is hard-false. The preference storage
|
||||
// and option lists stay (the platform drives them); these tests assert the control is gone.
|
||||
it("does not render the auto-leech select (the platform's sidebar owns it now)", () => {
|
||||
const engine = createLostFleetRoundMoveEngine();
|
||||
it("shows auto-charge in the action bar during a round", () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", engine);
|
||||
|
||||
store.commit("receiveData", createLostFleetRoundMoveEngine());
|
||||
const { container } = render(Commands, { props: { currentMove: "" }, store });
|
||||
|
||||
expect(container.querySelectorAll(".auto-leech-select").length).to.equal(0);
|
||||
expect(container.textContent).to.not.contain("Leech:");
|
||||
});
|
||||
|
||||
it("does not render after-passing auto-leech cap choices either, even once the viewing seat has passed", () => {
|
||||
const engine = createLostFleetRoundMoveEngine();
|
||||
const store = makeStore();
|
||||
store.commit("preferences", { autoChargePower: "4", autoChargeMaxPassedRoundLeech: "3" });
|
||||
store.commit("receiveData", engine);
|
||||
|
||||
engine.passedPlayers = [PlayerEnum.Player1];
|
||||
store.commit("receiveData", engine);
|
||||
|
||||
const afterPass = render(Commands, { props: { currentMove: "" }, store });
|
||||
expect(afterPass.container.textContent).to.not.contain("After passing:");
|
||||
expect(afterPass.container.textContent).to.not.contain("Leech:");
|
||||
expect(container.querySelectorAll(".auto-leech-select").length).to.equal(2);
|
||||
});
|
||||
|
||||
it("hides the auto-leech select during analysis mode, putting the line's controls in its place instead (§2.9/§12)", () => {
|
||||
|
|
@ -806,8 +782,7 @@ describe("Commands", () => {
|
|||
expect(controls.length).to.equal(2); // one in #move-title, one in the mobile sticky bar
|
||||
const title = container.querySelector("#move-title .analysis-controls");
|
||||
expect(title.textContent).to.contain("3 moves");
|
||||
expect(title.textContent).to.contain("-7c");
|
||||
expect(title.textContent).to.contain("+2 power");
|
||||
expect(title.querySelector(".analysis-controls__shortfall").getAttribute("title")).to.contain("7 credits, 2 power");
|
||||
});
|
||||
|
||||
it("puts round 0's faction seed in the action area as one button per faction, announced in the header", async () => {
|
||||
|
|
@ -878,9 +853,7 @@ describe("Commands", () => {
|
|||
store,
|
||||
});
|
||||
|
||||
const commit = Array.from(container.querySelectorAll("button")).find((b) =>
|
||||
(b.textContent ?? "").includes("Commit")
|
||||
) as HTMLButtonElement;
|
||||
const commit = container.querySelector(".analysis-controls__btn") as HTMLButtonElement;
|
||||
await fireEvent.click(commit);
|
||||
await Vue.nextTick();
|
||||
|
||||
|
|
@ -901,7 +874,7 @@ describe("Commands", () => {
|
|||
store,
|
||||
});
|
||||
|
||||
expect(container.querySelector("#move-title").textContent).to.contain("SANDBOX");
|
||||
expect(container.querySelector("#move-title").textContent).to.contain("Planning");
|
||||
expect(container.querySelector("#move-title").classList.contains("move-title--analysis")).to.equal(true);
|
||||
expect(
|
||||
container.querySelector("#move-buttons .sticky-bar-title").classList.contains("sticky-bar-title--analysis")
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -42,7 +42,7 @@
|
|||
<g
|
||||
v-if="!preview"
|
||||
v-b-tooltip.hover
|
||||
title="Leech network - number of upgradable buildings by other players within leeching distance"
|
||||
title="Charge network - number of upgradable buildings by other players within charging distance"
|
||||
:transform="`translate(33.5,${height - 16.6}) scale(.08)`"
|
||||
>
|
||||
<image
|
||||
|
|
@ -256,7 +256,7 @@ export default class PlayerBoardInfo extends Vue {
|
|||
"<li>Click on the planets to highlight all planets of this type</li>" +
|
||||
"<li>Click on the sectors icon to highlight all colonized sectors (also works for other players)</li>" +
|
||||
"<li>Click on the federation icon to highlight all federation (also works for other players)</li>" +
|
||||
"<li>Click on the network icon (right of power bowl) to leech network - how much power can be gained if other players upgrade buildings</li>" +
|
||||
"<li>Click on the network icon (right of power bowl) to show the charge network: how much power can be gained if other players upgrade buildings</li>" +
|
||||
"</ul>"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,296 +0,0 @@
|
|||
import Engine from "@gaia-project/engine";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import BootstrapVue from "bootstrap-vue";
|
||||
import { expect } from "chai";
|
||||
import Vue from "vue";
|
||||
import { makeStore } from "../store";
|
||||
import PremoveBar from "./PremoveBar.vue";
|
||||
|
||||
Vue.use(BootstrapVue);
|
||||
|
||||
const SETUP_MOVES = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
"p2 faction nevlas",
|
||||
"terrans build m -1x2",
|
||||
"nevlas build m -1x0",
|
||||
];
|
||||
|
||||
describe("PremoveBar", () => {
|
||||
it("clears zoom compensation after a pinch leaves only a tiny scale residue", () => {
|
||||
const originalVisualViewport = Object.getOwnPropertyDescriptor(window, "visualViewport");
|
||||
const listeners: Record<string, Array<() => void>> = {};
|
||||
const viewport = {
|
||||
scale: 2,
|
||||
offsetLeft: 10,
|
||||
offsetTop: 40,
|
||||
height: 420,
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
(listeners[type] ?? (listeners[type] = [])).push(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
listeners[type] = (listeners[type] ?? []).filter((candidate) => candidate !== listener);
|
||||
},
|
||||
};
|
||||
|
||||
Object.defineProperty(window, "visualViewport", {
|
||||
configurable: true,
|
||||
value: viewport,
|
||||
});
|
||||
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: {
|
||||
seat: 0,
|
||||
composeModePreference: "sequential",
|
||||
stickyMobile: true,
|
||||
},
|
||||
store: makeStore(),
|
||||
});
|
||||
|
||||
try {
|
||||
const bar = wrapper.element as HTMLElement;
|
||||
expect(bar.style.transform, "a genuine zoom should be compensated").to.not.equal("");
|
||||
|
||||
// Recreate the state that caused the intermittent bug: the pinch has ended, but the browser
|
||||
// reports a scale infinitesimally different from 1 while an ordinary scroll changes the
|
||||
// visual viewport's top/height. The bar must remove its transform and return to native fixed
|
||||
// positioning instead of translating up into the middle of the screen.
|
||||
viewport.scale = 1.0000000002;
|
||||
viewport.offsetLeft = 0;
|
||||
viewport.offsetTop = 90;
|
||||
viewport.height = 600;
|
||||
for (const listener of listeners.scroll ?? []) {
|
||||
listener();
|
||||
}
|
||||
|
||||
expect(bar.style.transform).to.equal("");
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
if (originalVisualViewport) {
|
||||
Object.defineProperty(window, "visualViewport", originalVisualViewport);
|
||||
} else {
|
||||
delete (window as any).visualViewport;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// The bottom-sheet chrome (dark header band + grab handle) belongs to the off-turn sticky layout
|
||||
// only - the in-flow desktop card keeps the plain `__will-fire` line instead. Both live in the
|
||||
// same stylesheet and are toggled by the media query, so what's asserted here is the DOM half of
|
||||
// that split: the header exists to be styled at all only while the bar is in sticky mode.
|
||||
it("renders the bottom-sheet header only in sticky-mobile mode", () => {
|
||||
const sticky = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: true },
|
||||
store: makeStore(),
|
||||
});
|
||||
const inFlow = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: false },
|
||||
store: makeStore(),
|
||||
});
|
||||
|
||||
try {
|
||||
expect(sticky.find(".premove-bar__sheet-title").exists()).to.be.true;
|
||||
expect(sticky.find(".premove-bar__sheet-title").text()).to.equal("Plan your next turn");
|
||||
expect(inFlow.find(".premove-bar__sheet-title").exists()).to.be.false;
|
||||
} finally {
|
||||
sticky.destroy();
|
||||
inFlow.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// Mode used to be two "+" buttons that each ALSO rewrote a queue-wide setting (and one of which
|
||||
// silently discarded the queue). It's a labelled two-way choice now, with a single add action
|
||||
// beside it, so "which mode am I in" and "add a move" stop being the same click.
|
||||
it("separates the mode choice from the single add action", () => {
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: false },
|
||||
store: makeStore(),
|
||||
});
|
||||
try {
|
||||
const modes = wrapper.findAll(".premove-bar__segment-option").wrappers.map((w) => w.text().trim());
|
||||
expect(modes).to.deep.equal(["Chain", "Fallback"]);
|
||||
expect(wrapper.find(".premove-bar__segment-option--on").text().trim()).to.equal("Chain");
|
||||
|
||||
const actions = wrapper.findAll(".premove-bar__action-button").wrappers.map((w) => w.text().trim());
|
||||
expect(actions).to.deep.equal(["+ Add move", "⚠ Cancel if…"]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("emits start-cancel-trigger from the ⚠ Cancel if… button", async () => {
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: false },
|
||||
store: makeStore(),
|
||||
});
|
||||
try {
|
||||
const buttons = wrapper.findAll(".premove-bar__action-button");
|
||||
await buttons.at(1).trigger("click");
|
||||
expect(wrapper.emitted("start-cancel-trigger")).to.have.length(1);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// The cancel-rule steps used to be a b-modal in Game.vue, which threw the player from the bottom
|
||||
// of the screen to the middle of it in the middle of one task. They render in the sheet now.
|
||||
it("renders the cancel-rule steps inside the sheet, with the band and footer following the step", () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: true, stage: "picker" },
|
||||
store,
|
||||
});
|
||||
try {
|
||||
expect(wrapper.find(".cancel-trigger-picker").exists()).to.be.true;
|
||||
expect(wrapper.find(".premove-bar__sheet-title").text()).to.equal("Cancel my queue if…");
|
||||
// The picker's own chips are the action, so the footer offers only the escape.
|
||||
const footer = wrapper.findAll(".premove-bar__foot .premove-bar__action-button");
|
||||
expect(footer.wrappers.map((w) => w.text().trim())).to.deep.equal(["Back"]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps Arm rule disabled until the refine step reports a selection", async () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: {
|
||||
seat: 0,
|
||||
composeModePreference: "sequential",
|
||||
stickyMobile: true,
|
||||
stage: "refine",
|
||||
watchedSeat: 1,
|
||||
draftMove: "nevlas build lab 7A6. tech eco. up eco",
|
||||
},
|
||||
store,
|
||||
});
|
||||
try {
|
||||
const arm = () => wrapper.findAll(".premove-bar__foot .premove-bar__action-button").at(0);
|
||||
expect(wrapper.find(".premove-bar__sheet-title").text()).to.equal("Cancel if Nevlas…");
|
||||
expect(arm().attributes("disabled")).to.equal("disabled");
|
||||
|
||||
(wrapper.findComponent({ name: "CancelTriggerRefine" }).vm as any).selected = [true, false, false];
|
||||
await wrapper.vm.$nextTick();
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(arm().attributes("disabled")).to.equal(undefined);
|
||||
|
||||
await arm().trigger("click");
|
||||
expect(wrapper.emitted("arm-refine")).to.deep.equal([[["build:lab:7A6"]]]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// Every entry readable at once, carrying its own move text - it used to be a tab strip labelled
|
||||
// "Premove 1/2/3" that revealed one entry at a time.
|
||||
it("lists every queued entry with its move text and its own legality state", () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
store.commit("premoveState", {
|
||||
premoves: [
|
||||
{ seat: 0, seq: 1, move: "terrans build m -2x2", mode: "sequential", queued_move_count: 5 },
|
||||
{ seat: 0, seq: 2, move: "terrans burn 1", mode: "sequential", queued_move_count: 5 },
|
||||
],
|
||||
failures: [],
|
||||
});
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: false },
|
||||
store,
|
||||
});
|
||||
try {
|
||||
const moves = wrapper.findAll(".premove-bar__entry-move").wrappers.map((w) => w.text().trim());
|
||||
expect(moves).to.deep.equal(["terrans build m -2x2", "terrans burn 1"]);
|
||||
// Each row states its own status rather than hiding it behind a tap.
|
||||
expect(wrapper.findAll(".premove-bar__entry-state")).to.have.length(2);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// The cascade / failure / played-automatically notices used to render in Game.vue's in-flow
|
||||
// column, i.e. up the page, above a sheet pinned to the bottom of the viewport.
|
||||
it("shows the 'played automatically' notice inside the sheet", () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
store.commit("premovePlayed", { seat: 0, move: "terrans build m -2x2" });
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: true },
|
||||
store,
|
||||
});
|
||||
try {
|
||||
expect(wrapper.find(".premove-bar__notice--ok").text()).to.contain("terrans build m -2x2");
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("lists armed triggers (move and leech kind) with Edit/Remove, and removing dispatches disarmCancelTrigger", async () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
store.commit("cancelTriggerState", [
|
||||
{
|
||||
seat: 0,
|
||||
seq: 1,
|
||||
kind: "move",
|
||||
watched_seat: 1,
|
||||
move: "",
|
||||
atoms: ["up:eco"],
|
||||
config: {},
|
||||
match: "any",
|
||||
armed_from_move_count: 0,
|
||||
},
|
||||
{
|
||||
seat: 0,
|
||||
seq: 2,
|
||||
kind: "leech",
|
||||
watched_seat: 0,
|
||||
move: "",
|
||||
atoms: [],
|
||||
config: { mode: "gained", minPower: 2 },
|
||||
match: "any",
|
||||
armed_from_move_count: 0,
|
||||
},
|
||||
]);
|
||||
const dispatched: any[] = [];
|
||||
store.dispatch = (type: string, payload: any) => {
|
||||
dispatched.push({ type, payload });
|
||||
return Promise.resolve();
|
||||
};
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: false },
|
||||
store,
|
||||
});
|
||||
try {
|
||||
const rows = wrapper.findAll(".premove-bar__trigger-row");
|
||||
expect(rows).to.have.length(2);
|
||||
expect(rows.at(0).text()).to.contain("Nevlas");
|
||||
expect(rows.at(0).text()).to.contain("advances Economy");
|
||||
expect(rows.at(1).text()).to.contain("Power charge ≥ 2 taken by me");
|
||||
|
||||
await rows.at(1).find("button.btn-link:last-child").trigger("click");
|
||||
expect(dispatched).to.deep.equal([{ type: "disarmCancelTrigger", payload: { seat: 0, seq: 2 } }]);
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("the fired-state header reads 'Cancelled - <reason>' once a cancel trigger has matched", () => {
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", new Engine(SETUP_MOVES));
|
||||
store.commit("premoveState", {
|
||||
premoves: [],
|
||||
failures: [{ id: "1", seat: 0, move: "", reason: "Nevlas advanced Economy", read_at: null, kind: "cancelled" }],
|
||||
});
|
||||
const wrapper = mount(PremoveBar, {
|
||||
propsData: { seat: 0, composeModePreference: "sequential", stickyMobile: true },
|
||||
store,
|
||||
});
|
||||
try {
|
||||
expect(wrapper.find(".premove-bar__sheet-title").text()).to.equal("Cancelled — Nevlas advanced Economy");
|
||||
} finally {
|
||||
wrapper.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load diff
49
viewer/src/components/PremoveNotice.spec.ts
Normal file
49
viewer/src/components/PremoveNotice.spec.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import type { PremovePlan } from "@gaia-project/engine/src/premove-types";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { expect } from "chai";
|
||||
import PremoveNotice from "./PremoveNotice.vue";
|
||||
|
||||
describe("premove notice dismissal", () => {
|
||||
const plan: PremovePlan = {
|
||||
moves: ["terrans up nav."],
|
||||
revision: 2,
|
||||
round: 1,
|
||||
requestId: "plan-1",
|
||||
notice: { kind: "played", text: "Played for you: terrans up terra." },
|
||||
};
|
||||
|
||||
afterEach(() => window.localStorage.clear());
|
||||
|
||||
it("persists dismissal across remounts without changing remaining premoves, but shows a new notice", async () => {
|
||||
const propsData = { plan: JSON.parse(JSON.stringify(plan)), storageKey: "notice:game-1:seat-0" };
|
||||
const wrapper = mount(PremoveNotice, { propsData });
|
||||
await wrapper.find("button").trigger("click");
|
||||
expect(wrapper.find(".premove-notice").exists()).to.equal(false);
|
||||
expect(propsData.plan).to.deep.equal(plan);
|
||||
wrapper.destroy();
|
||||
|
||||
const refreshed = mount(PremoveNotice, { propsData });
|
||||
expect(refreshed.find(".premove-notice").exists()).to.equal(false);
|
||||
await refreshed.setProps({ plan: { ...plan, revision: 3 } });
|
||||
expect(refreshed.find(".premove-notice").exists()).to.equal(true);
|
||||
refreshed.destroy();
|
||||
});
|
||||
|
||||
it("can dismiss a stopped empty queue and isolates the dismissal by game and seat", async () => {
|
||||
const stopped: PremovePlan = {
|
||||
...plan,
|
||||
moves: [],
|
||||
notice: { kind: "stopped", text: "Premoves stopped: booster4 is not in the available boosters" },
|
||||
};
|
||||
const wrapper = mount(PremoveNotice, {
|
||||
propsData: { plan: stopped, storageKey: "notice:game-1:seat-0" },
|
||||
});
|
||||
await wrapper.find("button").trigger("click");
|
||||
expect(wrapper.find(".premove-notice").exists()).to.equal(false);
|
||||
await wrapper.setProps({ storageKey: "notice:game-1:seat-1" });
|
||||
expect(wrapper.find(".premove-notice").exists()).to.equal(true);
|
||||
await wrapper.setProps({ storageKey: "notice:game-2:seat-0" });
|
||||
expect(wrapper.find(".premove-notice").exists()).to.equal(true);
|
||||
wrapper.destroy();
|
||||
});
|
||||
});
|
||||
66
viewer/src/components/PremoveNotice.vue
Normal file
66
viewer/src/components/PremoveNotice.vue
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<template>
|
||||
<div
|
||||
v-if="plan.notice && noticeId !== dismissedId"
|
||||
class="premove-notice small d-flex align-items-center"
|
||||
:class="plan.notice.kind === 'stopped' ? 'text-warning' : 'text-muted'"
|
||||
role="status"
|
||||
>
|
||||
<span>{{ plan.notice.text }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="dismiss-notice btn btn-sm btn-link ml-2"
|
||||
aria-label="Dismiss premove notice"
|
||||
@click="dismiss"
|
||||
>
|
||||
<span aria-hidden="true">✕</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import type { PremovePlan } from "@gaia-project/engine/src/premove-types";
|
||||
import Vue from "vue";
|
||||
|
||||
export default Vue.extend({
|
||||
props: {
|
||||
plan: { type: Object as () => PremovePlan, required: true },
|
||||
storageKey: { type: String, required: true },
|
||||
},
|
||||
data: () => ({ dismissedId: "" }),
|
||||
computed: {
|
||||
noticeId(): string {
|
||||
return JSON.stringify([this.plan.requestId, this.plan.revision, this.plan.notice]);
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
storageKey: {
|
||||
immediate: true,
|
||||
handler(key: string) {
|
||||
this.dismissedId = "";
|
||||
try {
|
||||
this.dismissedId = window.localStorage.getItem(key) ?? "";
|
||||
} catch {
|
||||
// Dismissal still works for this view when browser storage is unavailable.
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
dismiss() {
|
||||
this.dismissedId = this.noticeId;
|
||||
try {
|
||||
window.localStorage.setItem(this.storageKey, this.dismissedId);
|
||||
} catch {
|
||||
// Keep the in-memory dismissal without affecting the saved premove queue.
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dismiss-notice {
|
||||
color: inherit;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
142
viewer/src/components/PremoveQueue.vue
Normal file
142
viewer/src/components/PremoveQueue.vue
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
<template>
|
||||
<section class="premove-queue" :aria-label="queueEnabled ? 'Your premoves' : 'Planning'">
|
||||
<div class="premove-queue__heading">
|
||||
<div>
|
||||
<strong>{{
|
||||
moves.length ? `Your premoves · ${moves.length}` : active ? "Planning · preview only" : "Plan your next turn"
|
||||
}}</strong>
|
||||
<div class="small text-muted">
|
||||
{{
|
||||
moves.length
|
||||
? "Attempts each move on your turn with your actual resources. Auto-charge continues as usual."
|
||||
: active && previewRound
|
||||
? `Previewing round ${previewRound}. Queued moves will wait for the appropriate round and phase.`
|
||||
: active
|
||||
? "Try moves with the game controls. Nothing is played until you confirm."
|
||||
: queueEnabled
|
||||
? "Prepare moves for your next turns, even while someone else is playing."
|
||||
: "Try moves and compare plans using the game controls."
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="premove-queue__actions">
|
||||
<button v-if="active" class="btn btn-sm btn-outline-secondary" @click="$emit('exit')">
|
||||
Return to live game
|
||||
</button>
|
||||
<button
|
||||
v-if="moves.length"
|
||||
class="btn btn-sm btn-outline-primary"
|
||||
:disabled="!canPreview"
|
||||
:title="canPreview ? undefined : 'Return to the live game to preview these moves'"
|
||||
@click="$emit('view')"
|
||||
>
|
||||
View on board
|
||||
</button>
|
||||
<button
|
||||
v-if="moves.length"
|
||||
class="btn btn-sm btn-outline-danger"
|
||||
:disabled="pending"
|
||||
@click="$emit('cancel', 0)"
|
||||
>
|
||||
Cancel all
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ol v-if="moves.length" class="premove-queue__moves">
|
||||
<li v-for="(move, index) in moves" :key="index">
|
||||
<span v-if="plan.timings" class="premove-queue__price premove-queue__round">{{
|
||||
plan.timings[index].round === 0 ? "Setup" : `Round ${plan.timings[index].round}`
|
||||
}}</span>
|
||||
<span>{{ move }}</span>
|
||||
<span
|
||||
v-if="isCheapAnalysisBuild(move)"
|
||||
class="premove-queue__price"
|
||||
title="Stops if the 3c price is unavailable"
|
||||
>3c only</span
|
||||
>
|
||||
<button
|
||||
class="btn btn-sm btn-link"
|
||||
:disabled="pending"
|
||||
:aria-label="`Cancel premove ${index + 1}${index !== moves.length - 1 ? ' and the moves after it' : ''}`"
|
||||
@click="$emit('cancel', index)"
|
||||
>
|
||||
{{ index !== moves.length - 1 ? "Cancel from here" : "Cancel" }}
|
||||
</button>
|
||||
</li>
|
||||
</ol>
|
||||
<div v-if="pending" class="small mt-2" role="status">Saving your plan…</div>
|
||||
<PremoveNotice v-else-if="plan && plan.notice" :plan="plan" :storage-key="noticeStorageKey" class="mt-2" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import type { PremovePlan } from "@gaia-project/engine/src/premove-types";
|
||||
import Vue from "vue";
|
||||
import { isCheapAnalysisBuild } from "../logic/analysis";
|
||||
import PremoveNotice from "./PremoveNotice.vue";
|
||||
|
||||
export default Vue.extend({
|
||||
components: { PremoveNotice },
|
||||
methods: { isCheapAnalysisBuild },
|
||||
props: {
|
||||
plan: { type: Object as () => PremovePlan, default: undefined },
|
||||
noticeStorageKey: { type: String, required: true },
|
||||
pending: Boolean,
|
||||
queueEnabled: { type: Boolean, default: true },
|
||||
active: Boolean,
|
||||
previewRound: Number,
|
||||
canPreview: { type: Boolean, default: true },
|
||||
},
|
||||
computed: {
|
||||
moves(): string[] {
|
||||
return this.plan?.moves ?? [];
|
||||
},
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.premove-queue {
|
||||
background: var(--ui-surface-muted);
|
||||
border: 1px solid var(--ui-border-strong);
|
||||
border-left: 3px solid var(--ui-info, #4294c4);
|
||||
border-radius: 0.4rem;
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.premove-queue__heading,
|
||||
.premove-queue__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.premove-queue__heading {
|
||||
justify-content: space-between;
|
||||
}
|
||||
.premove-queue__moves {
|
||||
padding-left: 1.5rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.premove-queue__moves li {
|
||||
padding-top: 0.35rem;
|
||||
}
|
||||
.premove-queue__moves span {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.premove-queue__moves button {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
.premove-queue__price {
|
||||
margin-left: 0.5rem;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border: 1px solid var(--ui-border-strong);
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.premove-queue__round {
|
||||
margin-left: 0;
|
||||
margin-right: 0.5rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -54,7 +54,17 @@
|
|||
:disable-tooltip="true"
|
||||
/>
|
||||
<Booster v-else-if="c.booster" :key="i" :booster="c.booster" highlighted />
|
||||
<svg v-else-if="c.planet" :key="i" viewBox="-10 -10 20 20" width="20" height="20" :data-planet="c.planet">
|
||||
<svg
|
||||
v-else-if="c.planet"
|
||||
:key="i"
|
||||
viewBox="-10 -10 20 20"
|
||||
width="20"
|
||||
height="20"
|
||||
:data-planet="c.planet"
|
||||
role="img"
|
||||
:aria-label="planetNames[c.planet]"
|
||||
>
|
||||
<title>{{ planetNames[c.planet] }}</title>
|
||||
<circle r="7" :class="['planet-fill', c.planet]" style="stroke: black; stroke-width: 0.7" />
|
||||
</svg>
|
||||
<svg v-else-if="c.text === 'arrow'" :key="i" viewBox="0 0 10 10" width="20" height="20">
|
||||
|
|
@ -70,6 +80,7 @@ import { Building as BuildingEnum, Faction, Resource } from "@gaia-project/engin
|
|||
import Reward from "@gaia-project/engine/src/reward";
|
||||
import Vue from "vue";
|
||||
import { Component, Prop } from "vue-property-decorator";
|
||||
import { planetNames } from "../../data/planets";
|
||||
import { foregroundColor } from "../../graphics/colors";
|
||||
import type { RichText, RichTextBuilding, RichTextElement } from "../../graphics/rich-text";
|
||||
import { factionColorVar } from "../../graphics/utils";
|
||||
|
|
@ -85,6 +96,8 @@ import TechTile from "../TechTile.vue";
|
|||
components: { Booster, TechTile, BoardAction, Building, SpecialAction, ShipActionIcon, ArtifactIcon },
|
||||
})
|
||||
export default class RichTextView extends Vue {
|
||||
readonly planetNames = planetNames;
|
||||
|
||||
@Prop()
|
||||
content: RichText;
|
||||
|
||||
|
|
|
|||
|
|
@ -80,6 +80,19 @@
|
|||
unit, leaving the letter on the baseline / high in the hex) and `dominant-baseline`
|
||||
(iOS Safari renders it off) - the same proven mechanism the `.sector-name` labels use. -->
|
||||
<text class="lost-fleet-spaceship__label" y="0" dy="0.315">{{ lostFleetSpaceshipLabel }}</text>
|
||||
<g
|
||||
v-for="(explorer, index) in explorers"
|
||||
:key="explorer.player"
|
||||
class="lost-fleet-spaceship__explorer"
|
||||
:class="{ recent: recentExploration(explorer) }"
|
||||
:data-player="explorer.player"
|
||||
:transform="`translate(${[-0.65, 0.65, 0, 0][index]}, ${[0, 0, -0.57, 0.57][index]})`"
|
||||
role="img"
|
||||
:aria-label="explorerLabel(explorer)"
|
||||
>
|
||||
<circle class="lost-fleet-spaceship__explorer-outline" r="0.3" />
|
||||
<circle :class="['planet-fill', playerPlanet(explorer.player)]" r="0.25" />
|
||||
</g>
|
||||
</g>
|
||||
<Planet
|
||||
v-if="showPlanet"
|
||||
|
|
@ -374,6 +387,22 @@ export default class SpaceHex extends Vue {
|
|||
return this.lostFleetSpaceship ? spaceshipColors[this.lostFleetSpaceship] : "";
|
||||
}
|
||||
|
||||
get explorers(): Player[] {
|
||||
const ship = this.lostFleetSpaceship;
|
||||
if (!ship) return [];
|
||||
return this.engine.players
|
||||
.filter((player) => player.data.hasExplored(ship))
|
||||
.sort((a, b) => a.data.explorationShips[ship] - b.data.explorationShips[ship]);
|
||||
}
|
||||
|
||||
explorerLabel(player: Player): string {
|
||||
return `Explored by ${player.name || `P${player.player + 1}`} (${factionName(player.faction)})`;
|
||||
}
|
||||
|
||||
recentExploration(player: Player): boolean {
|
||||
return this.$store.getters.recentOpponentExplorations.get(player.faction)?.has(this.lostFleetSpaceship) ?? false;
|
||||
}
|
||||
|
||||
// Deep Space tiles no longer render a per-hex badge here - SpaceMap.vue renders one big
|
||||
// sector-style label centered across all 3 hexes of the tile instead (see its
|
||||
// `deepSpaceLabels` getter), matching the sector-number styling and staying clear of whichever
|
||||
|
|
@ -571,7 +600,11 @@ export default class SpaceHex extends Vue {
|
|||
const spaceship = this.lostFleetSpaceship
|
||||
? `Lost Fleet spaceship: ${this.lostFleetSpaceshipNames[this.lostFleetSpaceship]}`
|
||||
: null;
|
||||
return [coord, sector, spaceship, planet].concat(buildings).concat(messages).join(" ");
|
||||
return [coord, sector, spaceship, planet]
|
||||
.concat(this.explorers.map(this.explorerLabel))
|
||||
.concat(buildings)
|
||||
.concat(messages)
|
||||
.join(" ");
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
@ -730,6 +763,19 @@ svg {
|
|||
font-size: 0.9px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
&__explorer-outline {
|
||||
fill: #17202b;
|
||||
stroke: #fff;
|
||||
stroke-width: 0.025;
|
||||
}
|
||||
|
||||
&__explorer.recent {
|
||||
.lost-fleet-spaceship__explorer-outline {
|
||||
stroke: var(--recent);
|
||||
stroke-width: 0.09;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -6,8 +6,9 @@ import Engine, {
|
|||
LostFleetSectorType,
|
||||
Planet,
|
||||
PlayerEnum,
|
||||
Spaceship,
|
||||
} from "@gaia-project/engine";
|
||||
import { fireEvent, render } from "@testing-library/vue";
|
||||
import { render } from "@testing-library/vue";
|
||||
import { expect } from "chai";
|
||||
import fs from "fs";
|
||||
import { hexCenter } from "../graphics/hex";
|
||||
|
|
@ -134,6 +135,40 @@ describe("SpaceMap", () => {
|
|||
}
|
||||
});
|
||||
|
||||
it("shows each ship's explorers in slot order with their faction colors and recent-move highlight", () => {
|
||||
const engine = new Engine(
|
||||
[
|
||||
"init 4 map-explore-markers",
|
||||
"p1 faction terrans",
|
||||
"p2 faction hadsch-hallas",
|
||||
"p3 faction moweyds",
|
||||
"p4 faction xenos",
|
||||
],
|
||||
{ lostFleet: true }
|
||||
);
|
||||
engine.players.forEach((player, index) => {
|
||||
player.name = `Player ${index + 1}`;
|
||||
player.data.explorationShips[Spaceship.Twilight] = 4 - index;
|
||||
});
|
||||
engine.players[1].data.explorationShips[Spaceship.Eclipse] = 1;
|
||||
engine.moveHistory = ["init 4 map-explore-markers", "terrans explore twilight", "moweyds explore twilight"];
|
||||
engine.advancedLog = [{ player: 0, move: 1 }, { player: 2, move: 2 }, { player: 0 }];
|
||||
|
||||
const store = makeStore();
|
||||
store.commit("player", { index: 0 });
|
||||
store.commit("receiveData", engine);
|
||||
const { container } = render(SpaceMap, { store });
|
||||
const ship = (name: Spaceship) => container.querySelector(`[data-ship="${name}"]`).parentElement;
|
||||
const markers = Array.from(ship(Spaceship.Twilight).querySelectorAll(".lost-fleet-spaceship__explorer"));
|
||||
expect(markers.map((marker) => marker.getAttribute("data-player"))).to.deep.equal(["3", "2", "1", "0"]);
|
||||
expect(markers[1].querySelector(".planet-fill.p")).not.to.equal(null);
|
||||
expect(markers[1].getAttribute("aria-label")).to.equal("Explored by Player 3 (Moweyds)");
|
||||
expect(markers.filter((marker) => marker.classList.contains("recent"))).to.deep.equal([markers[1]]);
|
||||
expect(ship(Spaceship.Twilight).querySelector("title").textContent).to.contain("Explored by Player 3");
|
||||
expect(ship(Spaceship.Eclipse).querySelectorAll(".lost-fleet-spaceship__explorer").length).to.equal(1);
|
||||
expect(ship(Spaceship.Rebellion).querySelectorAll(".lost-fleet-spaceship__explorer").length).to.equal(0);
|
||||
});
|
||||
|
||||
it("renders Lost Fleet Interspace and Deep Space hexes in addition to the base sectors", () => {
|
||||
const engine = new Engine(["init 2 lost-fleet-space-map"], { lostFleet: true });
|
||||
const store = makeStore();
|
||||
|
|
@ -461,140 +496,4 @@ describe("SpaceMap", () => {
|
|||
|
||||
expect(container.querySelectorAll(".finalScoringTile").length).to.equal(0);
|
||||
});
|
||||
|
||||
describe("the analysis mode map-corner button (docs/lost-fleet/ANALYSIS_MODE_PLAN.md §5.4)", () => {
|
||||
function mountWithProps(props: { analysisOffered?: boolean; analysisActive?: boolean; analysisCanEdit?: boolean }) {
|
||||
const engine = loadFixtureEngine();
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", engine);
|
||||
return render(SpaceMap, { store, props });
|
||||
}
|
||||
|
||||
it("is hidden when neither offered nor active", () => {
|
||||
const { container } = mountWithProps({ analysisOffered: false, analysisActive: false });
|
||||
expect(container.querySelector(".space-map__analysis-button")).to.equal(null);
|
||||
});
|
||||
|
||||
it("shows a neutral (not warning-styled) button when merely offered", () => {
|
||||
const { container } = mountWithProps({ analysisOffered: true, analysisActive: false });
|
||||
const button = container.querySelector(".space-map__analysis-button");
|
||||
expect(button).to.not.equal(null);
|
||||
expect(button.classList.contains("space-map__analysis-button--active")).to.equal(false);
|
||||
expect(button.querySelector("title").textContent).to.equal("Enter sandbox mode");
|
||||
});
|
||||
|
||||
it("shows the warning-styled button and the Exit label while active", () => {
|
||||
const { container } = mountWithProps({ analysisOffered: false, analysisActive: true });
|
||||
const button = container.querySelector(".space-map__analysis-button");
|
||||
expect(button).to.not.equal(null);
|
||||
expect(button.classList.contains("space-map__analysis-button--active")).to.equal(true);
|
||||
expect(button.querySelector("title").textContent).to.equal("Exit sandbox mode");
|
||||
});
|
||||
|
||||
it("emits analysis-toggle when clicked, regardless of which state it's in", async () => {
|
||||
const { container, emitted } = mountWithProps({ analysisOffered: true, analysisActive: false });
|
||||
const button = container.querySelector(".space-map__analysis-button");
|
||||
await fireEvent.click(button);
|
||||
expect(emitted()["analysis-toggle"]).to.have.length(1);
|
||||
});
|
||||
|
||||
it("offers Undo/Reset beside the toggle only while the sandbox is open", () => {
|
||||
const offered = mountWithProps({ analysisOffered: true, analysisActive: false });
|
||||
expect(offered.container.querySelector(".space-map__analysis-button--undo")).to.equal(null);
|
||||
expect(offered.container.querySelector(".space-map__analysis-button--reset")).to.equal(null);
|
||||
|
||||
const { container } = mountWithProps({ analysisActive: true, analysisCanEdit: true });
|
||||
expect(container.querySelector(".space-map__analysis-button--undo")).to.not.equal(null);
|
||||
expect(container.querySelector(".space-map__analysis-button--reset")).to.not.equal(null);
|
||||
});
|
||||
|
||||
it("keeps the toggle first in document order, so a bare .space-map__analysis-button query still finds it", () => {
|
||||
const { container } = mountWithProps({ analysisActive: true, analysisCanEdit: true });
|
||||
expect(container.querySelector(".space-map__analysis-button title").textContent).to.equal("Exit sandbox mode");
|
||||
});
|
||||
|
||||
it("lays the three controls out right to left - toggle, Reset, Undo - all on the bottom edge", () => {
|
||||
const { container } = mountWithProps({ analysisActive: true, analysisCanEdit: true });
|
||||
const x = (selector: string) => {
|
||||
const match = /translate\((-?[\d.]+),\s*(-?[\d.]+)\)/.exec(
|
||||
container.querySelector(selector).getAttribute("transform")
|
||||
);
|
||||
return { x: Number(match[1]), y: Number(match[2]) };
|
||||
};
|
||||
const toggle = x(".space-map__analysis-button");
|
||||
const reset = x(".space-map__analysis-button--reset");
|
||||
const undo = x(".space-map__analysis-button--undo");
|
||||
|
||||
expect(undo.x).to.be.lessThan(reset.x);
|
||||
expect(reset.x).to.be.lessThan(toggle.x);
|
||||
expect(reset.y).to.equal(toggle.y);
|
||||
expect(undo.y).to.equal(toggle.y);
|
||||
});
|
||||
|
||||
it("emits analysis-undo / analysis-reset when they are pressable, and nothing at all for an empty line", async () => {
|
||||
const live = mountWithProps({ analysisActive: true, analysisCanEdit: true });
|
||||
await fireEvent.click(live.container.querySelector(".space-map__analysis-button--undo"));
|
||||
await fireEvent.click(live.container.querySelector(".space-map__analysis-button--reset"));
|
||||
expect(live.emitted()["analysis-undo"]).to.have.length(1);
|
||||
expect(live.emitted()["analysis-reset"]).to.have.length(1);
|
||||
|
||||
// Still rendered (so the toggle beside them never shifts), but inert - CSS also takes their
|
||||
// pointer events away, which jsdom does not apply, hence the handler's own guard.
|
||||
const empty = mountWithProps({ analysisActive: true, analysisCanEdit: false });
|
||||
const undo = empty.container.querySelector(".space-map__analysis-button--undo");
|
||||
expect(undo.classList.contains("space-map__analysis-button--inert")).to.equal(true);
|
||||
await fireEvent.click(undo);
|
||||
expect(empty.emitted()["analysis-undo"]).to.equal(undefined);
|
||||
});
|
||||
|
||||
it("never overlaps a hex, for any Lost Fleet player count", () => {
|
||||
// Same geometric-clearance methodology as the faction-wheel test above: derive the button's
|
||||
// actual rendered bounding box from its own transform (not a hardcoded guess) and assert no
|
||||
// hex (inflated by its own ~1-unit radius) intersects it.
|
||||
const rotationDeg = (players: number) => (players === 3 ? 0 : 60);
|
||||
const rotate = (x: number, y: number, deg: number) => {
|
||||
const rad = (deg * Math.PI) / 180;
|
||||
const cos = Math.cos(rad);
|
||||
const sin = Math.sin(rad);
|
||||
return { x: x * cos - y * sin, y: x * sin + y * cos };
|
||||
};
|
||||
|
||||
for (const players of [2, 3, 4]) {
|
||||
const engine = new Engine([`init ${players} lost-fleet-space-map`], { lostFleet: true });
|
||||
const store = makeStore();
|
||||
store.commit("receiveData", engine);
|
||||
|
||||
const { container } = render(SpaceMap, { store, props: { analysisActive: true, analysisCanEdit: true } });
|
||||
|
||||
// All three corner controls, not just the toggle: Undo/Reset extend the row leftwards, so
|
||||
// they are the ones actually at risk of reaching a hex.
|
||||
const buttons = container.querySelectorAll(".space-map__analysis-button");
|
||||
expect(buttons.length, `${players}p expected toggle + Undo + Reset`).to.equal(3);
|
||||
|
||||
for (const button of buttons) {
|
||||
const match = /translate\((-?[\d.]+),\s*(-?[\d.]+)\)\s*scale\((-?[\d.]+)\)/.exec(
|
||||
button.getAttribute("transform") ?? ""
|
||||
);
|
||||
expect(match, `${players}p expected an anchored+scaled transform`).to.not.equal(null);
|
||||
const origin = { x: Number(match[1]), y: Number(match[2]) };
|
||||
const scale = Number(match[3]);
|
||||
// The badge rect's own local footprint is x=-11..11, y=-11..11 (see the template).
|
||||
const buttonBox = {
|
||||
left: origin.x - 11 * scale,
|
||||
right: origin.x + 11 * scale,
|
||||
top: origin.y - 11 * scale,
|
||||
bottom: origin.y + 11 * scale,
|
||||
};
|
||||
|
||||
for (const hex of engine.map.grid.values()) {
|
||||
const raw = hexCenter(hex);
|
||||
const c = rotate(raw.x * 1.01, raw.y * 1.01, rotationDeg(players));
|
||||
const overlapsX = c.x + 1 > buttonBox.left && c.x - 1 < buttonBox.right;
|
||||
const overlapsY = c.y + 1 > buttonBox.top && c.y - 1 < buttonBox.bottom;
|
||||
expect(overlapsX && overlapsY, `${players}p button overlaps hex at (${c.x}, ${c.y})`).to.equal(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -73,44 +73,6 @@
|
|||
role="button"
|
||||
:transform="`translate(${bounds.right - 1.9}, ${bounds.top + 1.4}) scale(0.1)`"
|
||||
/>
|
||||
<!-- Analysis mode's map-corner button (docs/lost-fleet/ANALYSIS_MODE_PLAN.md §5.4) - the
|
||||
bottom-right mirror of the chart icon above, same inset/scale convention, anchored to
|
||||
bounds.bottom instead of bounds.top. One button toggles both directions: Game.vue decides
|
||||
enter vs. exit from its own analysisMode state, so this component only ever has to say
|
||||
"the button was pressed." -->
|
||||
<g
|
||||
v-if="analysisOffered || analysisActive"
|
||||
class="space-map__analysis-button"
|
||||
:class="{ 'space-map__analysis-button--active': analysisActive }"
|
||||
role="button"
|
||||
:transform="`translate(${analysisButtonX(0)}, ${analysisButtonY}) scale(0.1)`"
|
||||
@click="$emit('analysis-toggle')"
|
||||
>
|
||||
<title>{{ analysisActive ? "Exit sandbox mode" : "Enter sandbox mode" }}</title>
|
||||
<rect class="space-map__analysis-badge" x="-11" y="-11" width="22" height="22" rx="4" />
|
||||
<use xlink:href="#analysis-calculator" transform="translate(-8.75, -8.75)" />
|
||||
</g>
|
||||
<!-- Undo / Reset for the sandbox line, in the same corner as the toggle above rather than in the
|
||||
striped header they used to live in (owner instruction) - so the three sandbox controls are
|
||||
one cluster instead of two, and editing the line no longer means leaving the board.
|
||||
Rendered AFTER the toggle deliberately: they sit to its LEFT (`analysisButtonX` counts right
|
||||
to left), but keeping the toggle first in document order means `.space-map__analysis-button`
|
||||
still resolves to it, as SpaceMap.spec.ts and anything else querying the corner expects.
|
||||
Kept on screen but inert while the line is empty, so the toggle never shifts position the
|
||||
moment the first move lands. -->
|
||||
<g
|
||||
v-for="(control, i) in analysisLineControls"
|
||||
:key="control.event"
|
||||
class="space-map__analysis-button space-map__analysis-button--active"
|
||||
:class="[control.class, { 'space-map__analysis-button--inert': !analysisCanEdit }]"
|
||||
role="button"
|
||||
:transform="`translate(${analysisButtonX(i + 1)}, ${analysisButtonY}) scale(0.1)`"
|
||||
@click="analysisCanEdit && $emit(control.event)"
|
||||
>
|
||||
<title>{{ control.title }}</title>
|
||||
<rect class="space-map__analysis-badge" x="-11" y="-11" width="22" height="22" rx="4" />
|
||||
<use :xlink:href="`#${control.icon}`" transform="translate(-8.75, -8.75)" />
|
||||
</g>
|
||||
<rect
|
||||
v-for="(planet, i) in terraformingColors"
|
||||
:key="planet"
|
||||
|
|
@ -148,7 +110,7 @@ import Engine, {
|
|||
import { lostFleetTerraformingBoard } from "@gaia-project/engine/src/factions";
|
||||
import { CubeCoordinates } from "hexagrid";
|
||||
import Vue from "vue";
|
||||
import { Component, Prop } from "vue-property-decorator";
|
||||
import { Component } from "vue-property-decorator";
|
||||
import type { MapMode } from "../data/actions";
|
||||
import { MapModeType } from "../data/actions";
|
||||
import { HEX_SPREAD, hexCenter } from "../graphics/hex";
|
||||
|
|
@ -192,20 +154,6 @@ const RIGHT_SWATCH_WIDTH = 7.5;
|
|||
const RIGHT_ICON_WIDTH = 3;
|
||||
const RIGHT_BAND_HEIGHT = 2.5;
|
||||
|
||||
// Analysis mode's map-corner buttons (§5.4), anchored to bounds.bottom/bounds.right instead of
|
||||
// bounds.top/bounds.right like the chart icon above - same footprint class as RIGHT_ICON_WIDTH
|
||||
// (small square icons, never competing with anything else for this corner). The row grows leftwards
|
||||
// from `bounds.right`: the sandbox toggle is always slot 0, and Undo/Reset take slots 1 and 2 while
|
||||
// the sandbox is open.
|
||||
const ANALYSIS_ICON_WIDTH = 3;
|
||||
const ANALYSIS_ICON_INSET = 1.9;
|
||||
const ANALYSIS_ICON_STEP = 2.6;
|
||||
// How far up from `bounds.bottom` the row actually reaches: its centre line sits ANALYSIS_ICON_INSET
|
||||
// up, and a badge is 22 units at scale 0.1, i.e. 1.1 above that. Anything shorter leaves a sliver of
|
||||
// hexes that the clearance query below never sees but the icons still overlap - which only became
|
||||
// visible once Undo/Reset widened the row enough to reach them.
|
||||
const ANALYSIS_BAND_HEIGHT = ANALYSIS_ICON_INSET + 1.1;
|
||||
|
||||
// Small safety gap kept between a hex's own edge (radius 1) and the nearest UI content edge, on
|
||||
// top of the content's own measured footprint.
|
||||
const CLEARANCE = 0.3;
|
||||
|
|
@ -239,19 +187,6 @@ function bandMaxX(points: Point[], top: number, height: number): number {
|
|||
return max;
|
||||
}
|
||||
|
||||
/** Mirror of `bandMaxX` measuring from the BOTTOM edge instead of the top - the analysis-mode
|
||||
* button anchors to `bounds.bottom`, so its clearance check needs hexes near the bottom-right
|
||||
* corner, not the top-right one `bandMaxX` already covers. */
|
||||
function bandMaxXFromBottom(points: Point[], bottom: number, height: number): number {
|
||||
let max = -Infinity;
|
||||
for (const p of points) {
|
||||
if (p.y >= bottom - height) {
|
||||
max = Math.max(max, p.x);
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
@Component<SpaceMap>({
|
||||
components: {
|
||||
FactionWheel,
|
||||
|
|
@ -261,52 +196,6 @@ function bandMaxXFromBottom(points: Point[], bottom: number, height: number): nu
|
|||
},
|
||||
})
|
||||
export default class SpaceMap extends Vue {
|
||||
/** Analysis mode's map-corner button (§5.4) - both props default false so a caller that never
|
||||
* passes them (there is none left in this codebase, but the props aren't required) renders the
|
||||
* map exactly as it did before this button existed. `analysisOffered`/`analysisMode` are Game.vue's
|
||||
* own single source of truth (the latter's sealed-bid-round handling in particular) - deliberately
|
||||
* NOT re-derived here, to avoid a second copy of that logic drifting out of sync with the first. */
|
||||
@Prop({ default: false }) analysisOffered: boolean;
|
||||
@Prop({ default: false }) analysisActive: boolean;
|
||||
/** Whether the sandbox line currently holds anything to undo or clear - Game.vue's
|
||||
* `analysisEntries.length > 0`, i.e. exactly what gated the header buttons these replaced. */
|
||||
@Prop({ default: false }) analysisCanEdit: boolean;
|
||||
|
||||
/** The sandbox line controls, in the order they occupy slots to the left of the toggle. Empty
|
||||
* unless the sandbox is actually open: they act on a line that does not exist otherwise, and the
|
||||
* corner would then reserve map width for two icons nobody can press. */
|
||||
get analysisLineControls(): { event: string; icon: string; title: string; class: string }[] {
|
||||
if (!this.analysisActive) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
event: "analysis-reset",
|
||||
icon: "analysis-reset",
|
||||
title: "Clear the whole sandbox line",
|
||||
class: "space-map__analysis-button--reset",
|
||||
},
|
||||
{
|
||||
event: "analysis-undo",
|
||||
icon: "analysis-undo",
|
||||
title: "Undo the last move in the sandbox line",
|
||||
class: "space-map__analysis-button--undo",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** x of the corner control in `slot`, counting right to left from the map's right edge - so the
|
||||
* toggle keeps the exact position it had before Undo/Reset joined it. */
|
||||
analysisButtonX(slot: number): number {
|
||||
return this.bounds.right - ANALYSIS_ICON_INSET - slot * ANALYSIS_ICON_STEP;
|
||||
}
|
||||
|
||||
/** Shared y for the whole row, so it can never drift from the clearance ANALYSIS_BAND_HEIGHT
|
||||
* reserves for it. */
|
||||
get analysisButtonY(): number {
|
||||
return this.bounds.bottom - ANALYSIS_ICON_INSET;
|
||||
}
|
||||
|
||||
hexCenter(hex: CubeCoordinates) {
|
||||
return hexCenter(hex);
|
||||
}
|
||||
|
|
@ -610,19 +499,7 @@ export default class SpaceMap extends Vue {
|
|||
const rightWidth = this.terraformingColors.length > 0 ? RIGHT_SWATCH_WIDTH : this.showCharts ? RIGHT_ICON_WIDTH : 0;
|
||||
const rightLimitTop = bandMaxX(points, top, RIGHT_BAND_HEIGHT + hexRadius) + hexRadius + CLEARANCE + rightWidth;
|
||||
|
||||
// Analysis mode's map-corner button (§5.4) - a second, independent right-edge constraint from
|
||||
// the BOTTOM band, since it sits in the opposite corner from the chart icon/swatches above and
|
||||
// the two bands never overlap for any board shape this game has.
|
||||
const showAnalysisButton = this.analysisOffered || this.analysisActive;
|
||||
const rightLimitBottom = showAnalysisButton
|
||||
? bandMaxXFromBottom(points, bottom, ANALYSIS_BAND_HEIGHT + hexRadius) +
|
||||
hexRadius +
|
||||
CLEARANCE +
|
||||
ANALYSIS_ICON_WIDTH +
|
||||
this.analysisLineControls.length * ANALYSIS_ICON_STEP
|
||||
: -Infinity;
|
||||
|
||||
const right = Math.max(tightRight, rightWidth > 0 ? rightLimitTop : tightRight, rightLimitBottom);
|
||||
const right = Math.max(tightRight, rightWidth > 0 ? rightLimitTop : tightRight);
|
||||
|
||||
if (this.isLostFleet && this.engine.players.length === 2) {
|
||||
// The 2p hex field is symmetric around x=0. Frame the wheel/UI constraints symmetrically too,
|
||||
|
|
|
|||
|
|
@ -15,51 +15,6 @@
|
|||
stroke="black"
|
||||
transform="scale(.7) translate(4, -3.5)"
|
||||
/>
|
||||
<!-- Sandbox mode's map-corner button (docs/lost-fleet/ANALYSIS_MODE_PLAN.md §5.4) - a calculator
|
||||
(owner instruction; it was a magnifying glass), drawn in the same artwork style as the stats
|
||||
button diagonally opposite it on the map: one solid filled silhouette, screen and keys cut
|
||||
out of the body as holes via `fill-rule="evenodd"` rather than painted in a background
|
||||
colour, so it renders identically over the neutral badge and the warning-coloured active one.
|
||||
Geometry rather than an external asset, so the fill follows `currentColor` - SpaceMap.vue's
|
||||
CSS is what sets that per offered/active state. Drawn on the same ~17.5-unit box the
|
||||
magnifier used, so the `translate(-8.75, -8.75)` that centres it in the badge is unchanged. -->
|
||||
<g id="analysis-calculator">
|
||||
<path
|
||||
fill="currentColor"
|
||||
fill-rule="evenodd"
|
||||
d="M4.5 1 H13 A1.5 1.5 0 0 1 14.5 2.5 V15 A1.5 1.5 0 0 1 13 16.5 H4.5 A1.5 1.5 0 0 1 3 15 V2.5 A1.5 1.5 0 0 1 4.5 1 Z
|
||||
M4.5 2.5 H13 V5.5 H4.5 Z
|
||||
M4.5 6.5 H6.8 V8.8 H4.5 Z M7.6 6.5 H9.9 V8.8 H7.6 Z M10.7 6.5 H13 V8.8 H10.7 Z
|
||||
M4.5 9.6 H6.8 V11.9 H4.5 Z M7.6 9.6 H9.9 V11.9 H7.6 Z M10.7 9.6 H13 V11.9 H10.7 Z
|
||||
M4.5 12.7 H6.8 V15 H4.5 Z M7.6 12.7 H9.9 V15 H7.6 Z M10.7 12.7 H13 V15 H10.7 Z"
|
||||
/>
|
||||
</g>
|
||||
<!-- Sandbox mode's two line controls, sitting beside the calculator in the map's bottom-right
|
||||
corner (SpaceMap.vue). Same 17.5-unit box and `currentColor` fill as the calculator above,
|
||||
so the shared `translate(-8.75, -8.75)` centres all three in the same badge and one CSS rule
|
||||
colours them. Undo is a single step back (the arc's arrowhead is the tail, so it reads as
|
||||
"one move", not "restart"); Reset empties the whole line, hence a bin rather than a second
|
||||
arrow - two curved arrows at 22px are not tellable apart. -->
|
||||
<g id="analysis-undo">
|
||||
<path
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2.4"
|
||||
stroke-linecap="round"
|
||||
d="M 3.75 8 A 5 5 0 1 1 12.58 11.21"
|
||||
/>
|
||||
<polygon fill="currentColor" points="3.75,14 0.35,7.6 7.15,7.6" />
|
||||
</g>
|
||||
<g id="analysis-reset">
|
||||
<path
|
||||
fill="currentColor"
|
||||
fill-rule="evenodd"
|
||||
d="M6.6 1.4 H10.9 V3.4 H14.6 V5.4 H2.9 V3.4 H6.6 Z
|
||||
M4.3 6.6 H13.2 L12.4 15.7 A1.1 1.1 0 0 1 11.3 16.7 H6.2 A1.1 1.1 0 0 1 5.1 15.7 Z
|
||||
M6.9 8.4 H8.1 V14.8 H6.9 Z
|
||||
M9.4 8.4 H10.6 V14.8 H9.4 Z"
|
||||
/>
|
||||
</g>
|
||||
</defs>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
|
|
|
|||
|
|
@ -29,5 +29,5 @@ export const mapModeTypeOptions = [
|
|||
{ value: MapModeType.default, text: "Default" },
|
||||
{ value: MapModeType.sectors, text: "Sectors" },
|
||||
{ value: MapModeType.federations, text: "Federations" },
|
||||
{ value: MapModeType.leech, text: "Leech Network" },
|
||||
{ value: MapModeType.leech, text: "Charge Network" },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -3,18 +3,6 @@ import { afterEach, beforeEach, vi } from "vitest";
|
|||
import Vue from "vue";
|
||||
import launch from "./launcher";
|
||||
|
||||
// Regression test for a real bug found in a live two-browser session (docs/lost-fleet/PROGRESS.md
|
||||
// #73): launcher.ts's store.subscribeAction handler is the ONLY bridge from a Vuex action dispatch
|
||||
// (e.g. PremoveBar.vue's `this.$store.dispatch("cancelAllPremoves", ...)`) to the event emitter
|
||||
// a hosting app listens on to actually call the backend. `cancelAllPremoves` and `reorderPremove` were
|
||||
// dispatched by the premove UI but never added to this bridge's forwarding list, so the mode-
|
||||
// switch-clears-queue and reorder buttons did nothing server-side despite the UI (confirm dialog,
|
||||
// button press state) looking like they worked - completely invisible to unit tests, since
|
||||
// PremoveBar.vue itself has no component-level test and every other premove test exercises
|
||||
// host.ts/resolvePremoveQueue directly, never through this bridge. Pin every premove-related action
|
||||
// type actually dispatched from a component (including `editPremove`, added for the Gaia 9 premove
|
||||
// UI redesign - Game.vue's queueCurrentPremove dispatches it) so a future one silently missing this
|
||||
// list fails loudly here instead of only in a live session.
|
||||
describe("launcher's store-to-emitter bridge", () => {
|
||||
beforeEach(() => {
|
||||
class Observer {
|
||||
|
|
@ -29,37 +17,38 @@ describe("launcher's store-to-emitter bridge", () => {
|
|||
vi.unstubAllGlobals();
|
||||
document.querySelectorAll(".bgs-game-chat, .chat-shortcut").forEach((element) => element.remove());
|
||||
});
|
||||
const premoveActionTypes = [
|
||||
"queuePremove",
|
||||
"cancelPremove",
|
||||
"editPremove",
|
||||
"cancelAllPremoves",
|
||||
"reorderPremove",
|
||||
"markPremoveFailureRead",
|
||||
];
|
||||
|
||||
for (const type of premoveActionTypes) {
|
||||
it(`forwards a "${type}" dispatch to the emitter`, () => {
|
||||
const container = document.createElement("div");
|
||||
container.id = `launcher-spec-${type}`;
|
||||
document.body.appendChild(container);
|
||||
|
||||
const item = launch(`#${container.id}`, Vue.component(`dummy-${type}`, { render: (h) => h("div") }));
|
||||
const payload = { seat: 0, seq: 1, move: "p1 up nav.", mode: "sequential", id: "abc" };
|
||||
|
||||
let received: unknown = undefined;
|
||||
item.on(type, (p: unknown) => {
|
||||
received = p;
|
||||
});
|
||||
|
||||
item.store.dispatch(type, payload);
|
||||
|
||||
expect(received).to.deep.equal(payload);
|
||||
|
||||
item.app.$destroy();
|
||||
// $mount(selector) replaces the matched element in place rather than mounting inside it, so
|
||||
// the live DOM node to clean up is item.app.$el, not the original (now-detached) container.
|
||||
item.app.$el.parentNode?.removeChild(item.app.$el);
|
||||
it("receives canonical settings and sends setting changes through the protocol", () => {
|
||||
const container = document.createElement("div");
|
||||
container.id = "launcher-settings";
|
||||
document.body.appendChild(container);
|
||||
const item = launch("#launcher-settings", Vue.extend({ render: (h) => h("div") }));
|
||||
item.emit("settings", { autoCharge: "3", autoIncome: true });
|
||||
expect(item.store.state.playerSettings).to.deep.equal({ autoCharge: "3", autoIncome: true });
|
||||
let received: unknown;
|
||||
item.on("update:setting", (update) => {
|
||||
received = update;
|
||||
});
|
||||
}
|
||||
item.store.dispatch("updatePlayerSetting", { name: "autoCharge", value: "4" });
|
||||
expect(received).to.deep.equal({ name: "autoCharge", value: "4" });
|
||||
expect(item.store.state.playerSettings.autoCharge).to.equal("3");
|
||||
item.app.$destroy();
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("sends a premove plan as an ordinary protocol move", () => {
|
||||
const container = document.createElement("div");
|
||||
container.id = "launcher-premove";
|
||||
document.body.appendChild(container);
|
||||
const item = launch("#launcher-premove", Vue.extend({ render: (h) => h("div") }));
|
||||
const payload = { type: "premoves", moves: ["p1 up nav."], requestId: "test", round: 1, turn: 0, revision: 0 };
|
||||
let received: unknown;
|
||||
item.on("move", (move) => {
|
||||
received = move;
|
||||
});
|
||||
item.store.dispatch("submitPlan", payload);
|
||||
expect(received).to.deep.equal(payload);
|
||||
expect(item.store.state.pendingPlan).to.deep.equal(payload);
|
||||
item.app.$destroy();
|
||||
container.remove();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import type { EventName } from "@boardgamers/protocol";
|
||||
import { downlinkSchemas, uplinkSchemas } from "@boardgamers/protocol";
|
||||
import { createViewer } from "@boardgamers/protocol/viewer";
|
||||
import type { PremoveCommand } from "@gaia-project/engine/src/premove-types";
|
||||
import BootstrapVue from "bootstrap-vue";
|
||||
import { EventEmitter } from "events";
|
||||
import Vue from "vue";
|
||||
|
|
@ -57,6 +58,8 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
let lastMovedAt = 0;
|
||||
|
||||
const store = makeStore();
|
||||
store.commit("hosted", true);
|
||||
let planTimer: ReturnType<typeof setTimeout>;
|
||||
|
||||
const app = new Vue({
|
||||
store,
|
||||
|
|
@ -94,14 +97,17 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
const item: EventEmitter & { store: typeof store; app: Vue } = Object.assign(new EventEmitter(), { store, app });
|
||||
|
||||
let replaying = false;
|
||||
const viewer = createViewer<Record<string, any>, string>({
|
||||
const viewer = createViewer<Record<string, any>, string | PremoveCommand>({
|
||||
async onState(data) {
|
||||
await store.dispatch("externalData", data);
|
||||
viewer.replaceLog(data?.moveHistory || []);
|
||||
if (!replaying) viewer.replaceLog(data?.moveHistory || []);
|
||||
await app.$nextTick();
|
||||
},
|
||||
onUpdate() {
|
||||
if (!replaying) viewer.fetchState();
|
||||
viewer.fetchState();
|
||||
},
|
||||
onSettings(data) {
|
||||
store.commit("playerSettings", data);
|
||||
},
|
||||
onPreferences(data) {
|
||||
store.commit("preferences", data);
|
||||
|
|
@ -142,23 +148,14 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
else console.error(error);
|
||||
},
|
||||
});
|
||||
// Gaia's premove/presence extensions still use its host emitter; standard events
|
||||
// pass through the shared protocol's validation and lifecycle.
|
||||
// Standard game actions, including premoves, use the BGS protocol.
|
||||
for (const event of Object.keys(downlinkSchemas)) {
|
||||
item.on(event, (payload) => viewer.emitter.receive(event, payload));
|
||||
}
|
||||
for (const event of Object.keys(uplinkSchemas) as EventName[]) {
|
||||
viewer.emitter.on(event, (payload) => item.emit(event, payload));
|
||||
}
|
||||
for (const event of [
|
||||
"premoveState",
|
||||
"premovePlayed",
|
||||
"cancelTriggerState",
|
||||
"cancelTriggerFired",
|
||||
"seatUsers",
|
||||
"seatLastActive",
|
||||
"presence",
|
||||
]) {
|
||||
for (const event of ["seatUsers", "seatLastActive", "presence"]) {
|
||||
item.on(event, (data) => store.commit(event, data));
|
||||
}
|
||||
installActionSounds(viewer.emitter);
|
||||
|
|
@ -176,6 +173,11 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
const unsub1 = store.subscribeAction(({ type, payload }) => {
|
||||
// console.log("spy action", type, payload);
|
||||
|
||||
if (type === "updatePlayerSetting") {
|
||||
viewer.updateSetting(payload.name, payload.value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === "move") {
|
||||
// There's a bug with the viewer, after an undo on some occasions moves are emitted twice in a row
|
||||
if (lastMovedAt + 50 > Date.now()) {
|
||||
|
|
@ -187,19 +189,18 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
type === "queuePremove" ||
|
||||
type === "cancelPremove" ||
|
||||
type === "editPremove" ||
|
||||
type === "cancelAllPremoves" ||
|
||||
type === "reorderPremove" ||
|
||||
type === "markPremoveFailureRead" ||
|
||||
type === "armCancelTrigger" ||
|
||||
type === "disarmCancelTrigger" ||
|
||||
type === "disarmAllCancelTriggers" ||
|
||||
type === "editCancelTrigger"
|
||||
) {
|
||||
item.emit(type, payload);
|
||||
if (type === "submitPlan") {
|
||||
store.commit("submittingPlan", payload);
|
||||
clearTimeout(planTimer);
|
||||
planTimer = setTimeout(() => {
|
||||
if (store.state.pendingPlan?.requestId !== payload.requestId) return;
|
||||
store.commit(
|
||||
"planError",
|
||||
"The server has not confirmed your plan. Your plan is still saved. Check the queue before trying again."
|
||||
);
|
||||
viewer.fetchState();
|
||||
}, 15000);
|
||||
viewer.move(payload);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -222,6 +223,7 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
|||
});
|
||||
|
||||
app.$once("hook:beforeDestroy", () => {
|
||||
clearTimeout(planTimer);
|
||||
unsub1();
|
||||
unsub2();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ import {
|
|||
loadAnalysisLines,
|
||||
markAnalysisSeat,
|
||||
MAX_ANALYSIS_LINES,
|
||||
MAX_COMMITTABLE_MOVES,
|
||||
moveBelongsToSeat,
|
||||
normalizeAnalysisLineSet,
|
||||
ownMoveCount,
|
||||
|
|
@ -30,11 +29,10 @@ import {
|
|||
resolveOpponentDecisions,
|
||||
saveAnalysisLines,
|
||||
settleAnalysisClone,
|
||||
stripCappedPass,
|
||||
summarizeAnalysisLine,
|
||||
} from "./analysis";
|
||||
|
||||
// Same fixture as premove-preview.spec.ts: after these moves it's terrans' (seat 0) turn.
|
||||
// After these moves it's terrans' (seat 0) turn.
|
||||
const SETUP_MOVES = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
|
|
@ -60,14 +58,11 @@ describe("replayAnalysisLine", () => {
|
|||
expect(engine.moveHistory[engine.moveHistory.length - 1]).to.equal("terrans up nav (0 ⇒ 1).");
|
||||
});
|
||||
|
||||
it("accumulates the assumed power top-up across the whole line, not just its last entry", () => {
|
||||
// Every replay step round-trips the engine through JSON, and `analysisAssumedPower` is
|
||||
// deliberately not serialized - so without being carried by hand the tally silently restarted on
|
||||
// each entry and the header could only ever report what the final move happened to top up.
|
||||
it("stops when earlier planned actions have spent the remaining power", () => {
|
||||
const origin = markAnalysisSeat(new Engine(SETUP_MOVES), 0);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
const first = replayAnalysisLine(origin, [{ kind: "move", move: "terrans action power3." }], 0, 1);
|
||||
const both = replayAnalysisLine(
|
||||
Object.assign(origin.players[0].data.power, { area1: 0, area2: 0, area3: 4 });
|
||||
const { engine, applied } = replayAnalysisLine(
|
||||
origin,
|
||||
[
|
||||
{ kind: "move", move: "terrans action power3." },
|
||||
|
|
@ -76,10 +71,9 @@ describe("replayAnalysisLine", () => {
|
|||
0,
|
||||
1
|
||||
);
|
||||
const afterOne = first.engine.players[0].data.analysisAssumedPower;
|
||||
expect(afterOne).to.be.greaterThan(0);
|
||||
expect(both.applied).to.equal(2);
|
||||
expect(both.engine.players[0].data.analysisAssumedPower).to.be.greaterThan(afterOne);
|
||||
expect(applied).to.equal(1);
|
||||
expect(engine.players[0].data.power.area3).to.equal(0);
|
||||
expect(engine.players[0].data.analysisAssumedPower).to.equal(0);
|
||||
});
|
||||
|
||||
it("stops at the first entry that has gone illegal, keeping the valid prefix", () => {
|
||||
|
|
@ -142,7 +136,7 @@ describe("replayAnalysisLine", () => {
|
|||
expect(second.engine.players[0].data.credits).to.equal(first.engine.players[0].data.credits);
|
||||
});
|
||||
|
||||
it("lets the seat overspend into debt rather than refusing the move", () => {
|
||||
it("rejects an unaffordable build without spending anything", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
origin.player(0).data.credits = 0;
|
||||
|
|
@ -150,26 +144,20 @@ describe("replayAnalysisLine", () => {
|
|||
|
||||
const { engine, applied } = replayAnalysisLine(origin, [{ kind: "move", move: "terrans build ts -1x2." }], 0, 1);
|
||||
|
||||
expect(applied).to.equal(1); // the move was offered and played anyway (§12)
|
||||
expect(applied).to.equal(0);
|
||||
const data = engine.players[0].data;
|
||||
expect(data.credits + data.ores).to.be.lessThan(0); // ...and the debt is real and visible
|
||||
expect(data.credits).to.equal(0);
|
||||
expect(data.ores).to.equal(0);
|
||||
});
|
||||
|
||||
it("never drives a power bowl negative - a power cost beyond the seat's is topped up and counted", () => {
|
||||
it("rejects a power action without inventing charges or tokens", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
const data = origin.player(0).data;
|
||||
data.power.area1 = 0;
|
||||
data.power.area2 = 0;
|
||||
data.power.area3 = 0;
|
||||
data.analysis = true;
|
||||
|
||||
data.spendPower(4);
|
||||
|
||||
expect(data.power.area1).to.be.at.least(0);
|
||||
expect(data.power.area2).to.be.at.least(0);
|
||||
expect(data.power.area3).to.be.at.least(0);
|
||||
expect(data.analysisAssumedPower).to.be.at.least(4);
|
||||
Object.assign(origin.player(0).data.power, { area1: 0, area2: 0, area3: 0 });
|
||||
const { engine, applied } = replayAnalysisLine(origin, [{ kind: "move", move: "terrans action power3." }], 0, 1);
|
||||
expect(applied).to.equal(0);
|
||||
expect(engine.players[0].data.power).to.deep.equal(origin.players[0].data.power);
|
||||
expect(engine.players[0].data.analysisAssumedPower).to.equal(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -234,66 +222,67 @@ describe("moveBelongsToSeat", () => {
|
|||
});
|
||||
|
||||
describe("ownMoveCount", () => {
|
||||
it("counts only the moves in a real history slice that belong to the seat", () => {
|
||||
it("counts own turns without treating leech responses as played sandbox moves", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
const moves = ["terrans build m 2A3.", "nevlas charge 1pw", "terrans up nav."];
|
||||
expect(ownMoveCount(engine, moves, 0)).to.equal(2);
|
||||
expect(ownMoveCount(engine, moves, 1)).to.equal(1);
|
||||
expect(ownMoveCount(engine, moves, 1)).to.equal(0);
|
||||
expect(ownMoveCount(engine, [], 0)).to.equal(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dropPlayedAnalysisPrefix (§3.5 - restoring a line you then played for real)", () => {
|
||||
// The board AFTER this seat played the line's first move for real, settled the way the sandbox
|
||||
// settles an origin.
|
||||
function originAfterRealMove(): Engine {
|
||||
const engine = markAnalysisSeat(new Engine([...SETUP_MOVES, "terrans build m 2A3."]), 0);
|
||||
settleAnalysisClone(engine, 0);
|
||||
return engine;
|
||||
}
|
||||
describe("dropPlayedAnalysisPrefix", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
const move = (text: string): AnalysisEntry => ({ kind: "move", move: text });
|
||||
const nav = move("terrans up nav.");
|
||||
const mine = move("terrans build m 2A3.");
|
||||
|
||||
const LINE: AnalysisEntry[] = [
|
||||
{ kind: "move", move: "terrans build m 2A3." },
|
||||
{ kind: "move", move: "terrans up nav." },
|
||||
];
|
||||
|
||||
it("drops the leading entry the seat has since played for real, keeping the rest of the line", () => {
|
||||
// Before this, restoring here replayed from the top, hit the move that had just been played for
|
||||
// real (the mine is on the hex), stopped there, and reported "0 of 2 restored".
|
||||
const { entries, dropped } = dropPlayedAnalysisPrefix(originAfterRealMove(), LINE, 0, 1, 1);
|
||||
expect(dropped).to.equal(1);
|
||||
expect(entries).to.deep.equal([{ kind: "move", move: "terrans up nav." }]);
|
||||
expect(replayAnalysisLine(originAfterRealMove(), entries, 0, 1).applied).to.equal(1);
|
||||
it("trims a played research once even though it can still be researched again", () => {
|
||||
const result = dropPlayedAnalysisPrefix(engine, [nav, nav, mine], 0, ["terrans up nav (0 ⇒ 1)."]);
|
||||
expect(result.dropped).to.equal(1);
|
||||
expect(result.entries).to.deep.equal([nav, mine]);
|
||||
});
|
||||
|
||||
it("drops nothing when there were no real moves by this seat to account for it", () => {
|
||||
const { entries, dropped } = dropPlayedAnalysisPrefix(originAfterRealMove(), LINE, 0, 1, 0);
|
||||
expect(dropped).to.equal(0);
|
||||
expect(entries).to.equal(LINE);
|
||||
it("trims multiple turns through opponents and autoleech, including coordinate aliases", () => {
|
||||
const coords = engine.map.parse("2A3");
|
||||
const result = dropPlayedAnalysisPrefix(engine, [mine, nav, nav], 0, [
|
||||
`p1 build m ${coords.q}x${coords.r}.`,
|
||||
"nevlas up nav (0 ⇒ 1).",
|
||||
"terrans charge 1.",
|
||||
"terrans up nav (0 ⇒ 1).",
|
||||
]);
|
||||
expect(result.entries).to.deep.equal([nav]);
|
||||
expect(result.dropped).to.equal(2);
|
||||
});
|
||||
|
||||
it("never drops more entries than the seat has real moves to account for", () => {
|
||||
const line: AnalysisEntry[] = [
|
||||
{ kind: "move", move: "terrans build m 2A3." },
|
||||
{ kind: "move", move: "terrans build m 2A3." },
|
||||
];
|
||||
const { dropped } = dropPlayedAnalysisPrefix(originAfterRealMove(), line, 0, 1, 1);
|
||||
expect(dropped).to.equal(1);
|
||||
it("does not trim a different move, even when that planned move has become invalid", () => {
|
||||
const after = new Engine([...SETUP_MOVES, "terrans build m 2A3."]);
|
||||
const result = dropPlayedAnalysisPrefix(after, [mine, nav], 0, ["terrans up nav (0 ⇒ 1)."]);
|
||||
expect(result.entries).to.deep.equal([mine, nav]);
|
||||
expect(result.dropped).to.equal(0);
|
||||
});
|
||||
|
||||
it("keeps a leading entry that still applies, even with budget left to drop it", () => {
|
||||
// A move that is still playable cannot be one that has already been played, so the budget alone
|
||||
// is never enough to discard it.
|
||||
const line: AnalysisEntry[] = [{ kind: "move", move: "terrans up nav." }, ...LINE];
|
||||
const { entries, dropped } = dropPlayedAnalysisPrefix(originAfterRealMove(), line, 0, 1, 3);
|
||||
expect(dropped).to.equal(0);
|
||||
expect(entries).to.equal(line);
|
||||
it("removes simulated charges only together with their played turn", () => {
|
||||
const charge: AnalysisEntry = { kind: "adjust", charge: 2 };
|
||||
expect(dropPlayedAnalysisPrefix(engine, [charge, nav, charge, mine], 0, ["terrans up nav."]).entries).to.deep.equal(
|
||||
[charge, mine]
|
||||
);
|
||||
expect(dropPlayedAnalysisPrefix(engine, [charge, nav], 0, ["terrans charge 2."]).entries).to.deep.equal([
|
||||
charge,
|
||||
nav,
|
||||
]);
|
||||
});
|
||||
|
||||
it("stops at a non-move entry, which no real move can ever have been", () => {
|
||||
const line: AnalysisEntry[] = [{ kind: "adjust", charge: 1 }, ...LINE];
|
||||
const { dropped } = dropPlayedAnalysisPrefix(originAfterRealMove(), line, 0, 1, 2);
|
||||
expect(dropped).to.equal(0);
|
||||
it("matches a guarded upgrade when the regular control played the same building", () => {
|
||||
const ts = move("terrans build ts -1x2 cheap.");
|
||||
expect(
|
||||
dropPlayedAnalysisPrefix(engine, [ts, nav], 0, ["terrans build ts 3A3. (2/4/0/0 ⇒ 1/5/0/0)"]).entries
|
||||
).to.deep.equal([nav]);
|
||||
});
|
||||
|
||||
it("keeps the whole turn when only one command matches", () => {
|
||||
const turn = move("terrans spend 1q for 1o. up nav.");
|
||||
expect(dropPlayedAnalysisPrefix(engine, [turn], 0, ["terrans up nav."]).entries).to.deep.equal([turn]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -349,28 +338,6 @@ describe("applySoloRoundFlow", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("stripCappedPass", () => {
|
||||
it("keeps Pass available in the current round", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(engine, 0);
|
||||
stripCappedPass(engine, engine.round);
|
||||
expect(engine.availableCommands.some((c) => c.name === Command.Pass)).to.equal(true);
|
||||
});
|
||||
|
||||
it("removes Pass once the line has advanced into its one bonus round", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(engine, 0);
|
||||
const baseRound = engine.round; // 1
|
||||
const cmd = engine.findAvailableCommand(0, Command.Pass);
|
||||
engine.move(`terrans pass ${cmd.data.boosters[0]}`); // -> round 2, the one bonus round
|
||||
engine.generateAvailableCommandsIfNeeded();
|
||||
|
||||
stripCappedPass(engine, baseRound);
|
||||
|
||||
expect(engine.availableCommands.some((c) => c.name === Command.Pass)).to.equal(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOpponentDecisions", () => {
|
||||
it("does nothing when it is already the analysis seat's turn", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
|
|
@ -606,6 +573,14 @@ describe("computeAnalysisStatus (§12)", () => {
|
|||
expect(status.assumedPower).to.equal(0);
|
||||
});
|
||||
|
||||
it("distinguishes spending 4 ore from a remaining balance of minus 2", () => {
|
||||
const status = computeAnalysisStatus(view({ ores: -2 }), 0, view({ ores: 2 }));
|
||||
expect(status.changes).to.deep.equal([{ kind: "o", amount: -4 }]);
|
||||
expect(status.overdrawn).to.deep.equal([{ kind: "o", amount: -2 }]);
|
||||
const gain = computeAnalysisStatus(view({ ores: 3 }), 0, view({ ores: 2 }));
|
||||
expect(gain.changes).to.deep.equal([{ kind: "o", amount: 1 }]);
|
||||
});
|
||||
|
||||
it("lists every overdrawn resource, and only those", () => {
|
||||
const status = computeAnalysisStatus(view({ credits: -7, ores: 3, knowledge: -1, qics: 0 }));
|
||||
expect(status.overdrawn).to.deep.equal([
|
||||
|
|
@ -649,6 +624,15 @@ describe("analysis line persistence", () => {
|
|||
expect(loadAnalysisLines(1)).to.equal(null);
|
||||
});
|
||||
|
||||
it("keeps hosted games separate even when their iframe URL and seat match", () => {
|
||||
const set = { lines: [[up]], active: 0, baseRound: 1, baseMoveCount: 9 };
|
||||
saveAnalysisLines(0, set, "init 2 first-game");
|
||||
expect(loadAnalysisLines(0, "init 2 second-game")).to.equal(null);
|
||||
saveAnalysisLines(0, emptyAnalysisLineSet(1, 9), "init 2 second-game");
|
||||
clearAnalysisLine(0, "init 2 second-game");
|
||||
expect(loadAnalysisLines(0, "init 2 first-game")).to.deep.equal(set);
|
||||
});
|
||||
|
||||
it("returns null when nothing is stored", () => {
|
||||
expect(loadAnalysisLines(0)).to.equal(null);
|
||||
});
|
||||
|
|
@ -697,19 +681,31 @@ describe("analysis line persistence", () => {
|
|||
expect(analysisLineSetSize({ lines: [[up, up], [], [up]], active: 0, baseRound: 1, baseMoveCount: 9 })).to.equal(3);
|
||||
});
|
||||
|
||||
it("numbers the tabs rather than naming them", () => {
|
||||
expect(analysisLineLabel(0)).to.equal("Line 1");
|
||||
expect(analysisLineLabel(4)).to.equal("Line 5");
|
||||
it("labels alternative plans alphabetically", () => {
|
||||
expect(analysisLineLabel(0)).to.equal("Plan A");
|
||||
expect(analysisLineLabel(4)).to.equal("Plan E");
|
||||
});
|
||||
});
|
||||
|
||||
// §13's tab strip is only a comparison because each tab carries its own outcome - switching replaces
|
||||
// the board, so a strip that only switched would still leave the player comparing from memory.
|
||||
describe("summarizeAnalysisLine (§13)", () => {
|
||||
it("does not count simulated charges as game turns", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
const entries: AnalysisEntry[] = [
|
||||
{ kind: "adjust", charge: 1 },
|
||||
{ kind: "move", move: "terrans up nav." },
|
||||
{ kind: "adjust", charge: 1 },
|
||||
];
|
||||
const summary = summarizeAnalysisLine(origin, entries, 0, Round.Round1, 0);
|
||||
expect(summary.moves).to.equal(1);
|
||||
expect(summary.applied).to.equal(1);
|
||||
});
|
||||
|
||||
it("reports an empty line as no moves and no change", () => {
|
||||
const origin = markAnalysisSeat(new Engine(SETUP_MOVES), 0);
|
||||
expect(summarizeAnalysisLine(origin, [], 0, Round.Round1, 0)).to.deep.equal({
|
||||
label: "Line 1",
|
||||
label: "Plan A",
|
||||
moves: 0,
|
||||
victoryPoints: 0,
|
||||
overdrawn: false,
|
||||
|
|
@ -723,15 +719,13 @@ describe("summarizeAnalysisLine (§13)", () => {
|
|||
const entries: AnalysisEntry[] = [{ kind: "move", move: "terrans up nav." }];
|
||||
const summary = summarizeAnalysisLine(origin, entries, 0, Round.Round1, 1);
|
||||
const { engine } = replayAnalysisLine(origin, entries, 0, Round.Round1);
|
||||
expect(summary.label).to.equal("Line 2");
|
||||
expect(summary.label).to.equal("Plan B");
|
||||
expect(summary.moves).to.equal(1);
|
||||
expect(summary.applied).to.equal(1);
|
||||
expect(summary.victoryPoints).to.equal(engine.players[0].data.victoryPoints - base);
|
||||
});
|
||||
|
||||
it("flags a line that spends more than the seat has", () => {
|
||||
// Same setup as "lets the seat overspend into debt" above: nothing real to pay with, and a
|
||||
// trading station played anyway (§12 lifts affordability inside the sandbox).
|
||||
it("flags the unapplied move in an unaffordable line", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
origin.player(0).data.credits = 0;
|
||||
|
|
@ -743,8 +737,9 @@ describe("summarizeAnalysisLine (§13)", () => {
|
|||
Round.Round1,
|
||||
0
|
||||
);
|
||||
expect(summary.applied).to.equal(1);
|
||||
expect(summary.overdrawn).to.equal(true);
|
||||
expect(summary.moves).to.equal(1);
|
||||
expect(summary.applied).to.equal(0);
|
||||
expect(summary.overdrawn).to.equal(false);
|
||||
});
|
||||
|
||||
// A line trimmed by a re-anchor must not be compared as if it were whole - `applied` below `moves`
|
||||
|
|
@ -807,14 +802,19 @@ describe("committableAnalysisMoves (§6, decision #13)", () => {
|
|||
expect(moves).to.deep.equal(["terrans build m -1x2"]);
|
||||
});
|
||||
|
||||
it("commits nothing from a line holding a sandbox cheap Trading Station - it priced a neighbour that is not there", () => {
|
||||
it("keeps an affordable prefix when a later upgrade needs a neighbour that is not there", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
const entries: AnalysisEntry[] = [
|
||||
{ kind: "move", move: "terrans up nav." },
|
||||
{ kind: "move", move: "terrans build ts 4A4 cheap." },
|
||||
];
|
||||
|
||||
expect(committableAnalysisMoves(origin, entries, 0, Round.Round1)).to.deep.equal([]);
|
||||
expect(committableAnalysisMoves(origin, entries, 0, Round.Round1)).to.deep.equal(["terrans up nav."]);
|
||||
expect(analysisCommitPrefix(origin, entries, 0, Round.Round1, 1).moves).to.deep.equal([
|
||||
"terrans up nav.",
|
||||
"terrans build ts 4A4 cheap.",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns nothing for a line with no move entries at all", () => {
|
||||
|
|
@ -825,10 +825,6 @@ describe("committableAnalysisMoves (§6, decision #13)", () => {
|
|||
expect(committableAnalysisMoves(origin, [{ kind: "adjust", charge: 1 }], 0, 1)).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("caps at 1 live move plus PremoveBar.vue's 3-row queue limit (§6)", () => {
|
||||
expect(MAX_COMMITTABLE_MOVES).to.equal(4);
|
||||
});
|
||||
|
||||
it("truncates at an opponent's move, which setup pass-and-play puts in the line as an ordinary entry", () => {
|
||||
const origin = new Engine(["init 2 randomSeed", "p1 faction terrans", "p2 faction nevlas"]);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
|
|
@ -856,6 +852,28 @@ describe("committableAnalysisMoves (§6, decision #13)", () => {
|
|||
});
|
||||
|
||||
describe("analysisCommitPrefix - the cut reason behind the prefix", () => {
|
||||
it("requires enough resources in the simulated position even for future premoves", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
origin.players[0].data.knowledge = 0;
|
||||
const entries: AnalysisEntry[] = [
|
||||
{ kind: "adjust", charge: 1 },
|
||||
{ kind: "move", move: "terrans up nav." },
|
||||
];
|
||||
expect(analysisCommitPrefix(origin, entries, 0, 1, 0).moves).to.deep.equal([]);
|
||||
expect(analysisCommitPrefix(origin, entries, 0, 1, 1).moves).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("can queue a power action after explicit simulated charges, but cannot play it immediately", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
Object.assign(origin.players[0].data.power, { area1: 0, area2: 4, area3: 0 });
|
||||
const entries: AnalysisEntry[] = [
|
||||
{ kind: "adjust", charge: 4 },
|
||||
{ kind: "move", move: "terrans action power3." },
|
||||
];
|
||||
expect(analysisCommitPrefix(origin, entries, 0, 1, 0).moves).to.deep.equal(["terrans action power3."]);
|
||||
expect(analysisCommitPrefix(origin, entries, 0, 1, 1).moves).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("reports no cut for a line that is committable end to end", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
|
|
@ -866,7 +884,7 @@ describe("analysisCommitPrefix - the cut reason behind the prefix", () => {
|
|||
expect(cut).to.equal(null);
|
||||
});
|
||||
|
||||
it("names the overdraft when a move spends past the seat's real resources", () => {
|
||||
it("rejects an older saved draft that spends past the seat's resources", () => {
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
applySoloRoundFlow(origin, 0);
|
||||
origin.player(0).data.credits = 0;
|
||||
|
|
@ -875,20 +893,25 @@ describe("analysisCommitPrefix - the cut reason behind the prefix", () => {
|
|||
const { moves, cut } = analysisCommitPrefix(origin, [{ kind: "move", move: "terrans build ts -1x2." }], 0, 1);
|
||||
|
||||
expect(moves).to.deep.equal([]);
|
||||
expect(cut).to.equal("overdrawn");
|
||||
expect(cut).to.equal("illegal");
|
||||
});
|
||||
|
||||
it("names the faction seed and the cheap build, both of which void the whole line", () => {
|
||||
it("rejects an imagined faction, but allows a future 3c-only upgrade with its constraint intact", () => {
|
||||
const seeded = new Engine(["init 2 randomSeed"]);
|
||||
applySoloRoundFlow(seeded, 0);
|
||||
expect(
|
||||
analysisCommitPrefix(seeded, [{ kind: "faction", lineup: [Faction.Terrans, Faction.Nevlas] }], 0, 1).cut
|
||||
).to.equal("faction");
|
||||
|
||||
const cheap = new Engine(SETUP_MOVES);
|
||||
const origin = new Engine(SETUP_MOVES);
|
||||
const entries: AnalysisEntry[] = [{ kind: "move", move: "terrans build ts 4A4 cheap." }];
|
||||
expect(analysisCommitPrefix(origin, entries, 0, Round.Round1, 0).moves).to.deep.equal([
|
||||
"terrans build ts 4A4 cheap.",
|
||||
]);
|
||||
expect(analysisCommitPrefix(origin, entries, 0, Round.Round1, 1).moves).to.deep.equal([]);
|
||||
expect(
|
||||
analysisCommitPrefix(cheap, [{ kind: "move", move: "terrans build ts 4A4 cheap." }], 0, Round.Round1).cut
|
||||
).to.equal("cheap-build");
|
||||
analysisCommitPrefix(origin, [{ kind: "move", move: "terrans build ts 3A3 cheap." }], 0, Round.Round1, 1).moves
|
||||
).to.deep.equal(["terrans build ts 3A3 cheap."]);
|
||||
});
|
||||
|
||||
it("names the foreign move that setup pass-and-play left in the line", () => {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ import Engine, {
|
|||
Reward,
|
||||
Round,
|
||||
} from "@gaia-project/engine";
|
||||
import type { PremoveTiming } from "@gaia-project/engine/src/premove-types";
|
||||
|
||||
import { parseCommands } from "./recent";
|
||||
|
||||
// Analysis mode (docs/lost-fleet/ANALYSIS_MODE_PLAN.md) - a local, non-committing sandbox clone of
|
||||
// the board. The "line" is the ordered list of turns played inside it. Persistence is localStorage
|
||||
|
|
@ -57,26 +60,19 @@ export interface AnalysisResourceView {
|
|||
ores: number;
|
||||
knowledge: number;
|
||||
qics: number;
|
||||
victoryPoints?: number;
|
||||
/** The engine's own tally of power the sandbox assumed this seat charged (§12) - absent on a
|
||||
* plain-JSON'd snapshot taken before the field existed, hence optional. */
|
||||
analysisAssumedPower?: number;
|
||||
}
|
||||
|
||||
/** Marks the analysis seat's player data as the sandbox seat (§3.4/§12, engine player-data.ts's
|
||||
* `analysis` flag): affordability stops being enforced for it, so an unaffordable move can be played
|
||||
* and the resulting debt shown, and `spendPower` tops up rather than driving a power bowl negative.
|
||||
* Must be re-applied after every `Engine.fromData` reconstruction in this file, since the flag is
|
||||
* deliberately absent from `toJSON()` and so never survives a serialize/deserialize round trip.
|
||||
*
|
||||
* `analysisAssumedPower` (the running total of that top-up) is absent from `toJSON()` for the same
|
||||
* reason, and it is a TALLY rather than a flag - so every reconstruction has to be handed the total
|
||||
* so far explicitly, or the count silently restarts at 0 on each clone and the header can only ever
|
||||
* report whatever the last step happened to top up. Callers that continue an existing line pass the
|
||||
* carried total; a genuinely fresh start passes nothing and gets 0. */
|
||||
/** Enables explicit planning options while preserving the position's normal resource checks.
|
||||
* Re-applied after cloning because the flag is intentionally not serialized. */
|
||||
export function markAnalysisSeat(engine: Engine, seat: number, assumedPower = 0): Engine {
|
||||
const data = engine.players[seat]?.data;
|
||||
if (data) {
|
||||
data.analysis = true;
|
||||
data.validatingFuturePremove = false;
|
||||
data.analysisAssumedPower = assumedPower;
|
||||
}
|
||||
return engine;
|
||||
|
|
@ -98,32 +94,20 @@ export function chargedPowerTotal(entries: AnalysisEntry[]): number {
|
|||
return entries.reduce((total, entry) => (entry.kind === "adjust" ? total + entry.charge : total), 0);
|
||||
}
|
||||
|
||||
/** One overdrawn resource: how far below zero the line has driven it. */
|
||||
export interface AnalysisOverdraft {
|
||||
/** The resource's single-letter icon key, matching the viewer's own `Resource` kinds. */
|
||||
kind: "c" | "o" | "k" | "q";
|
||||
/** Always negative - the number the player board is showing in red. */
|
||||
export interface AnalysisResourceChange {
|
||||
/** The resource's icon key, matching the viewer's own `Resource` kinds. */
|
||||
kind: "c" | "o" | "k" | "q" | "vp";
|
||||
/** Signed amount: positive for a gain, negative for a spend or deficit. */
|
||||
amount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the header needs to say about a line, and nothing more (§12).
|
||||
*
|
||||
* There used to be a full per-resource counter here, with a `displayed` figure (clone minus the
|
||||
* granted sandbox wallet) beside a `net` one, plus a power bowl delta and a per-entry feasibility
|
||||
* scan. All of it existed to undo the fake wallet analysis mode used to inject. Nothing injects
|
||||
* anything now - the seat keeps its real resources and simply goes negative - so the player board is
|
||||
* already showing every one of those numbers, live, in the place players actually read them. What is
|
||||
* left is the three facts the board CANNOT show: a compact overdraft summary for when the board is
|
||||
* scrolled off screen on mobile, how much power the sandbox topped up on its own, and how much the
|
||||
* player has told it to assume they charge.
|
||||
*
|
||||
* The last one matters because a Charge 1 press and a power spend both just move tokens between
|
||||
* bowls - once a later move has spent that power, the bowls can read exactly as they did before the
|
||||
* charge, so "did my charge land?" is genuinely unanswerable from the board alone (the reported
|
||||
* bug). The running total answers it.
|
||||
*/
|
||||
/** One overdrawn resource: how far below zero the plan has driven it. */
|
||||
export type AnalysisOverdraft = AnalysisResourceChange;
|
||||
|
||||
/** Resource changes and simulation assumptions for the selected plan. */
|
||||
export interface AnalysisStatus {
|
||||
/** Net resource change from the start of the selected plan, including the unfinished turn. */
|
||||
changes?: AnalysisResourceChange[];
|
||||
/** Empty when the line is genuinely affordable. */
|
||||
overdrawn: AnalysisOverdraft[];
|
||||
/** 0 unless a power cost was topped up (see engine `assumePowerForAnalysis`). */
|
||||
|
|
@ -132,7 +116,11 @@ export interface AnalysisStatus {
|
|||
chargedPower: number;
|
||||
}
|
||||
|
||||
export function computeAnalysisStatus(data: AnalysisResourceView, chargedPower = 0): AnalysisStatus {
|
||||
export function computeAnalysisStatus(
|
||||
data: AnalysisResourceView,
|
||||
chargedPower = 0,
|
||||
origin?: AnalysisResourceView
|
||||
): AnalysisStatus {
|
||||
const overdrawn: AnalysisOverdraft[] = [];
|
||||
const add = (kind: AnalysisOverdraft["kind"], amount: number) => {
|
||||
if (amount < 0) {
|
||||
|
|
@ -143,7 +131,20 @@ export function computeAnalysisStatus(data: AnalysisResourceView, chargedPower =
|
|||
add("o", data.ores);
|
||||
add("k", data.knowledge);
|
||||
add("q", data.qics);
|
||||
return { overdrawn, assumedPower: data.analysisAssumedPower ?? 0, chargedPower };
|
||||
const changes: AnalysisResourceChange[] = origin
|
||||
? (
|
||||
[
|
||||
["c", "credits"],
|
||||
["o", "ores"],
|
||||
["k", "knowledge"],
|
||||
["q", "qics"],
|
||||
["vp", "victoryPoints"],
|
||||
] as const
|
||||
)
|
||||
.map(([kind, field]) => ({ kind, amount: (data[field] ?? 0) - (origin[field] ?? 0) }))
|
||||
.filter(({ amount }) => amount !== 0)
|
||||
: [];
|
||||
return { changes, overdrawn, assumedPower: data.analysisAssumedPower ?? 0, chargedPower };
|
||||
}
|
||||
|
||||
/** The stored shape BEFORE §13's tab strip - one line per game+seat. Kept solely so
|
||||
|
|
@ -176,6 +177,8 @@ export interface AnalysisLineSet {
|
|||
active: number;
|
||||
baseRound: number;
|
||||
baseMoveCount: number;
|
||||
/** Last real move at the saved base, used to detect a rollback before trimming. */
|
||||
baseMove?: string;
|
||||
}
|
||||
|
||||
/** How many lines the strip will hold. The cap is the header's width far more than localStorage's
|
||||
|
|
@ -183,11 +186,9 @@ export interface AnalysisLineSet {
|
|||
* horizontally to read is not much of a comparison. */
|
||||
export const MAX_ANALYSIS_LINES = 5;
|
||||
|
||||
/** Tabs are numbered, never named (owner instruction) - "Line 1", "Line 2". A name would be one more
|
||||
* thing to type before you can get on with the actual question, and the tab already carries the only
|
||||
* label that matters for comparing: its own outcome. */
|
||||
/** Label the alternative plans without requiring players to name them. */
|
||||
export function analysisLineLabel(index: number): string {
|
||||
return `Line ${index + 1}`;
|
||||
return `Plan ${String.fromCharCode(65 + index)}`;
|
||||
}
|
||||
|
||||
/** Forces the invariants the rest of the code assumes: at least one line, `active` inside it, and no
|
||||
|
|
@ -214,9 +215,10 @@ export function analysisLineSetSize(set: AnalysisLineSet): number {
|
|||
return set.lines.reduce((total, entries) => total + entries.length, 0);
|
||||
}
|
||||
|
||||
function storageKey(seat: number): string {
|
||||
// Same convention as the old notes sheet's localKey(): a hosted game's `?game=<id>` and a
|
||||
// self-contained game's full launch query string both already uniquely identify "this game".
|
||||
function storageKey(seat: number, scope?: string): string {
|
||||
// BGS shares one iframe URL across games. Its initial move contains the game seed/name,
|
||||
// so hosted callers supply that stable identity instead of sharing a query-string key.
|
||||
if (scope !== undefined) return `analysis-mode:game:${scope}:${seat}`;
|
||||
const search = typeof window !== "undefined" ? window.location.search : "";
|
||||
return `analysis-mode:${search}:${seat}`;
|
||||
}
|
||||
|
|
@ -229,15 +231,13 @@ function storageKey(seat: number): string {
|
|||
* leave the old one behind for a later version to trip over. A stored value that is neither shape
|
||||
* reads as "nothing stored", exactly as an unparseable one always has.
|
||||
*/
|
||||
export function loadAnalysisLines(seat: number): AnalysisLineSet | null {
|
||||
export function loadAnalysisLines(seat: number, scope?: string): AnalysisLineSet | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
const raw = window.localStorage.getItem(storageKey(seat));
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey(seat, scope));
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && Array.isArray(parsed.lines)) {
|
||||
return normalizeAnalysisLineSet(parsed as AnalysisLineSet);
|
||||
|
|
@ -257,9 +257,13 @@ export function loadAnalysisLines(seat: number): AnalysisLineSet | null {
|
|||
}
|
||||
}
|
||||
|
||||
export function saveAnalysisLines(seat: number, set: AnalysisLineSet): void {
|
||||
export function saveAnalysisLines(seat: number, set: AnalysisLineSet, scope?: string): void {
|
||||
if (typeof window !== "undefined") {
|
||||
window.localStorage.setItem(storageKey(seat), JSON.stringify(normalizeAnalysisLineSet(set)));
|
||||
try {
|
||||
window.localStorage.setItem(storageKey(seat, scope), JSON.stringify(normalizeAnalysisLineSet(set)));
|
||||
} catch {
|
||||
// A blocked/full browser store must not prevent playing or queuing a move.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -277,16 +281,16 @@ export function saveAnalysisLines(seat: number, set: AnalysisLineSet): void {
|
|||
* same double-digit number on every tab and the difference between them is the whole question.
|
||||
*/
|
||||
export interface AnalysisLineSummary {
|
||||
/** "Line 1", "Line 2" - see `analysisLineLabel`. */
|
||||
/** "Plan A", "Plan B" - see `analysisLineLabel`. */
|
||||
label: string;
|
||||
/** Entries in the line, including `adjust`/`faction` ones - the same figure the header counts. */
|
||||
/** Complete game turns, excluding simulation adjustments. */
|
||||
moves: number;
|
||||
/** VP this line ends on, minus the VP the seat started the sandbox with. */
|
||||
victoryPoints: number;
|
||||
/** True when the line spends more than the seat has - a VP total bought with resources that do not
|
||||
* exist is not comparable to one that is actually payable, so the tab has to say so. */
|
||||
overdrawn: boolean;
|
||||
/** How many entries actually replayed. Below `moves` only after a re-anchor (§3.5) dropped part of
|
||||
/** How many game turns actually replayed. Below `moves` only after a re-anchor (§3.5) dropped part of
|
||||
* the line; the tab flags it so a truncated line is never silently compared as if it were whole. */
|
||||
applied: number;
|
||||
}
|
||||
|
|
@ -316,10 +320,10 @@ export function summarizeAnalysisLine(
|
|||
const data = engine.players[seat]?.data;
|
||||
return {
|
||||
label,
|
||||
moves: entries.length,
|
||||
moves: entries.filter((entry) => entry.kind === "move").length,
|
||||
victoryPoints: (data?.victoryPoints ?? baseVictoryPoints) - baseVictoryPoints,
|
||||
overdrawn: data ? computeAnalysisStatus(data).overdrawn.length > 0 : false,
|
||||
applied,
|
||||
applied: entries.slice(0, applied).filter((entry) => entry.kind === "move").length,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -331,9 +335,13 @@ export function summarizeAnalysisLine(
|
|||
* other line in the set was an ALTERNATIVE to the move that has now been played for real, worked out
|
||||
* from a board state the game has since left. Keeping them would leave tabs sitting there whose
|
||||
* numbers describe a table that no longer exists. */
|
||||
export function clearAnalysisLine(seat: number): void {
|
||||
export function clearAnalysisLine(seat: number, scope?: string): void {
|
||||
if (typeof window !== "undefined") {
|
||||
window.localStorage.removeItem(storageKey(seat));
|
||||
try {
|
||||
window.localStorage.removeItem(storageKey(seat, scope));
|
||||
} catch {
|
||||
// The server queue remains independent of local sandbox persistence.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -590,23 +598,6 @@ export function applyFactionSeed(engine: Engine, lineup: Faction[]): void {
|
|||
endSetupFactionPhase(engine);
|
||||
}
|
||||
|
||||
/** The two-round cap (§3.7): Pass is allowed while still in the round the line started on;
|
||||
* suppressed once the clone has advanced into its one bonus round - except round 6, the deliberate
|
||||
* exception (passing there ends the game for real, which is worth seeing). Exported so the UI can
|
||||
* explain a missing Pass button rather than leave it looking like it just vanished. */
|
||||
export function passAllowed(round: number, baseRound: number): boolean {
|
||||
return round < baseRound + 1 || round === Round.LastRound;
|
||||
}
|
||||
|
||||
/** Removes Command.Pass from the clone's available commands once the two-round cap forbids it, so
|
||||
* the button is simply never offered - the same "if you can't, the button doesn't exist" principle
|
||||
* affordability already uses (§2.3), applied here to a policy limit instead of a resource one. */
|
||||
export function stripCappedPass(engine: Engine, baseRound: number): void {
|
||||
if (!passAllowed(engine.round, baseRound) && engine.availableCommands) {
|
||||
engine.availableCommands = engine.availableCommands.filter((c) => c.name !== Command.Pass);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opponent decisions (§2.8) - your own building can trigger a leech offer to an opponent
|
||||
* (`beginLeechingPhase`, move/phase.ts), and the engine pauses on `Phase.RoundLeech` waiting for
|
||||
|
|
@ -642,7 +633,9 @@ export function resolveOpponentDecisions(engine: Engine, seat: number): void {
|
|||
if (
|
||||
tryMoves(
|
||||
engine,
|
||||
offers.map((offer) => `${faction} ${Command.Decline} ${offer}`)
|
||||
offers.length
|
||||
? offers.map((offer) => `${faction} ${Command.Decline} ${offer}`)
|
||||
: [`${faction} ${Command.Decline}`]
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
|
|
@ -696,14 +689,22 @@ export function resolveOpponentDecisions(engine: Engine, seat: number): void {
|
|||
continue;
|
||||
}
|
||||
}
|
||||
// Not a leech offer (a brainstone placement, an income choice, a faction pick): the engine's own
|
||||
// heuristics are the right answer for those, and they cannot be expressed as a Decline.
|
||||
// Opponents cannot answer prompts in a solo preview. Use the engine's income/brainstone
|
||||
// heuristics even when their live preferences require a manual answer. Restore those settings
|
||||
// afterwards; the planning player's own choices are never automated here.
|
||||
const settings = engine.players[toMove].settings;
|
||||
const { autoIncome, autoBrainstone } = settings;
|
||||
try {
|
||||
settings.autoIncome = true;
|
||||
settings.autoBrainstone = true;
|
||||
if (engine.autoMove()) {
|
||||
continue;
|
||||
}
|
||||
} catch {
|
||||
break;
|
||||
} finally {
|
||||
settings.autoIncome = autoIncome;
|
||||
settings.autoBrainstone = autoBrainstone;
|
||||
}
|
||||
break; // Nothing this function knows how to resolve - stop rather than guess at a move.
|
||||
}
|
||||
|
|
@ -776,11 +777,7 @@ export function applyLeechAdjustment(engine: Engine, seat: number, charge: numbe
|
|||
data.gainRewards([new Reward(charge, Resource.ChargePower)], true, Command.ChargePower);
|
||||
}
|
||||
|
||||
/** Whether a real (already-committed) `move` string from `engine.moveHistory` was made by `seat` -
|
||||
* used for §3.5's staleness check, to tell "only opponents moved since this line was saved" apart
|
||||
* from "I moved myself" (the row that needs a keep/clear prompt instead of a silent replay). Mirrors
|
||||
* the exact prefix format `engine.ts`'s own `loadTurnMoves` parses a move's acting player from
|
||||
* (`p<N>`, 1-indexed, or the player's faction name) rather than inventing a second convention. */
|
||||
/** Identify a real move's seat using either its faction or the engine's p<N> notation. */
|
||||
export function moveBelongsToSeat(engine: Engine, move: string, seat: number): boolean {
|
||||
const spaceIndex = move.indexOf(" ");
|
||||
const token = spaceIndex === -1 ? move : move.slice(0, spaceIndex);
|
||||
|
|
@ -790,58 +787,65 @@ export function moveBelongsToSeat(engine: Engine, move: string, seat: number): b
|
|||
return engine.players[seat]?.faction === token;
|
||||
}
|
||||
|
||||
/** How many of `moves` (a slice of a real `moveHistory`) were played by `seat` - the budget behind
|
||||
* `dropPlayedAnalysisPrefix`. */
|
||||
/** Count main decisions, excluding automatic power and income responses. */
|
||||
export function ownMoveCount(engine: Engine, moves: string[], seat: number): number {
|
||||
return moves.filter((move) => moveBelongsToSeat(engine, move, seat)).length;
|
||||
return moves.filter(
|
||||
(move) => moveBelongsToSeat(engine, move, seat) && !/^\S+\s+(?:charge|decline|income|brainstone)\b/.test(move)
|
||||
).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the leading entries of a line that the player has since played FOR REAL (§3.5's own-move
|
||||
* row), so restoring a line you followed at the table continues it instead of reporting nothing.
|
||||
*
|
||||
* This is the whole reason "I made the same line in the real game, then got 0 moves restored" was
|
||||
* the common outcome: `replayAnalysisLine` starts from the top and stops at the first entry the
|
||||
* engine rejects, and after you play the line's first move for real that entry is exactly the one
|
||||
* that is now illegal (the mine is already on the hex). The more faithfully the line was followed,
|
||||
* the more certainly restoring it returned nothing - and, before this, wrote that nothing back over
|
||||
* the saved line.
|
||||
*
|
||||
* An entry is dropped only when BOTH tests agree, which is what keeps this from quietly editing a
|
||||
* line the player did not play:
|
||||
*
|
||||
* - It no longer applies to `origin` on its own. `origin` is the board AFTER the real moves, so a
|
||||
* move that has genuinely already happened cannot be played again; one that still applies is
|
||||
* still ahead of the player and is kept, even if the budget would have allowed dropping it.
|
||||
* - The budget is not spent. `budget` is how many real moves this seat has actually made since the
|
||||
* line was saved, so the line can never lose more entries than there were real moves to account
|
||||
* for them.
|
||||
*
|
||||
* Only a leading run of `move` entries is considered: an `adjust` or `faction` entry is sandbox
|
||||
* fiction with no real move behind it (`committableAnalysisMoves`), so nothing in the real history
|
||||
* can ever have been it, and the scan stops there rather than skipping past it.
|
||||
*/
|
||||
/** Compare actions, ignoring display annotations, coordinate aliases and the 3c price guard.
|
||||
* The guard changes when an upgrade may execute, not which upgrade was played. */
|
||||
function analysisMoveKey(engine: Engine, move: string): string {
|
||||
return JSON.stringify(
|
||||
parseCommands(move).map(({ command, args }) => {
|
||||
if (command === Command.Build) args = args.slice(0, 2);
|
||||
if (command === Command.Pass || command === Command.UpgradeResearch) args = args.slice(0, 1);
|
||||
return [
|
||||
command,
|
||||
...args.map((arg) =>
|
||||
arg
|
||||
.split(",")
|
||||
.map((token) => {
|
||||
if (!/^(?:-?\d+x-?\d+|\d+[AB]\d+|IS\d+|DS\d+_\d+)$/.test(token)) return token;
|
||||
try {
|
||||
const { q, r } = engine.map.parse(token);
|
||||
return `${q}x${r}`;
|
||||
} catch {
|
||||
return token;
|
||||
}
|
||||
})
|
||||
.join(",")
|
||||
),
|
||||
];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Trim only a matching prefix actually present in this seat's new real history.
|
||||
* A repeatable action (research, for example) is consumed once per real turn. An invalid
|
||||
* alternative is never mistaken for a played move. Assumed charges leading into a consumed
|
||||
* turn go with it, so they cannot be added again on top of the real board. */
|
||||
export function dropPlayedAnalysisPrefix(
|
||||
origin: Engine,
|
||||
engine: Engine,
|
||||
entries: AnalysisEntry[],
|
||||
seat: number,
|
||||
baseRound: number,
|
||||
budget: number
|
||||
playedMoves: string[]
|
||||
): { entries: AnalysisEntry[]; dropped: number } {
|
||||
let consumed = 0;
|
||||
let dropped = 0;
|
||||
while (dropped < budget && dropped < entries.length) {
|
||||
const entry = entries[dropped];
|
||||
if (entry.kind !== "move") {
|
||||
break;
|
||||
for (const move of playedMoves) {
|
||||
if (!moveBelongsToSeat(engine, move, seat)) continue;
|
||||
let next = consumed;
|
||||
while (entries[next]?.kind === "adjust") next++;
|
||||
const entry = entries[next];
|
||||
if (entry?.kind !== "move" || !moveBelongsToSeat(engine, entry.move, seat)) continue;
|
||||
if (analysisMoveKey(engine, entry.move) === analysisMoveKey(engine, move)) {
|
||||
consumed = next + 1;
|
||||
dropped++;
|
||||
}
|
||||
// Each surviving entry is tested against `origin` alone, not against the entries before it:
|
||||
// everything already dropped is baked into `origin` by virtue of having been played for real.
|
||||
if (replayAnalysisLine(origin, [entry], seat, baseRound).applied === 1) {
|
||||
break;
|
||||
}
|
||||
dropped++;
|
||||
}
|
||||
return { entries: dropped === 0 ? entries : entries.slice(dropped), dropped };
|
||||
return { entries: consumed ? entries.slice(consumed) : entries, dropped };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -852,18 +856,11 @@ export function dropPlayedAnalysisPrefix(
|
|||
*
|
||||
* `seat`'s player data is re-marked as the sandbox seat (`markAnalysisSeat`, §3.4/§12) after every
|
||||
* reconstruction, since the flag never survives the `JSON.parse(JSON.stringify(...))` round trip this
|
||||
* function (and every other clone in the analysis pipeline) relies on. That flag is now the whole
|
||||
* mechanism: with affordability lifted in the engine, the seat keeps its real resources and simply
|
||||
* goes negative, so there is no wallet to grant, carry between calls, or subtract back out - the
|
||||
* player board reads the true numbers straight off the replayed engine.
|
||||
* function (and every other clone in the analysis pipeline) relies on. Resource checks stay active:
|
||||
* an unaffordable entry stops replay at the last valid position, including for older saved drafts.
|
||||
*
|
||||
* The one thing that DOES have to be carried by hand across those clones is `analysisAssumedPower`:
|
||||
* it is a tally rather than a flag, and it is dropped by the same round trip, so without threading
|
||||
* it through each step the returned engine would only report whatever the LAST entry topped up
|
||||
* rather than what the line as a whole assumed.
|
||||
*
|
||||
* After each entry lands, opponent decisions are auto-resolved (§2.8) and the two-round cap's Pass
|
||||
* suppression (§3.7) is reapplied, since both depend on where the line has gotten to.
|
||||
* After each entry lands, opponent decisions are auto-resolved and solo turn order is restored,
|
||||
* including after income and other round transitions.
|
||||
*/
|
||||
export function replayAnalysisLine(
|
||||
origin: Engine,
|
||||
|
|
@ -879,14 +876,9 @@ export function replayAnalysisLine(
|
|||
seat,
|
||||
assumedPowerOf(origin, seat)
|
||||
);
|
||||
// Regenerate before anything reads them: `Engine.fromData` carries over the command list `origin`
|
||||
// was serialized with, and that list was built while affordability still applied to this seat. With
|
||||
// the flag now set, the same position offers strictly more (§12) - without this an empty line shows
|
||||
// the real game's buttons, so entering analysis mode appeared to change nothing until the first
|
||||
// move happened to regenerate them.
|
||||
// Recompute choices using this position's resources and explicit planning options.
|
||||
engine.clearAvailableCommands();
|
||||
engine.generateAvailableCommands();
|
||||
stripCappedPass(engine, baseRound);
|
||||
let applied = 0;
|
||||
for (const entry of entries) {
|
||||
const copy = markAnalysisSeat(
|
||||
|
|
@ -914,56 +906,28 @@ export function replayAnalysisLine(
|
|||
} catch {
|
||||
break;
|
||||
}
|
||||
resolveOpponentDecisions(copy, seat);
|
||||
// Finishing income/setup can enter a round with the real multiplayer turn order. Reapply the
|
||||
// solo turn order after resolving opponents, just as when entering or rebasing a preview.
|
||||
settleAnalysisClone(copy, seat);
|
||||
// Unconditional, and it has to come after the decisions above. `Engine.executeMove` nulls the
|
||||
// command list after every successful move, including the declines `resolveOpponentDecisions`
|
||||
// plays - and nothing downstream regenerates it, because `Commands.vue` reads
|
||||
// `engine.availableCommands` straight off the store. A null list renders as an empty command area
|
||||
// with only the Back button in it, which was the reported "I built inside leech range, the log
|
||||
// shows the opponents declining, and then I'm stuck": the declines had worked exactly as intended
|
||||
// and simply left the position with no commands generated for it. `stripCappedPass` below also
|
||||
// silently did nothing whenever this happened, for the same reason.
|
||||
// and simply left the position with no commands generated for it.
|
||||
copy.generateAvailableCommandsIfNeeded();
|
||||
stripCappedPass(copy, baseRound);
|
||||
engine = copy;
|
||||
applied++;
|
||||
}
|
||||
return { engine, applied };
|
||||
}
|
||||
|
||||
/** §6's queue cap: 1 move committed live plus `PremoveBar.vue`'s own 3-row queue limit - never
|
||||
* arbitrary, it's just what the existing premove machinery already allows. */
|
||||
export const MAX_COMMITTABLE_MOVES = 4;
|
||||
// Bound both previews and server submissions to three turns.
|
||||
export const MAX_COMMITTABLE_MOVES = 3;
|
||||
|
||||
/**
|
||||
* The commit path's affordability gate (§6, decision #13). Only "move" entries are ever committed -
|
||||
* an `adjust` entry is analysis-only fiction (§4.4), so it is stripped out of the line entirely
|
||||
* (not merely skipped-but-counted) before replaying, and consequently every move after one is only
|
||||
* committable if it is STILL affordable **without** the leech it assumed: this replays the
|
||||
* move-only entries completely fresh.
|
||||
*
|
||||
* Affordability is now simply "did any resource end up negative" (§12) - the sandbox no longer hands
|
||||
* the seat resources it does not have, so an overdrawn line is visible in the player data itself. The
|
||||
* returned prefix is cut at the first move that leaves the seat overdrawn, since a line that only
|
||||
* worked by overspending must never be committable, and separately at wherever the move-only replay
|
||||
* stops applying (`applied`, e.g. a move that depended on an adjust entry's power to even be legal).
|
||||
*
|
||||
* Two whole-line disqualifications come first, both specific to a setup-phase line:
|
||||
*
|
||||
* - **A faction seed (§11) voids the entire line for commit purposes.** Every move after one was
|
||||
* played on a table this seat only imagined - possibly as a faction it does not even hold - so
|
||||
* nothing in it describes a move the real game would accept.
|
||||
* - **Only this seat's own moves are committable.** Setup pass-and-play (§2.6/decision #7) puts
|
||||
* opponents' picks and mine placements in the line as ordinary entries, and committing one would
|
||||
* dispatch a move for somebody else's seat. Truncates at the first foreign move rather than
|
||||
* filtering them out, since committing move 3 without move 2 would not describe the same line.
|
||||
* The replayed engine (not `origin`) resolves the faction prefixes, because a setup line is
|
||||
* typically what assigned those factions in the first place.
|
||||
*
|
||||
* A power cost that had to be topped up (`analysisAssumedPower`, §12) also blocks the commit: the
|
||||
* move is only legal in the sandbox because power was assumed, so it is exactly as hypothetical as an
|
||||
* `adjust` entry.
|
||||
*/
|
||||
/** Moves that can be submitted now, replayed without simulated charges. Faction changes and
|
||||
* other players' moves cannot be submitted. The returned prefix stops at the first invalid move. */
|
||||
export function committableAnalysisMoves(
|
||||
origin: Engine,
|
||||
entries: AnalysisEntry[],
|
||||
|
|
@ -982,8 +946,6 @@ export function committableAnalysisMoves(
|
|||
export type AnalysisCommitCut =
|
||||
/** §11's faction seed: every move after it was played as a faction this seat may not even hold. */
|
||||
| "faction"
|
||||
/** The sandbox's cheap Trading Station - priced as if an opponent were adjacent when none is. */
|
||||
| "cheap-build"
|
||||
/** The move stopped applying at all once the line's `adjust` entries were stripped out. */
|
||||
| "illegal"
|
||||
/** The move left a resource below zero, i.e. it only worked because the sandbox lets you overspend. */
|
||||
|
|
@ -996,36 +958,39 @@ export type AnalysisCommitCut =
|
|||
| "cap";
|
||||
|
||||
/** The committable prefix plus the reason it ends there. See `committableAnalysisMoves` (the thin
|
||||
* wrapper above) for the full account of the rules; this is the same computation, reporting its cut. */
|
||||
* wrapper above) for the full account of the rules; this is the same computation, reporting its cut.
|
||||
* `affordableTurns` is 0 for future premoves, 1 when the first move plays now, or Infinity for offline
|
||||
* submission. Future turns may include explicitly simulated charges while checking the plan,
|
||||
* but those adjustments are never submitted. The server rechecks actual resources at execution. */
|
||||
export function analysisCommitPrefix(
|
||||
origin: Engine,
|
||||
entries: AnalysisEntry[],
|
||||
seat: number,
|
||||
baseRound: number
|
||||
baseRound: number,
|
||||
affordableTurns = Infinity
|
||||
): { moves: string[]; cut: AnalysisCommitCut | null } {
|
||||
if (entries.some((entry) => entry.kind === "faction")) {
|
||||
return { moves: [], cut: "faction" };
|
||||
}
|
||||
// The sandbox's cheap Trading Station (owner instruction, 2026-08-19) is a fiction in exactly the
|
||||
// way an `adjust` entry is: it prices a hex as if an opponent's structure were adjacent when none
|
||||
// is. A real game would charge the isolated price, so a line holding one describes moves it would
|
||||
// not accept - the whole line is out, not just that move, since everything after it was played on
|
||||
// credits the seat never had.
|
||||
if (entries.some((entry) => entry.kind === "move" && isCheapAnalysisBuild(entry.move))) {
|
||||
return { moves: [], cut: "cheap-build" };
|
||||
}
|
||||
const moveEntries = entries.filter((entry): entry is AnalysisMoveEntry => entry.kind === "move");
|
||||
if (moveEntries.length === 0) {
|
||||
return { moves: [], cut: null };
|
||||
}
|
||||
// Replay one move at a time so the cut lands on the first move that overdrew, rather than only
|
||||
// being able to say "somewhere in this line". Each pass restarts from `origin`, exactly as every
|
||||
// other replay in this file does.
|
||||
// A move played now must work without simulated charges. Future moves may use charges the
|
||||
// player explicitly simulated, while still obeying every cost in that simulated position.
|
||||
const replayPrefix = (count: number) => {
|
||||
const prefix =
|
||||
count <= affordableTurns
|
||||
? moveEntries.slice(0, count)
|
||||
: entries.slice(0, entries.indexOf(moveEntries[count - 1]) + 1);
|
||||
return replayAnalysisLine(origin, prefix, seat, baseRound);
|
||||
};
|
||||
let affordable = 0;
|
||||
let cut: AnalysisCommitCut | null = null;
|
||||
for (let count = 1; count <= moveEntries.length; count++) {
|
||||
const { engine, applied } = replayAnalysisLine(origin, moveEntries.slice(0, count), seat, baseRound);
|
||||
if (applied < count) {
|
||||
const { engine, applied } = replayPrefix(count);
|
||||
const expected = count <= affordableTurns ? count : entries.indexOf(moveEntries[count - 1]) + 1;
|
||||
if (applied < expected) {
|
||||
cut = "illegal";
|
||||
break;
|
||||
}
|
||||
|
|
@ -1035,14 +1000,28 @@ export function analysisCommitPrefix(
|
|||
break;
|
||||
}
|
||||
const status = computeAnalysisStatus(data);
|
||||
if (status.overdrawn.length > 0) {
|
||||
if (count <= affordableTurns && status.overdrawn.length > 0) {
|
||||
cut = "overdrawn";
|
||||
break;
|
||||
}
|
||||
if (status.assumedPower > 0) {
|
||||
if (count <= affordableTurns && status.assumedPower > 0) {
|
||||
cut = "assumed-power";
|
||||
break;
|
||||
}
|
||||
if (count <= affordableTurns && isCheapAnalysisBuild(moveEntries[count - 1].move)) {
|
||||
// A turn played now must already have the neighbour price. Future premoves retain the
|
||||
// qualifier and are checked on their actual turn, without granting a simulated discount.
|
||||
const real = Engine.fromData(JSON.parse(JSON.stringify(origin)));
|
||||
try {
|
||||
for (const entry of moveEntries.slice(0, count)) {
|
||||
real.forcePremovePreviewTurn(seat);
|
||||
real.move(entry.move);
|
||||
}
|
||||
} catch {
|
||||
cut = "illegal";
|
||||
break;
|
||||
}
|
||||
}
|
||||
affordable = count;
|
||||
if (count >= MAX_COMMITTABLE_MOVES) {
|
||||
cut = count < moveEntries.length ? "cap" : null;
|
||||
|
|
@ -1052,7 +1031,7 @@ export function analysisCommitPrefix(
|
|||
if (affordable === 0) {
|
||||
return { moves: [], cut };
|
||||
}
|
||||
const { engine } = replayAnalysisLine(origin, moveEntries.slice(0, affordable), seat, baseRound);
|
||||
const { engine } = replayPrefix(affordable);
|
||||
const ownCount = ownMovePrefixLength(engine, moveEntries, seat);
|
||||
const length = Math.min(affordable, ownCount, MAX_COMMITTABLE_MOVES);
|
||||
// A foreign move is the better explanation whenever it lands at or before wherever the replay
|
||||
|
|
@ -1067,12 +1046,9 @@ export function analysisCommitPrefix(
|
|||
};
|
||||
}
|
||||
|
||||
/** Whether `move` is a sandbox cheap-Trading-Station build (`... build ts 1x2 cheap`). Matched on the
|
||||
* qualifier rather than on the building token, so it stays correct if the qualifier is ever offered
|
||||
* for another building - as the last token of a turn, which is where `buildings.ts` appends it, and
|
||||
* which no ordinary build annotation (`build gf 6A9 using area1: 6.`) ever ends with. */
|
||||
/** A simulated neighbour becomes an explicit maximum-price constraint in a queued upgrade. */
|
||||
export function isCheapAnalysisBuild(move: string): boolean {
|
||||
return move.split(".").some((turn) => turn.trim().split(/\s+/).slice(-1)[0] === ANALYSIS_CHEAP_BUILD);
|
||||
return new RegExp(`\\bbuild\\s+\\S+\\s+\\S+\\s+${ANALYSIS_CHEAP_BUILD}(?=\\s*(?:\\.|$))`).test(move);
|
||||
}
|
||||
|
||||
/** How many of `moveEntries` from the start belong to `seat` - see `committableAnalysisMoves`' own
|
||||
|
|
@ -1088,6 +1064,10 @@ function ownMovePrefixLength(engine: Engine, moveEntries: AnalysisMoveEntry[], s
|
|||
* three things outside the line itself that bound a commit - whether the real game is waiting on
|
||||
* this seat, whether there is a premove queue at all, and how much room is left in it. */
|
||||
export interface AnalysisCommitPlan {
|
||||
/** Round and phase for each submitted move, in live-then-queued order. */
|
||||
timings?: PremoveTiming[];
|
||||
/** A submitted upgrade must keep the 3c neighbour price. */
|
||||
simulatedNeighbour?: boolean;
|
||||
/** Played for real immediately. `null` off turn, where there is no live move to play - see
|
||||
* `Game.vue`'s `commitAnalysisLine`. */
|
||||
live: string | null;
|
||||
|
|
@ -1103,7 +1083,7 @@ export interface AnalysisCommitPlan {
|
|||
}
|
||||
|
||||
/** §6/decision #13, made explicit so the player can read it before pressing anything. Applies the
|
||||
* two caps that live outside the line (`PremoveBar.vue`'s 3-row queue and hosted-only premoves) to
|
||||
* two caps that live outside the line (the three-move limit and hosted-only premoves) to
|
||||
* the committable prefix, and reports what is left behind either way. */
|
||||
export function planAnalysisCommit(args: {
|
||||
/** The committable prefix - `analysisCommitPrefix().moves`. */
|
||||
|
|
@ -1116,7 +1096,7 @@ export function planAnalysisCommit(args: {
|
|||
onTurn: boolean;
|
||||
/** Hosted play has a premove queue; self-contained/hot-seat does not. */
|
||||
hosted: boolean;
|
||||
/** Rows still free in this seat's premove queue (3 minus what is already queued). */
|
||||
/** Number of planned turns allowed after any move played immediately. The submitted plan replaces the queue. */
|
||||
queueRoom: number;
|
||||
}): AnalysisCommitPlan {
|
||||
const { committable, cut, lineMoves, onTurn, hosted, queueRoom } = args;
|
||||
|
|
@ -1129,6 +1109,7 @@ export function planAnalysisCommit(args: {
|
|||
return {
|
||||
live,
|
||||
queued,
|
||||
...(lineMoves.slice(0, allowed.length).some(isCheapAnalysisBuild) ? { simulatedNeighbour: true } : {}),
|
||||
dropped: lineMoves.slice(allowed.length),
|
||||
cut: limit === "line" ? cut : null,
|
||||
limit,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import Engine, {
|
|||
Command,
|
||||
Expansion,
|
||||
Faction,
|
||||
Phase,
|
||||
Planet,
|
||||
Player,
|
||||
Round,
|
||||
|
|
@ -31,14 +32,8 @@ function buildingMenu(building: Building, faction: Faction): { richText?: RichTe
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sandbox's pair of Trading Station buttons (owner instruction, 2026-08-19). Every build button
|
||||
* in this app is icon-only - the words live in the tooltip - which is fine when each icon is a
|
||||
* different building, and useless the moment two buttons carry the SAME Trading Station icon. So
|
||||
* whenever the sandbox twin exists, BOTH get a visible word on the button face: you pick "cheap" or
|
||||
* "expensive" by reading them, not by hovering. Outside sandbox mode there is no twin and the real
|
||||
* button keeps exactly the bare icon it has always had.
|
||||
*/
|
||||
/** Distinguish normal upgrades, which already include any neighbour discount, from a hypothetical
|
||||
* neighbour. The actual cost is shown for each mine when selecting where to upgrade. */
|
||||
function buildingLabel(
|
||||
bld: AvailableBuilding,
|
||||
faction: Faction,
|
||||
|
|
@ -48,8 +43,8 @@ function buildingLabel(
|
|||
const name = buildingName(building, faction);
|
||||
if (bld.analysisCheap) {
|
||||
return {
|
||||
label: `Cheap ${name} - sandbox only: 3c, as if an opponent's building were next door. A line holding one cannot be committed.`,
|
||||
richText: [richText("Cheap"), richTextBuilding(building, faction)],
|
||||
label: `Simulate a neighbour for this ${name}: preview the 3c price on an isolated mine. If queued, this upgrade only plays at 3c; otherwise the premoves stop.`,
|
||||
richText: [richText("Simulate neighbour"), richTextBuilding(building, faction)],
|
||||
};
|
||||
}
|
||||
let label = `Build a ${name}`;
|
||||
|
|
@ -63,8 +58,7 @@ function buildingLabel(
|
|||
// No `withShortcut` here: it exists to put the shortcut's underline into the label text, and
|
||||
// `symbolButton`'s own `tooltipWithShortcut` already does that from `button.shortcuts` - which
|
||||
// this button still carries, so `t` keeps working and the tooltip still marks it.
|
||||
label = `Expensive ${name} - the real price: 6c on a hex with no opponent's building next door`;
|
||||
rich.unshift(richText("Expensive"));
|
||||
label = `Upgrade to ${name}: 3c near an opponent's building, 6c otherwise. Select a mine to see its full cost.`;
|
||||
} else {
|
||||
label = withShortcut(`Upgrade to ${name}`, availableBuildingShortcut(bld, faction), ["Upgrade to"]);
|
||||
}
|
||||
|
|
@ -94,6 +88,13 @@ function buildingButton(
|
|||
commandSuffix?: string
|
||||
) {
|
||||
const hexes = hexMap(engine, buildings, false);
|
||||
if (engine.phase === Phase.SetupBuilding) {
|
||||
for (const target of hexes.hexes.values()) {
|
||||
if (isFree(target.cost)) {
|
||||
delete target.cost;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!upgrade && engine.round != Round.None && building != Building.SpaceStation) {
|
||||
const map = engine.map;
|
||||
for (const hex of map.grid.values()) {
|
||||
|
|
|
|||
|
|
@ -68,10 +68,12 @@ export function hexSelectionButton(
|
|||
label.push(richText(hex.toString()));
|
||||
}
|
||||
|
||||
// Lost Fleet Interspace/Deep Space addresses (IS3, DS14_1) don't carry a readable sector
|
||||
// reference like base-game coordinates do, so show which planet the button targets
|
||||
if (hex.data.planet !== Planet.Empty && classifySectorId(hex.data.sector) !== LostFleetSectorType.Space) {
|
||||
label.push(richTextPlanet(hex.data.planet), richText(planetNames[hex.data.planet]));
|
||||
// Identify Lost Fleet destinations by their planet icon; keep the full name in the tooltip
|
||||
// instead of repeating it in every button of the mobile action bar.
|
||||
const showPlanet =
|
||||
hex.data.planet !== Planet.Empty && classifySectorId(hex.data.sector) !== LostFleetSectorType.Space;
|
||||
if (showPlanet) {
|
||||
label.push(richTextPlanet(hex.data.planet));
|
||||
}
|
||||
|
||||
const highlightHex = hexes.get(hex);
|
||||
|
|
@ -96,7 +98,7 @@ export function hexSelectionButton(
|
|||
}
|
||||
|
||||
b.warning = buttonWarnings(highlightHex.warnings);
|
||||
b.tooltip = tooltipWithShortcut(null, b.warning);
|
||||
b.tooltip = tooltipWithShortcut(showPlanet ? `${hex}: ${planetNames[hex.data.planet]}` : null, b.warning);
|
||||
|
||||
b.hover = {
|
||||
enter: () => {
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ export function autoLeechRiskWarning(
|
|||
const capText = cap > 0 ? `, capped at ${cap} total power after passing` : "";
|
||||
return {
|
||||
disableKey: WarningKey.autoLeechVpRisk,
|
||||
message: `Auto-leech is set to accept leeches up to ${threshold} power${capText}, which can cost Victory Points - other players still have turns this round, so this could happen before you act again.`,
|
||||
message: `Auto-charge is set to accept charges up to ${threshold} power${capText}, which can cost Victory Points - other players still have turns this round, so this could happen before you act again.`,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,10 +4,7 @@ import type { ButtonData } from "../../data";
|
|||
import { buildButtons } from "./buildings";
|
||||
import type { CommandController } from "./types";
|
||||
|
||||
// The sandbox's two Trading Station buttons (owner instruction, 2026-08-19). Every build button in
|
||||
// this app is icon-only, with the words in the tooltip - which stops working the moment two buttons
|
||||
// carry the same Trading Station icon, so the pair has to be readable on the button face itself.
|
||||
describe("the sandbox's cheap/expensive Trading Station pair", () => {
|
||||
describe("normal Trading Stations and simulated neighbours", () => {
|
||||
const SETUP = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
|
|
@ -81,15 +78,22 @@ describe("the sandbox's cheap/expensive Trading Station pair", () => {
|
|||
const buttons = tradingStationButtons(true);
|
||||
|
||||
expect(buttons).to.have.length(2);
|
||||
expect(buttons.map(faceText)).to.deep.equal(["Expensive", "Cheap"]);
|
||||
expect(buttons.map(faceText)).to.deep.equal(["", "Simulate neighbour"]);
|
||||
});
|
||||
|
||||
it("says which price each one charges, and that the cheap one is a sandbox fiction", () => {
|
||||
const [expensive, cheap] = tradingStationButtons(true);
|
||||
it("keeps both actual prices under the normal upgrade and reserves simulation for isolated mines", () => {
|
||||
const [normal, simulated] = tradingStationButtons(true);
|
||||
|
||||
expect(expensive.label).to.contain("6c");
|
||||
expect(cheap.label).to.contain("3c");
|
||||
expect(cheap.label).to.contain("cannot be committed");
|
||||
expect(normal.label).to.contain("3c");
|
||||
expect(normal.label).to.contain("6c");
|
||||
expect(simulated.label).to.contain("only plays at 3c");
|
||||
const normalCosts = Array.from(normal.hexes.hexes.values()).map((hex) => hex.cost);
|
||||
expect(normalCosts).to.include("3c,2o");
|
||||
expect(normalCosts).to.include("6c,2o");
|
||||
for (const [hex, simulatedCost] of simulated.hexes.hexes) {
|
||||
expect(normal.hexes.hexes.get(hex).cost).to.equal("6c,2o");
|
||||
expect(simulatedCost.cost).to.equal("3c,2o");
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the shortcut on the real one only, since nothing here resolves a collision", () => {
|
||||
|
|
|
|||
|
|
@ -151,14 +151,14 @@ export function balanceSheetEventSources(expansion: Expansion): BalanceSheetSour
|
|||
color: "--specialAction",
|
||||
},
|
||||
{
|
||||
label: "Free Leech",
|
||||
label: "Free Charge",
|
||||
incomeResources: [Resource.ChargePower, Resource.GainToken],
|
||||
costResources: [],
|
||||
eventSources: [PowerChargeSource.freeLeech],
|
||||
color: "--res-power",
|
||||
},
|
||||
{
|
||||
label: "Paid Leech",
|
||||
label: "Paid Charge",
|
||||
incomeResources: [Resource.ChargePower, Resource.GainToken],
|
||||
costResources: [],
|
||||
eventSources: [PowerChargeSource.paidLeech],
|
||||
|
|
|
|||
|
|
@ -19,49 +19,49 @@ enum LeechSource {
|
|||
const leechSources: ChartSource<LeechSource>[] = [
|
||||
{
|
||||
type: LeechSource.leech1,
|
||||
label: "Leech 1 (free)",
|
||||
label: "Charge 1 (free)",
|
||||
color: "--rt-terra",
|
||||
weight: 1,
|
||||
},
|
||||
{
|
||||
type: LeechSource.leech2,
|
||||
label: "Leech 2 (1 VP)",
|
||||
label: "Charge 2 (1 VP)",
|
||||
color: "--rt-nav",
|
||||
weight: 1,
|
||||
},
|
||||
{
|
||||
type: LeechSource.leech3,
|
||||
label: "Leech 3 (2 VP)",
|
||||
label: "Charge 3 (2 VP)",
|
||||
color: "--rt-int",
|
||||
weight: 1,
|
||||
},
|
||||
{
|
||||
type: LeechSource.leech4,
|
||||
label: "Leech 4 (3 VP)",
|
||||
label: "Charge 4 (3 VP)",
|
||||
color: "--rt-gaia",
|
||||
weight: 1,
|
||||
},
|
||||
{
|
||||
type: LeechSource.leech5,
|
||||
label: "Leech 5 (4 VP)",
|
||||
label: "Charge 5 (4 VP)",
|
||||
color: "--rt-eco",
|
||||
weight: 1,
|
||||
},
|
||||
{
|
||||
type: LeechSource.Declined,
|
||||
label: "Declined Leech",
|
||||
label: "Declined Charge",
|
||||
color: "--lost",
|
||||
weight: 0,
|
||||
},
|
||||
{
|
||||
type: LeechSource.MissedVp,
|
||||
label: "Missed Leech (lack of VP)",
|
||||
label: "Missed Charge (lack of VP)",
|
||||
color: "--rt-sci",
|
||||
weight: 0,
|
||||
},
|
||||
{
|
||||
type: LeechSource.MissedCharge,
|
||||
label: "Missed Leech (lack of tokens)",
|
||||
label: "Missed Charge (lack of tokens)",
|
||||
color: "--tech-tile",
|
||||
weight: 0,
|
||||
},
|
||||
|
|
@ -116,8 +116,8 @@ export const terranChargeExtractLog: (sourceType: any) => ExtractLogEntry<any> =
|
|||
});
|
||||
|
||||
export const leechSourceFactory: SimpleSourceFactory<ChartSource<LeechSource>> = {
|
||||
name: "Power Leech",
|
||||
playerSummaryLineChartTitle: "Power Leech of all players",
|
||||
name: "Power Charge",
|
||||
playerSummaryLineChartTitle: "Power Charge of all players",
|
||||
summary: ChartSummary.weightedTotal,
|
||||
extractChange: powerChargeDetails(),
|
||||
extractLog: ExtractLog.mux([
|
||||
|
|
|
|||
|
|
@ -26,14 +26,14 @@
|
|||
}
|
||||
},
|
||||
"labels": [
|
||||
"Leech 1 (free)",
|
||||
"Leech 2 (1 VP)",
|
||||
"Leech 3 (2 VP)",
|
||||
"Leech 4 (3 VP)",
|
||||
"Leech 5 (4 VP)",
|
||||
"Declined Leech",
|
||||
"Missed Leech (lack of VP)",
|
||||
"Missed Leech (lack of tokens)"
|
||||
"Charge 1 (free)",
|
||||
"Charge 2 (1 VP)",
|
||||
"Charge 3 (2 VP)",
|
||||
"Charge 4 (3 VP)",
|
||||
"Charge 5 (4 VP)",
|
||||
"Declined Charge",
|
||||
"Missed Charge (lack of VP)",
|
||||
"Missed Charge (lack of tokens)"
|
||||
],
|
||||
"datasets": [
|
||||
{
|
||||
|
|
@ -48,8 +48,8 @@
|
|||
"Tech Tiles income",
|
||||
"Research income",
|
||||
"Booster income",
|
||||
"Free Leech income",
|
||||
"Paid Leech income",
|
||||
"Free Charge income",
|
||||
"Paid Charge income",
|
||||
"Powerful Power Tokens income",
|
||||
"Terrans income",
|
||||
"Free actions cost",
|
||||
|
|
|
|||
|
|
@ -49,8 +49,8 @@
|
|||
"Booster income",
|
||||
"Free actions income",
|
||||
"Power/Q.I.C Actions income",
|
||||
"Free Leech income",
|
||||
"Paid Leech income",
|
||||
"Free Charge income",
|
||||
"Paid Charge income",
|
||||
"Federations income",
|
||||
"Free actions cost",
|
||||
"Federations cost",
|
||||
|
|
|
|||
|
|
@ -26,14 +26,14 @@
|
|||
}
|
||||
},
|
||||
"labels": [
|
||||
"Leech 1 (free)",
|
||||
"Leech 2 (1 VP)",
|
||||
"Leech 3 (2 VP)",
|
||||
"Leech 4 (3 VP)",
|
||||
"Leech 5 (4 VP)",
|
||||
"Declined Leech",
|
||||
"Missed Leech (lack of VP)",
|
||||
"Missed Leech (lack of tokens)"
|
||||
"Charge 1 (free)",
|
||||
"Charge 2 (1 VP)",
|
||||
"Charge 3 (2 VP)",
|
||||
"Charge 4 (3 VP)",
|
||||
"Charge 5 (4 VP)",
|
||||
"Declined Charge",
|
||||
"Missed Charge (lack of VP)",
|
||||
"Missed Charge (lack of tokens)"
|
||||
],
|
||||
"datasets": [
|
||||
{
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"types": ["Federations", "Power Leech"],
|
||||
"types": ["Federations", "Power Charge"],
|
||||
"options": {
|
||||
"layout": "standard"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -36,8 +36,8 @@
|
|||
"Tech Tiles income",
|
||||
"Research income",
|
||||
"Booster income",
|
||||
"Free Leech income",
|
||||
"Paid Leech income",
|
||||
"Free Charge income",
|
||||
"Paid Charge income",
|
||||
"Powerful Power Tokens income",
|
||||
"Terrans income",
|
||||
"Free actions cost",
|
||||
|
|
|
|||
|
|
@ -48,8 +48,8 @@
|
|||
"Tech Tiles income",
|
||||
"Research income",
|
||||
"Booster income",
|
||||
"Free Leech income",
|
||||
"Paid Leech income",
|
||||
"Free Charge income",
|
||||
"Paid Charge income",
|
||||
"Powerful Power Tokens income",
|
||||
"Terrans income",
|
||||
"Free actions cost",
|
||||
|
|
|
|||
|
|
@ -26,14 +26,14 @@
|
|||
}
|
||||
},
|
||||
"labels": [
|
||||
"Leech 1 (free)",
|
||||
"Leech 2 (1 VP)",
|
||||
"Leech 3 (2 VP)",
|
||||
"Leech 4 (3 VP)",
|
||||
"Leech 5 (4 VP)",
|
||||
"Declined Leech",
|
||||
"Missed Leech (lack of VP)",
|
||||
"Missed Leech (lack of tokens)"
|
||||
"Charge 1 (free)",
|
||||
"Charge 2 (1 VP)",
|
||||
"Charge 3 (2 VP)",
|
||||
"Charge 4 (3 VP)",
|
||||
"Charge 5 (4 VP)",
|
||||
"Declined Charge",
|
||||
"Missed Charge (lack of VP)",
|
||||
"Missed Charge (lack of tokens)"
|
||||
],
|
||||
"datasets": [
|
||||
{
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"legacyIvitsStartingPower": true,
|
||||
"types": ["Power Leech"],
|
||||
"types": ["Power Charge"],
|
||||
"options": {
|
||||
"advancedRules": true,
|
||||
"layout": "standard",
|
||||
|
|
|
|||
|
|
@ -48,8 +48,8 @@
|
|||
"Tech Tiles income",
|
||||
"Research income",
|
||||
"Booster income",
|
||||
"Free Leech income",
|
||||
"Paid Leech income",
|
||||
"Free Charge income",
|
||||
"Paid Charge income",
|
||||
"Powerful Power Tokens income",
|
||||
"Terrans income",
|
||||
"Free actions cost",
|
||||
|
|
|
|||
|
|
@ -1,108 +1,5 @@
|
|||
// Row shapes for a hosted multiplayer backend (premove/sealed-bid/game-row shapes used by game
|
||||
// components and the store).
|
||||
|
||||
import type { SealedBidVariant } from "./sealed-bid";
|
||||
|
||||
export type GameRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
seed: string;
|
||||
player_count: number;
|
||||
options: Record<string, unknown>;
|
||||
status: "open" | "active" | "finished";
|
||||
current_seat: number | null;
|
||||
starting_seat?: number;
|
||||
setup_move?: string | null;
|
||||
move_count: number;
|
||||
// Cached lobby-list display data - null until this game's first post-migration commit (see the
|
||||
// migration's own doc comment). Never read by game logic, only the Lobby row.
|
||||
current_round: number | null;
|
||||
latest_move_summary: string | null;
|
||||
// Cached lobby-list "time since last move" (migration 0026) - avoids an unbounded cross-game
|
||||
// moves query that silently hit PostgREST's row cap once this project passed ~1000 total moves.
|
||||
latest_move_committed_at?: string | null;
|
||||
abandoned_at?: string | null;
|
||||
};
|
||||
|
||||
export type PlayerRow = {
|
||||
game_id: string;
|
||||
seat: number;
|
||||
invited_email: string;
|
||||
user_id: string | null;
|
||||
display_name: string;
|
||||
faction: string | null;
|
||||
score: number | null;
|
||||
/** Refreshed every ~20s while a tab for this seat is open - used as a "seen recently" presence
|
||||
* fallback when there's no live presence entry. Optional so existing test fixtures that predate
|
||||
* this field don't all need updating. */
|
||||
last_active_at?: string | null;
|
||||
};
|
||||
|
||||
export type MoveRow = {
|
||||
game_id: string;
|
||||
seq: number;
|
||||
seat: number;
|
||||
move: string;
|
||||
};
|
||||
|
||||
export type PlayerUpdate = { seat: number; faction: string; score: number };
|
||||
|
||||
export type CommitTurnArgs = {
|
||||
gameId: string;
|
||||
seq: number;
|
||||
seat: number;
|
||||
move: string;
|
||||
nextSeat: number | null;
|
||||
finished: boolean;
|
||||
/** Freshly-computed from the local engine at commit time (see host.ts) - cached lobby display
|
||||
* data only, see GameRow/PlayerRow's current_round/faction/score. */
|
||||
currentRound: number;
|
||||
latestMoveSummary: string | null;
|
||||
playerUpdates: PlayerUpdate[];
|
||||
};
|
||||
|
||||
// Premove (PREMOVE_PLAN.md, Phase 1) - RLS already scopes selects to the caller's own seats, so
|
||||
// fetches don't take a seat filter; queue/cancel take an explicit seat since a multi-seat owner is
|
||||
// never ambiguous (see the RPCs in 0010_premoves.sql).
|
||||
// Phase 3 (§10.1-10.4) added `mode` - all of a seat's rows share one mode; `seq` means turn-order in
|
||||
// sequential mode, priority-rank in priority mode.
|
||||
export type PremoveMode = "sequential" | "priority";
|
||||
export type PremoveRow = { seat: number; seq: number; move: string; mode: PremoveMode; queued_move_count: number };
|
||||
export type PremoveFailureRow = {
|
||||
id: string;
|
||||
seat: number;
|
||||
move: string;
|
||||
reason: string;
|
||||
read_at: string | null;
|
||||
// 'cancelled' (added for premove cancel triggers) reads differently in the UI ("cancelled by
|
||||
// trigger" rather than "your premove couldn't be played") - see PremoveBar/Game.vue.
|
||||
kind: "failure" | "cancelled";
|
||||
};
|
||||
|
||||
// Premove cancel triggers - a trigger watches one opponent's moves (kind='move') or the owner's
|
||||
// own power charges (kind='leech') and, if it matches, clears the owner's entire premove queue
|
||||
// instead of ever playing anything. The shared matcher (logic/premove-cancel-trigger.ts) uses its
|
||||
// own camelCase CancelTriggerRow shape instead - callers adapt between the two.
|
||||
export type CancelTriggerKind = "move" | "leech";
|
||||
export type CancelTriggerLeechConfig = { mode: "gained" | "offered"; minPower: number };
|
||||
export type CancelTriggerRow = {
|
||||
seat: number;
|
||||
seq: number;
|
||||
kind: CancelTriggerKind;
|
||||
watched_seat: number;
|
||||
move: string;
|
||||
atoms: string[];
|
||||
config: CancelTriggerLeechConfig | Record<string, never>;
|
||||
match: "any" | "all";
|
||||
armed_from_move_count: number;
|
||||
};
|
||||
|
||||
// The sealed-bid side channel, shared by both simultaneous-bid auction variants: the Preference
|
||||
// Split (AuctionVariant.PreferenceSplit) and the Silent Auction (AuctionVariant.Silent, migration
|
||||
// 20260812130000). Bids do NOT go through commitTurn while the auction is open: they are held
|
||||
// server-side (auction_sealed_bids, migration 20260805120000) where RLS shows a player only their
|
||||
// own row, and become one ordinary move per seat in one transaction once everybody has submitted.
|
||||
// See that migration's header for why the ordinary move log cannot be used here.
|
||||
export type SealedBidEntry = { faction: string; points: number };
|
||||
export type SealedBidStatus = {
|
||||
playerCount: number;
|
||||
|
|
@ -117,97 +14,3 @@ export type SealedBidStatus = {
|
|||
};
|
||||
|
||||
// The data layer a hosted game backend needs to provide.
|
||||
export interface HostedBackend {
|
||||
fetchGame(gameId: string): Promise<GameRow>;
|
||||
fetchPlayers(gameId: string): Promise<PlayerRow[]>;
|
||||
fetchMoves(gameId: string): Promise<MoveRow[]>;
|
||||
claimMySeats(): Promise<void>;
|
||||
repairMoveCount(gameId: string): Promise<number>;
|
||||
commitTurn(args: CommitTurnArgs): Promise<void>;
|
||||
fetchPremoves(gameId: string): Promise<PremoveRow[]>;
|
||||
fetchPremoveFailures(gameId: string): Promise<PremoveFailureRow[]>;
|
||||
queuePremove(gameId: string, seat: number, move: string, mode: PremoveMode): Promise<number>;
|
||||
cancelPremove(gameId: string, seat: number, seq: number): Promise<void>;
|
||||
// Premove UI redesign (Gaia 9) - updates a queued premove's move in place (Sequential also
|
||||
// cascade-deletes everything after it, same as a cancel there - see the migration).
|
||||
editPremove(gameId: string, seat: number, seq: number, move: string): Promise<void>;
|
||||
// Phase 3 (§10.4) - clears a seat's whole queue in one call: the mode-toggle confirm, and the
|
||||
// §10.7 reconciliation cases.
|
||||
cancelAllPremoves(gameId: string, seat: number): Promise<void>;
|
||||
// Phase 3, priority mode only - swaps a row's rank with its neighbour.
|
||||
reorderPremove(gameId: string, seat: number, seq: number, direction: "up" | "down"): Promise<void>;
|
||||
markPremoveFailureRead(id: string): Promise<void>;
|
||||
// Phase 2 (offline auto-leech) - persists the client's existing auto-charge preference per seat
|
||||
// so resolve-automation can honor it while the player is offline.
|
||||
setAutoCharge(gameId: string, seat: number, pref: string): Promise<void>;
|
||||
/** Preference Split Auction: submission progress. Safe to call from any seat at any time. */
|
||||
fetchSealedBidStatus(gameId: string): Promise<SealedBidStatus>;
|
||||
/** Announces the open bid phase, so every player who still owes a bid gets a push. Server-side
|
||||
* exactly-once (migration 20260808120000); returns whether THIS call was the one that announced,
|
||||
* so every client can call it unconditionally while sitting in the phase. */
|
||||
announceSealedBidAuction(gameId: string): Promise<boolean>;
|
||||
/** Submits one seat's whole split. Returns how many seats have submitted afterwards. */
|
||||
submitSealedBid(gameId: string, seat: number, bids: SealedBidEntry[]): Promise<number>;
|
||||
/** Every seat's submitted split. RLS only ever returns rows once all of them are in (before that
|
||||
* it returns just the caller's own), so this is safe to call and useless to call early. */
|
||||
fetchSealedBids(gameId: string): Promise<{ seat: number; bids: SealedBidEntry[] }[]>;
|
||||
/** Appends every sealed bid to the move log at once. Returns the number of moves appended, or 0
|
||||
* if another client had already done it. Throws `seq_conflict` when this client was racing one. */
|
||||
revealSealedBids(gameId: string, seq: number, nextSeat: number): Promise<number>;
|
||||
// Premove cancel triggers - RLS scopes selects to the caller's own seats, same as premoves.
|
||||
fetchCancelTriggers(gameId: string): Promise<CancelTriggerRow[]>;
|
||||
armCancelTrigger(
|
||||
gameId: string,
|
||||
seat: number,
|
||||
watchedSeat: number,
|
||||
move: string,
|
||||
atoms: string[],
|
||||
kind: CancelTriggerKind,
|
||||
config: CancelTriggerLeechConfig | Record<string, never>
|
||||
): Promise<number>;
|
||||
disarmCancelTrigger(gameId: string, seat: number, seq: number): Promise<void>;
|
||||
disarmAllCancelTriggers(gameId: string, seat: number): Promise<void>;
|
||||
editCancelTrigger(
|
||||
gameId: string,
|
||||
seat: number,
|
||||
seq: number,
|
||||
move: string,
|
||||
atoms: string[],
|
||||
config: CancelTriggerLeechConfig | Record<string, never>
|
||||
): Promise<void>;
|
||||
/** The atomic "a match just fired" step (migration 20260815090000's own doc comment explains the
|
||||
* race it closes). Returns whether THIS call is the one that actually applied the cancellation -
|
||||
* false means another evaluator (another tab's fast-path, or the offline edge function) already
|
||||
* got there first, so the caller does nothing further (no toast, no second notice). */
|
||||
resolveCancelTriggerMatch(gameId: string, seat: number, reason: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
export type HostedCallbacks = {
|
||||
/** Serialized engine JSON, ready for the launcher's "state" event. */
|
||||
onState: (engineData: unknown) => void;
|
||||
/**
|
||||
* The same serialized engine JSON as `onState`, but only for a COMMITTED state - a completed turn
|
||||
* (local or remote), a load, or a resync - never a half-composed turn being previewed while the
|
||||
* player clicks through it. For consumers that persist or export the game rather than render it
|
||||
* (e.g. an offline mirror copy). Fires per state, not per move: a resync that lands several
|
||||
* turns at once fires once.
|
||||
*/
|
||||
onCommittedState?: (engineData: any) => void;
|
||||
onError?: (message: string) => void;
|
||||
/** Refetched on load and whenever a moves row arrives (PREMOVE_PLAN.md §3's refresh rule). */
|
||||
onPremoveState?: (premoves: PremoveRow[], failures: PremoveFailureRow[]) => void;
|
||||
/** Preference Split Auction: submission progress while the bid phase is open. Progress only -
|
||||
* never anybody's points, which is the whole point of the sealed table. */
|
||||
onSealedBidState?: (status: SealedBidStatus) => void;
|
||||
/** Phase 3 (§10.6) - fired whenever a queued premove is the thing that just played (fast-path
|
||||
* success only - the offline edge function's own plays are noticed the same way on the next
|
||||
* refresh, since the consumed row simply vanished). Quiet, in-app only: a log tag / subtle toast,
|
||||
* never a push (successes don't push - only failures do, via the existing premove_failures infra). */
|
||||
onPremovePlayed?: (seat: number, move: string, info: { rank?: number; totalRanks?: number }) => void;
|
||||
/** Refetched alongside premoves/failures (same refresh points). */
|
||||
onCancelTriggerState?: (triggers: CancelTriggerRow[]) => void;
|
||||
/** Fired when THIS session's fast-path is the one that actually applied a cancel-trigger match
|
||||
* (resolveCancelTriggerMatch returned true) - the toast (§8.5). The offline edge function's own
|
||||
* matches are noticed the same way any premove_failures row is: via onPremoveState. */
|
||||
onCancelTriggerFired?: (seat: number, reason: string) => void;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,251 +0,0 @@
|
|||
import Engine from "@gaia-project/engine";
|
||||
import { expect } from "chai";
|
||||
import type { CancelTriggerRow, LeechConfig, SeatedMove } from "./premove-cancel-trigger";
|
||||
import { candidateAtoms, matchCancelTriggers, moveAtoms } from "./premove-cancel-trigger";
|
||||
|
||||
// An identity map: hex args round-trip unchanged. Good enough for every test that isn't
|
||||
// specifically exercising hex-notation canonicalization (that group builds a real engine map
|
||||
// instead, since the module intentionally has no engine dependency of its own to fake one with).
|
||||
const identityMap = { getS: (coords: string) => ({ toString: () => coords }) };
|
||||
|
||||
function trigger(overrides: Partial<CancelTriggerRow>): CancelTriggerRow {
|
||||
return {
|
||||
seq: 1,
|
||||
kind: "move",
|
||||
watchedSeat: 1,
|
||||
move: "",
|
||||
atoms: [],
|
||||
config: {},
|
||||
match: "any",
|
||||
armedFromMoveCount: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function seated(seq: number, seat: number, move: string): SeatedMove {
|
||||
return { seq, seat, move };
|
||||
}
|
||||
|
||||
describe("moveAtoms", () => {
|
||||
it("normalizes a full move line into one atom per command", () => {
|
||||
expect(moveAtoms("firaks build lab 7A6. tech eco. up eco", identityMap)).to.deep.equal([
|
||||
"build:lab:7A6",
|
||||
"tech:eco",
|
||||
"up:eco",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does NOT drop plumbing commands - an actual move is normalized in full", () => {
|
||||
const atoms = moveAtoms("xenos burn 2. spend 2pw for 1o. build m 3A4.", identityMap);
|
||||
expect(atoms).to.include("burn:2");
|
||||
expect(atoms).to.include("build:m:3A4");
|
||||
// "spend 2pw for 1o" - the "for" token is dropped by the underlying command/arg split the same
|
||||
// way parseCommands treats it (args are whitespace-split, "for"/"1o" both become plain args).
|
||||
expect(atoms.some((a) => a.startsWith("spend:"))).to.equal(true);
|
||||
});
|
||||
|
||||
it("the three real up-eco routes all produce an up:eco atom (§2.2's verified fact)", () => {
|
||||
const techTile = moveAtoms("firaks build lab 7A6. tech eco. up eco", identityMap);
|
||||
const freeTile = moveAtoms("firaks build lab 7A6. tech free2. up eco", identityMap);
|
||||
const special = moveAtoms("bescods special up-lowest. up eco", identityMap);
|
||||
expect(techTile).to.include("up:eco");
|
||||
expect(freeTile).to.include("up:eco");
|
||||
expect(special).to.include("up:eco");
|
||||
});
|
||||
|
||||
it("lowercases non-hex args and strips a trailing dot", () => {
|
||||
expect(moveAtoms("terrans pass Booster3.", identityMap)).to.deep.equal(["pass:booster3"]);
|
||||
});
|
||||
|
||||
it("canonicalizes a FormFederation hex list by sorting its members", () => {
|
||||
const a = moveAtoms("ivits federation 3A4,1A2 fed3", identityMap);
|
||||
const b = moveAtoms("ivits federation 1A2,3A4 fed3", identityMap);
|
||||
expect(a).to.deep.equal(b);
|
||||
expect(a).to.deep.equal(["federation:1A2,3A4:fed3"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("candidateAtoms", () => {
|
||||
it("drops plumbing commands from the composer's candidates", () => {
|
||||
const candidates = candidateAtoms("xenos burn 2. spend 2pw for 1o. build m 3A4.", identityMap);
|
||||
expect(candidates.map((c) => c.exact)).to.deep.equal(["build:m:3A4"]);
|
||||
});
|
||||
|
||||
it("drops every command on the DROP list, keeps everything else, including unknown commands", () => {
|
||||
const candidates = candidateAtoms(
|
||||
"terrans charge 2pw. decline 3pw. income. endturn. brainstone. up eco. mystery 1 2",
|
||||
identityMap
|
||||
);
|
||||
expect(candidates.map((c) => c.exact)).to.deep.equal(["up:eco", "mystery:1:2"]);
|
||||
});
|
||||
|
||||
it("offers a loose (*) form for build that keeps the building type and drops the hex", () => {
|
||||
const [candidate] = candidateAtoms("terrans build lab 7A6.", identityMap);
|
||||
expect(candidate).to.deep.equal({ exact: "build:lab:7A6", any: "build:lab:*", label: candidate.label });
|
||||
});
|
||||
|
||||
it("offers a fully-collapsing loose form for up/tech/action/special/pass/federation", () => {
|
||||
expect(candidateAtoms("terrans up eco", identityMap)[0].any).to.equal("up:*");
|
||||
expect(candidateAtoms("terrans tech eco", identityMap)[0].any).to.equal("tech:*");
|
||||
expect(candidateAtoms("terrans action power3", identityMap)[0].any).to.equal("action:*");
|
||||
expect(candidateAtoms("terrans special up-lowest", identityMap)[0].any).to.equal("special:*");
|
||||
expect(candidateAtoms("terrans pass booster3", identityMap)[0].any).to.equal("pass:*");
|
||||
expect(candidateAtoms("ivits federation 3A4 fed3", identityMap)[0].any).to.equal("federation:*");
|
||||
});
|
||||
|
||||
it("offers no loose form for a command outside the §2.4 table", () => {
|
||||
expect(candidateAtoms("terrans mystery 1 2", identityMap)[0].any).to.equal(null);
|
||||
});
|
||||
|
||||
it("dedupes identical atoms, keeping first-seen order", () => {
|
||||
const candidates = candidateAtoms("terrans build m 3A4. build m 3A4.", identityMap);
|
||||
expect(candidates.length).to.equal(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hex notation equivalence (real engine map)", () => {
|
||||
it("a regular hex's cube and sector-relative notations produce the same atom", () => {
|
||||
const engine = new Engine(["init 2 randomSeed"]);
|
||||
const [hex] = [...(engine.map as any).grid.values()];
|
||||
const cube = `${hex.q}x${hex.r}`;
|
||||
const relative = hex.toString();
|
||||
expect(moveAtoms(`terrans build m ${cube}.`, engine.map)).to.deep.equal(
|
||||
moveAtoms(`terrans build m ${relative}.`, engine.map)
|
||||
);
|
||||
});
|
||||
|
||||
it("a Lost Fleet Interspace/Deep Space hex's cube and canonical (IS.../DS...) notations agree", () => {
|
||||
const engine = new Engine(["init 2 randomSeed"], { lostFleet: true });
|
||||
const hexes = [...(engine.map as any).grid.values()] as any[];
|
||||
const special = hexes.find((h) => /^(IS|DS)/.test(h.toString()));
|
||||
if (!special) {
|
||||
// Some seeds/configurations may not place any - nothing to assert against, so skip rather
|
||||
// than fail on an environment-dependent absence.
|
||||
return;
|
||||
}
|
||||
const cube = `${special.q}x${special.r}`;
|
||||
expect(moveAtoms(`terrans build m ${cube}.`, engine.map)).to.deep.equal(
|
||||
moveAtoms(`terrans build m ${special.toString()}.`, engine.map)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchCancelTriggers - move kind", () => {
|
||||
it("matches an exact stored atom against the same actual atom", () => {
|
||||
const triggers = [trigger({ atoms: ["build:m:3A4"] })];
|
||||
const moves = [seated(1, 1, "xenos build m 3A4.")];
|
||||
const result = matchCancelTriggers(triggers, moves, identityMap);
|
||||
expect(result?.atom).to.equal("build:m:3A4");
|
||||
expect(result?.matchedMove.seq).to.equal(1);
|
||||
});
|
||||
|
||||
it("does not match a different hex under an exact atom", () => {
|
||||
const triggers = [trigger({ atoms: ["build:m:3A4"] })];
|
||||
const moves = [seated(1, 1, "xenos build m 9B2.")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)).to.equal(null);
|
||||
});
|
||||
|
||||
it("a loose (*) stored atom matches any hex", () => {
|
||||
const triggers = [trigger({ atoms: ["build:m:*"] })];
|
||||
const moves = [seated(1, 1, "xenos build m 9B2.")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)?.atom).to.equal("build:m:9B2");
|
||||
});
|
||||
|
||||
it("build:m:* does not match build:lab:* - the loose form still pins the building type", () => {
|
||||
const triggers = [trigger({ atoms: ["build:m:*"] })];
|
||||
const moves = [seated(1, 1, "xenos build lab 9B2.")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)).to.equal(null);
|
||||
});
|
||||
|
||||
it("only scans moves with seq strictly greater than armed_from_move_count", () => {
|
||||
const triggers = [trigger({ atoms: ["up:eco"], armedFromMoveCount: 5 })];
|
||||
const moves = [seated(5, 1, "xenos up eco"), seated(4, 1, "xenos up eco")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)).to.equal(null);
|
||||
|
||||
const laterMoves = [...moves, seated(6, 1, "xenos up eco")];
|
||||
expect(matchCancelTriggers(triggers, laterMoves, identityMap)?.matchedMove.seq).to.equal(6);
|
||||
});
|
||||
|
||||
it("only watches the trigger's own watched seat - a different seat's identical move never fires it", () => {
|
||||
const triggers = [trigger({ atoms: ["up:eco"], watchedSeat: 1 })];
|
||||
const moves = [seated(1, 2, "firaks up eco")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)).to.equal(null);
|
||||
});
|
||||
|
||||
it("OR-s multiple triggers on different opponents - the first (chronological) match wins", () => {
|
||||
const triggers = [
|
||||
trigger({ seq: 1, watchedSeat: 1, atoms: ["up:eco"] }),
|
||||
trigger({ seq: 2, watchedSeat: 2, atoms: ["tech:*"] }),
|
||||
];
|
||||
const moves = [seated(1, 2, "firaks tech eco"), seated(2, 1, "xenos up eco")];
|
||||
const result = matchCancelTriggers(triggers, moves, identityMap);
|
||||
expect(result?.trigger.seq).to.equal(2);
|
||||
expect(result?.matchedMove.seq).to.equal(1);
|
||||
});
|
||||
|
||||
it("atoms combine with OR within one trigger - either selected atom fires it", () => {
|
||||
const triggers = [trigger({ atoms: ["up:eco", "tech:eco"] })];
|
||||
expect(matchCancelTriggers(triggers, [seated(1, 1, "xenos tech eco")], identityMap)?.atom).to.equal("tech:eco");
|
||||
});
|
||||
|
||||
it("requires the atom to appear within a single committed move, not spread across two", () => {
|
||||
const triggers = [trigger({ atoms: ["build:m:*"] })];
|
||||
// "build" never appears in either move on its own - only "gaiaform" then, separately, "up".
|
||||
const moves = [seated(1, 1, "xenos gaiaFormTransdim 3A4"), seated(2, 1, "xenos up eco")];
|
||||
expect(matchCancelTriggers(triggers, moves, identityMap)).to.equal(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchCancelTriggers - leech kind", () => {
|
||||
const gained: LeechConfig = { mode: "gained", minPower: 2 };
|
||||
const offered: LeechConfig = { mode: "offered", minPower: 2 };
|
||||
|
||||
function leechTrigger(config: LeechConfig, seat = 1): CancelTriggerRow {
|
||||
return trigger({ kind: "leech", watchedSeat: seat, atoms: [], config });
|
||||
}
|
||||
|
||||
it("fires on charge 2pw at minPower 2", () => {
|
||||
const result = matchCancelTriggers([leechTrigger(gained)], [seated(1, 1, "xenos charge 2pw")], identityMap);
|
||||
expect(result?.atom).to.equal("charge:2pw");
|
||||
});
|
||||
|
||||
it("does not fire on charge 1pw at minPower 2", () => {
|
||||
expect(matchCancelTriggers([leechTrigger(gained)], [seated(1, 1, "xenos charge 1pw")], identityMap)).to.equal(null);
|
||||
});
|
||||
|
||||
it("decline 3pw fires in 'offered' mode but not in 'gained' mode", () => {
|
||||
const moves = [seated(1, 1, "xenos decline 3pw")];
|
||||
expect(matchCancelTriggers([leechTrigger(offered)], moves, identityMap)?.atom).to.equal("decline:3pw");
|
||||
expect(matchCancelTriggers([leechTrigger(gained)], moves, identityMap)).to.equal(null);
|
||||
});
|
||||
|
||||
it("an opponent's charge never fires the owner's leech trigger", () => {
|
||||
// Trigger's watched_seat is the OWNER's own seat (1); the charge below belongs to seat 2.
|
||||
const result = matchCancelTriggers([leechTrigger(gained, 1)], [seated(1, 2, "firaks charge 5pw")], identityMap);
|
||||
expect(result).to.equal(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchCancelTriggers - mixed kinds", () => {
|
||||
it("a leech trigger and a move trigger armed together: whichever matches first (chronologically) wins", () => {
|
||||
const moveTrig = trigger({ seq: 1, kind: "move", watchedSeat: 2, atoms: ["up:eco"] });
|
||||
const leechTrig = trigger({
|
||||
seq: 2,
|
||||
kind: "leech",
|
||||
watchedSeat: 1,
|
||||
atoms: [],
|
||||
config: { mode: "gained", minPower: 2 },
|
||||
});
|
||||
const moves = [seated(1, 1, "xenos charge 2pw"), seated(2, 2, "firaks up eco")];
|
||||
const result = matchCancelTriggers([moveTrig, leechTrig], moves, identityMap);
|
||||
expect(result?.trigger.kind).to.equal("leech");
|
||||
expect(result?.matchedMove.seq).to.equal(1);
|
||||
});
|
||||
|
||||
it("returns null when no trigger matches anything", () => {
|
||||
const moveTrig = trigger({ kind: "move", watchedSeat: 2, atoms: ["up:eco"] });
|
||||
const leechTrig = trigger({ kind: "leech", watchedSeat: 1, atoms: [], config: { mode: "gained", minPower: 2 } });
|
||||
const moves = [seated(1, 1, "xenos charge 1pw"), seated(2, 2, "firaks tech eco")];
|
||||
expect(matchCancelTriggers([moveTrig, leechTrig], moves, identityMap)).to.equal(null);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,293 +0,0 @@
|
|||
// Premove cancel triggers (docs/lost-fleet/PREMOVE_PLAN.md's premove design, extended by the
|
||||
// cancel-trigger spec) - the shared decision module for "does anything watched by this seat's
|
||||
// armed triggers appear in the committed moves since they were armed, and if so which one fires
|
||||
// first". Designed so a client fast-path and a server-side automation function can import the same
|
||||
// module (this .ts source directly, the same way premove-resolver.ts is structured), so
|
||||
// online/offline evaluation can never drift.
|
||||
//
|
||||
// Structural/engine-agnostic on purpose - no "@gaia-project/engine" import here, and no import of
|
||||
// viewer/src/logic/recent.ts either (that file pulls in the real engine's `Command` enum, which
|
||||
// would drag a static "@gaia-project/engine" dependency into resolve-automation's bundle; that
|
||||
// function only ever loads the engine dynamically via ../_shared/engine.bundle.js). This file
|
||||
// duplicates the small slice of recent.ts's move-parsing it needs (parseCommands/cleanArg/hexArg)
|
||||
// as plain strings instead, deliberately - see premove-resolver.ts's own doc comment for the same
|
||||
// reasoning applied to engine types.
|
||||
//
|
||||
// Matching is on EFFECT, not on the literal move string (§2.1): a move is normalized into a set of
|
||||
// "atoms", one per command in the line, each canonicalized so equivalent notations (a cube
|
||||
// coordinate vs. a sector-relative one vs. an Interspace/Deep Space id for the same hex) and
|
||||
// equivalent routes (a research step from a tech tile vs. a "free" tile vs. a faction's own special
|
||||
// action) compare equal.
|
||||
|
||||
export type CancelTriggerKind = "move" | "leech";
|
||||
export type LeechConfig = { mode: "gained" | "offered"; minPower: number };
|
||||
|
||||
export type CancelTriggerRow = {
|
||||
seq: number;
|
||||
kind: CancelTriggerKind;
|
||||
watchedSeat: number;
|
||||
move: string;
|
||||
atoms: string[];
|
||||
config: LeechConfig | Record<string, never>;
|
||||
match: "any" | "all";
|
||||
armedFromMoveCount: number;
|
||||
};
|
||||
|
||||
export type SeatedMove = { seq: number; seat: number; move: string };
|
||||
|
||||
/** The only engine surface this file needs: canonicalizing a coordinate string to its unique
|
||||
* per-hex address, whatever notation it was written in (cube/sector-relative/Lost Fleet IS/DS). */
|
||||
export type MapLike = { getS(coords: string): { toString(): string } };
|
||||
|
||||
type ParsedCommand = { command: string; args: string[] };
|
||||
|
||||
/** Local copy of recent.ts's parseCommands (see the file header for why this can't just import
|
||||
* that one) - identical behavior: strip the leading faction token, split on ".", drop any
|
||||
* parenthesized suffix, ignore empty segments. */
|
||||
function parseCommandLine(move: string): ParsedCommand[] {
|
||||
const trimmed = move.trim();
|
||||
const factionIndex = trimmed.indexOf(" ");
|
||||
if (factionIndex === -1) {
|
||||
return [];
|
||||
}
|
||||
return trimmed
|
||||
.slice(factionIndex)
|
||||
.split(".")
|
||||
.flatMap((segment) => {
|
||||
const split = segment.split("(")[0].trim().split(/\s+/);
|
||||
if (split[0].length === 0) {
|
||||
return [];
|
||||
}
|
||||
return [{ command: split[0], args: split.slice(1) }];
|
||||
});
|
||||
}
|
||||
|
||||
/** A move line's last argument can keep the "." that separates it from the next command, e.g.
|
||||
* "build m 3A4." (recent.ts's cleanArg, duplicated for the same reason as parseCommandLine). */
|
||||
function cleanArg(arg: string | undefined): string {
|
||||
return (arg ?? "").replace(/\.+$/, "");
|
||||
}
|
||||
|
||||
/** Which argument index of a command names the hex it happened on (recent.ts's hexArg table). */
|
||||
const HEX_ARG_INDEX: Record<string, number> = {
|
||||
build: 1,
|
||||
gaiaFormTransdim: 0,
|
||||
lostPlanet: 0,
|
||||
placePowerRing: 0,
|
||||
};
|
||||
|
||||
const FEDERATION_COMMAND = "federation";
|
||||
|
||||
/** §2.2 step 2's plumbing DROP list - applies only to candidateAtoms (the composer), never to
|
||||
* moveAtoms (normalizing an actual committed move for matching): "we compare against everything
|
||||
* they did; you just can't ask to watch plumbing." */
|
||||
const PLUMBING_DROP = new Set(["spend", "burn", "brainstone", "charge", "decline", "income", "endturn"]);
|
||||
|
||||
function canonicalizeHex(coord: string, map: MapLike): string {
|
||||
try {
|
||||
return map.getS(coord).toString();
|
||||
} catch {
|
||||
// Unrecognized/malformed coordinate (e.g. a future notation this build doesn't know yet) -
|
||||
// fall back to the cleaned raw text rather than throwing out of a matcher that runs against
|
||||
// arbitrary recorded history (mirrors recent.ts's hexMovesByHex's own defensive catch).
|
||||
return coord;
|
||||
}
|
||||
}
|
||||
|
||||
/** One command's args, canonicalized: hex-bearing positions through the map, FormFederation's
|
||||
* comma-separated hex list canonicalized member-by-member and sorted, everything else lowercased. */
|
||||
function canonicalizeArgs(command: string, args: string[], map: MapLike): string[] {
|
||||
const hexIndex = HEX_ARG_INDEX[command];
|
||||
return args.map((raw, index) => {
|
||||
const cleaned = cleanArg(raw);
|
||||
if (command === FEDERATION_COMMAND && index === 0) {
|
||||
return cleaned
|
||||
.split(",")
|
||||
.map((c) => canonicalizeHex(c, map))
|
||||
.sort()
|
||||
.join(",");
|
||||
}
|
||||
if (hexIndex === index) {
|
||||
return canonicalizeHex(cleaned, map);
|
||||
}
|
||||
return cleaned.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function encodeAtom(command: string, args: string[]): string {
|
||||
return [command, ...args].join(":");
|
||||
}
|
||||
|
||||
/** Normalizes one committed move line into its atom set (§2.2 - no plumbing filtering here: an
|
||||
* actual move is normalized in full, since the composer can never offer a plumbing atom in the
|
||||
* first place, so no trigger can ever contain one to match against). */
|
||||
export function moveAtoms(move: string, map: MapLike): string[] {
|
||||
const commands = parseCommandLine(move);
|
||||
const atoms = commands.map((c) => encodeAtom(c.command, canonicalizeArgs(c.command, c.args, map)));
|
||||
return [...new Set(atoms)];
|
||||
}
|
||||
|
||||
/** §2.4 - which command forms offer a loosened ("any") form, and how many of their leading
|
||||
* (already-canonicalized) args survive into it. `build` keeps its building type and drops only the
|
||||
* hex ("any lab, anywhere"); every other listed form collapses entirely to `command:*`. Forms not
|
||||
* in this table have no loosening - candidateAtoms returns `any: null` for them. */
|
||||
const LOOSE_KEEP_PREFIX: Record<string, number> = {
|
||||
build: 1,
|
||||
up: 0,
|
||||
tech: 0,
|
||||
action: 0,
|
||||
special: 0,
|
||||
pass: 0,
|
||||
federation: 0,
|
||||
};
|
||||
|
||||
function looseAtom(command: string, canonicalArgs: string[]): string | null {
|
||||
const keep = LOOSE_KEEP_PREFIX[command];
|
||||
if (keep === undefined) {
|
||||
return null;
|
||||
}
|
||||
return encodeAtom(command, [...canonicalArgs.slice(0, keep), "*"]);
|
||||
}
|
||||
|
||||
const BUILDING_LABELS: Record<string, string> = {
|
||||
m: "a mine",
|
||||
ts: "a trading station",
|
||||
lab: "a research lab",
|
||||
ac1: "an academy",
|
||||
ac2: "an academy",
|
||||
pi: "the planetary institute",
|
||||
gf: "a gaiaformer",
|
||||
};
|
||||
|
||||
/** Plain-language text for one candidate atom's refine-screen row (§8.3). Cosmetic only - never
|
||||
* used for matching, so it doesn't need to be exhaustive for every command in the game. */
|
||||
function describeCommand(command: string, args: string[]): string {
|
||||
switch (command) {
|
||||
case "build":
|
||||
return `Build ${BUILDING_LABELS[args[0]?.toLowerCase()] ?? args[0]} at ${args[1]}`;
|
||||
case "up":
|
||||
return `Advance ${args[0]}`;
|
||||
case "tech":
|
||||
return `Take the tech tile at ${args[0]}`;
|
||||
case "action":
|
||||
return `Take board action ${args[0]}`;
|
||||
case "special":
|
||||
return `Use special action ${args[0]}`;
|
||||
case "pass":
|
||||
return `Pass, taking booster ${args[0]}`;
|
||||
case "federation":
|
||||
return `Form a federation${args[1] ? ` (tile ${args[1]})` : ""}`;
|
||||
case "charge":
|
||||
return `Charge ${args[0]}`;
|
||||
case "decline":
|
||||
return `Decline ${args[0]}`;
|
||||
default:
|
||||
return args.length > 0 ? `${command} ${args.join(" ")}` : command;
|
||||
}
|
||||
}
|
||||
|
||||
/** Atoms of a composed move, exact + loose form + label, for the refine chips (§2.3/§2.4). This is
|
||||
* the ONLY place the plumbing DROP list is applied - actual-move normalization (moveAtoms) never
|
||||
* filters. Unknown commands are default-kept (§2.2): a new command surfaces as an over-broad
|
||||
* trigger candidate, never a silently-missed one. Deduped by exact atom text, first-seen order. */
|
||||
export function candidateAtoms(
|
||||
move: string,
|
||||
map: MapLike
|
||||
): Array<{ exact: string; any: string | null; label: string }> {
|
||||
const seen = new Set<string>();
|
||||
const result: Array<{ exact: string; any: string | null; label: string }> = [];
|
||||
for (const c of parseCommandLine(move)) {
|
||||
if (PLUMBING_DROP.has(c.command)) {
|
||||
continue;
|
||||
}
|
||||
const canonicalArgs = canonicalizeArgs(c.command, c.args, map);
|
||||
const exact = encodeAtom(c.command, canonicalArgs);
|
||||
if (seen.has(exact)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(exact);
|
||||
result.push({ exact, any: looseAtom(c.command, canonicalArgs), label: describeCommand(c.command, c.args) });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** A stored atom (exact, or loose with a trailing "*") matches an actual atom when the command
|
||||
* matches and every stored position before a trailing "*" equals the actual one there (§2.4) - a
|
||||
* trailing "*" leaves everything from that position on unconstrained, otherwise every position must
|
||||
* match exactly, including the argument count. Exported so the refine/leech-config UI's own
|
||||
* "would have fired" preview (§8.3/§8.4) can reuse the exact same comparison instead of a second,
|
||||
* potentially drifting copy. */
|
||||
export function atomMatches(stored: string, actual: string): boolean {
|
||||
const s = stored.split(":");
|
||||
const a = actual.split(":");
|
||||
if (s[0] !== a[0]) {
|
||||
return false;
|
||||
}
|
||||
if (s[s.length - 1] === "*") {
|
||||
for (let i = 1; i < s.length - 1; i++) {
|
||||
if (s[i] !== a[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return s.length === a.length && s.every((part, i) => part === a[i]);
|
||||
}
|
||||
|
||||
/** §2.6 - the leading integer of a "<N>pw" arg, e.g. "2pw" -> 2. */
|
||||
function leadingPowerAmount(arg: string | undefined): number | null {
|
||||
const amount = parseInt(arg ?? "", 10);
|
||||
return Number.isNaN(amount) ? null : amount;
|
||||
}
|
||||
|
||||
/** §2.6 - a leech trigger's own scan of ONE move already known to belong to the owner's own watched
|
||||
* seat: does it contain a charge/decline atom meeting the trigger's mode/threshold? Returns the
|
||||
* matched atom text (also what the notice renders) or null. */
|
||||
function leechMatch(move: SeatedMove, config: LeechConfig, map: MapLike): string | null {
|
||||
for (const atom of moveAtoms(move.move, map)) {
|
||||
const [command, arg] = atom.split(":");
|
||||
if (command !== "charge" && (command !== "decline" || config.mode !== "offered")) {
|
||||
continue;
|
||||
}
|
||||
const amount = leadingPowerAmount(arg);
|
||||
if (amount !== null && amount >= config.minPower) {
|
||||
return atom;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** §2 - the one decision function. Scans committed moves in chronological order and, for each,
|
||||
* checks every armed trigger whose watched seat played it and whose arm-time is behind it; returns
|
||||
* the first (move, trigger) pair that matches, or null. Chronological-move-first order is what
|
||||
* makes "whichever matches first" mean what actually happened first in the game, not merely
|
||||
* whichever trigger happens to sit first in the caller's array. */
|
||||
export function matchCancelTriggers(
|
||||
triggers: CancelTriggerRow[],
|
||||
moves: SeatedMove[],
|
||||
map: MapLike
|
||||
): { trigger: CancelTriggerRow; matchedMove: SeatedMove; atom: string } | null {
|
||||
const orderedMoves = [...moves].sort((a, b) => a.seq - b.seq);
|
||||
for (const move of orderedMoves) {
|
||||
for (const trigger of triggers) {
|
||||
if (move.seat !== trigger.watchedSeat || move.seq <= trigger.armedFromMoveCount) {
|
||||
continue;
|
||||
}
|
||||
if (trigger.kind === "leech") {
|
||||
const atom = leechMatch(move, trigger.config as LeechConfig, map);
|
||||
if (atom) {
|
||||
return { trigger, matchedMove: move, atom };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const actualAtoms = moveAtoms(move.move, map);
|
||||
for (const stored of trigger.atoms) {
|
||||
const hit = actualAtoms.find((actual) => atomMatches(stored, actual));
|
||||
if (hit) {
|
||||
return { trigger, matchedMove: move, atom: hit };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
import Engine from "@gaia-project/engine";
|
||||
import { expect } from "chai";
|
||||
import { buildSequentialChainPreview } from "./premove-preview";
|
||||
|
||||
// Same fixture as host.spec.ts/Game.spec.ts's "premove (hosted mode)" describe block: after these
|
||||
// moves it's terrans' (seat 0) turn, and "nevlas up terra." / "nevlas pass booster4" are both legal,
|
||||
// turn-completing moves for nevlas (seat 1).
|
||||
const SETUP_MOVES = [
|
||||
"init 2 randomSeed",
|
||||
"p1 faction terrans",
|
||||
"p2 faction nevlas",
|
||||
"terrans build m -1x2",
|
||||
"nevlas build m -1x0",
|
||||
"nevlas build m 0x-4",
|
||||
"terrans build m -4x-1",
|
||||
"nevlas booster booster7",
|
||||
"terrans booster booster3",
|
||||
];
|
||||
|
||||
describe("buildSequentialChainPreview", () => {
|
||||
it("forces the given seat's turn with no prior moves (equivalent to previewAvailableCommandsFor)", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
const clone = buildSequentialChainPreview(engine, 1, []);
|
||||
expect(clone.playerToMove).to.equal(1);
|
||||
expect(clone.availableCommands.map((c) => c.name)).to.include("up");
|
||||
});
|
||||
|
||||
it("previews premove #2 against a clone with #1 already applied", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
const clone = buildSequentialChainPreview(engine, 1, ["nevlas up terra."]);
|
||||
// #1's effect (the research upgrade) is visible, and it's forced back to seat 1's turn for #2.
|
||||
expect(clone.playerToMove).to.equal(1);
|
||||
expect(clone.availableCommands.map((c) => c.name)).to.not.include("up");
|
||||
expect(clone.availableCommands.map((c) => c.name)).to.include("pass");
|
||||
|
||||
// #2 itself is a legal, turn-completing move against this chained preview.
|
||||
clone.move("nevlas pass booster4");
|
||||
clone.generateAvailableCommandsIfNeeded();
|
||||
expect(clone.newTurn).to.equal(true);
|
||||
});
|
||||
|
||||
it("does not throw, and stops the chain, when an earlier queued move has gone illegal", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
// "up nav" is not a real prior queued move for this fixture - simulates a since-illegal entry.
|
||||
const clone = buildSequentialChainPreview(engine, 1, ["nevlas build m 99x99"]);
|
||||
// Broke on the illegal replay, so the preview reflects the ORIGINAL state, still forced to seat 1.
|
||||
expect(clone.playerToMove).to.equal(1);
|
||||
expect(clone.availableCommands.map((c) => c.name)).to.include("up");
|
||||
});
|
||||
|
||||
it("keeps chaining when premove #1 offers an opponent a leech", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
// Nevlas's mine at -1x0 is two hexes from terrans' at -1x2, so upgrading it offers terrans 2
|
||||
// power - a real decision (it costs a VP), which parks the engine in Phase.RoundLeech. Replaying
|
||||
// that move used to leave the chain clone stuck in that phase, where the next slot could
|
||||
// generate no commands at all and every queued row behind it read "no longer possible".
|
||||
engine.players[1].data.credits = 20;
|
||||
engine.players[1].data.ores = 20;
|
||||
|
||||
const clone = buildSequentialChainPreview(engine, 1, ["nevlas build ts -1x0."]);
|
||||
|
||||
expect(clone.playerToMove).to.equal(1);
|
||||
expect(clone.availableCommands.length).to.be.greaterThan(0);
|
||||
expect(clone.availableCommands.map((c) => c.name)).to.include("pass");
|
||||
|
||||
clone.move("nevlas pass booster4");
|
||||
clone.generateAvailableCommandsIfNeeded();
|
||||
expect(clone.newTurn).to.equal(true);
|
||||
});
|
||||
|
||||
it("leaves the original engine untouched", () => {
|
||||
const engine = new Engine(SETUP_MOVES);
|
||||
const before = JSON.stringify(engine);
|
||||
buildSequentialChainPreview(engine, 1, ["nevlas up terra."]);
|
||||
expect(JSON.stringify(engine)).to.equal(before);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
import Engine, { PlayerEnum } from "@gaia-project/engine";
|
||||
|
||||
// Phase 3 (docs/lost-fleet/PREMOVE_PLAN.md §10.1) - the composer-side counterpart of the engine's
|
||||
// own `previewAvailableCommandsFor`: builds the clone a NEW queue entry should be composed against.
|
||||
//
|
||||
// - Priority mode previews every rank against the SAME fresh current state (one turn ahead only) -
|
||||
// trivial, just `previewAvailableCommandsFor` itself.
|
||||
// - Sequential mode chains: premove #2 is previewed against a clone with #1 already applied, #3
|
||||
// against a clone with #1+#2 applied. Each already-queued move is replayed in turn-order, then the
|
||||
// engine's own "force it to be this seat's turn" trick (identical to previewAvailableCommandsFor)
|
||||
// is re-applied so the NEXT slot's preview models "assume my prior queued turn(s) landed, what can
|
||||
// I do for the one after that" rather than whoever the engine says is really up next.
|
||||
//
|
||||
// A since-illegal earlier entry (replayed move now throws) stops the chain where it broke rather
|
||||
// than guessing further - the resolver's own runtime cascade (§10.5) is what actually cleans up a
|
||||
// broken chain when it executes; this is preview-only, never used for execution (see §2's own
|
||||
// caveat, unchanged by Phase 3).
|
||||
export function buildSequentialChainPreview(engine: Engine, seat: number, priorMoves: string[]): Engine {
|
||||
const clone = Engine.fromData(JSON.parse(JSON.stringify(engine)));
|
||||
for (const move of priorMoves) {
|
||||
// Force it to be this seat's move-phase turn before EACH replayed step, not just once at the
|
||||
// end - the real engine only lets a move through when playerToMove already matches the move's
|
||||
// stated player, and every one of these steps is only ever hypothetically "this seat's turn"
|
||||
// (that's the whole point of previewing a premove chain before it's genuinely anyone's turn for
|
||||
// real). `forcePremovePreviewTurn` resets the PHASE too, which is what makes a chain survive a
|
||||
// step that offers an opponent a leech: replaying such a move leaves the clone in RoundLeech,
|
||||
// where the next step could neither execute nor generate a single available command, so every
|
||||
// slot after the first build near an opponent came back empty/"no longer possible" (2026-08-06).
|
||||
clone.forcePremovePreviewTurn(seat as PlayerEnum);
|
||||
try {
|
||||
clone.move(move);
|
||||
clone.generateAvailableCommandsIfNeeded();
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
}
|
||||
clone.forcePremovePreviewTurn(seat as PlayerEnum);
|
||||
clone.generateAvailableCommands();
|
||||
return clone;
|
||||
}
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
import { expect } from "chai";
|
||||
import type { EngineLike } from "./premove-resolver";
|
||||
import { resolvePremoveQueue } from "./premove-resolver";
|
||||
|
||||
// Fully generic tests (no real engine needed - the resolver is engine-agnostic, see its own doc
|
||||
// comment) exercising the mode-branching decision logic in isolation, per PREMOVE_PLAN.md §10.8.
|
||||
// `behavior` scripts what each move line does when applied to a fresh clone: "ok" completes a turn,
|
||||
// "incomplete" applies but leaves newTurn false, anything else (including omission) throws.
|
||||
function fakeCloneFactory(behavior: Record<string, "ok" | "incomplete">): () => EngineLike {
|
||||
return () => {
|
||||
const engine: EngineLike = {
|
||||
playerToMove: 0,
|
||||
phase: "roundMove",
|
||||
round: 1,
|
||||
newTurn: false,
|
||||
players: [],
|
||||
move(line: string) {
|
||||
const outcome = behavior[line];
|
||||
if (outcome === undefined) {
|
||||
throw new Error(`illegal move: ${line}`);
|
||||
}
|
||||
engine.newTurn = outcome === "ok";
|
||||
},
|
||||
generateAvailableCommandsIfNeeded() {
|
||||
return undefined;
|
||||
},
|
||||
};
|
||||
return engine;
|
||||
};
|
||||
}
|
||||
|
||||
describe("resolvePremoveQueue", () => {
|
||||
it("returns 'none' for an empty queue", () => {
|
||||
const result = resolvePremoveQueue(fakeCloneFactory({}), 0, [], "sequential");
|
||||
expect(result).to.deep.equal({ outcome: "none" });
|
||||
});
|
||||
|
||||
describe("sequential mode", () => {
|
||||
it("fires the lowest-seq entry when it's legal, leaving the rest untouched", () => {
|
||||
const clone = fakeCloneFactory({ A: "ok" });
|
||||
const result = resolvePremoveQueue(
|
||||
clone,
|
||||
0,
|
||||
[
|
||||
{ seq: 2, move: "B" },
|
||||
{ seq: 1, move: "A" },
|
||||
],
|
||||
"sequential"
|
||||
);
|
||||
expect(result.outcome).to.equal("success");
|
||||
if (result.outcome === "success") {
|
||||
expect(result.move).to.equal("A");
|
||||
expect(result.consumedSeqs).to.deep.equal([1]);
|
||||
expect(result.rank).to.equal(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("cascades away every later entry when the head throws", () => {
|
||||
const clone = fakeCloneFactory({ B: "ok", C: "ok" });
|
||||
const result = resolvePremoveQueue(
|
||||
clone,
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
{ seq: 3, move: "C" },
|
||||
],
|
||||
"sequential"
|
||||
);
|
||||
expect(result.outcome).to.equal("failed");
|
||||
if (result.outcome === "failed") {
|
||||
expect(result.failedMove).to.equal("A");
|
||||
expect(result.consumedSeqs).to.deep.equal([1, 2, 3]);
|
||||
expect(result.reason).to.contain("illegal move: A");
|
||||
expect(result.reason).to.contain("2 more queued premoves discarded");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not cascade when the throwing entry has nothing queued behind it", () => {
|
||||
const result = resolvePremoveQueue(fakeCloneFactory({}), 0, [{ seq: 1, move: "A" }], "sequential");
|
||||
expect(result.outcome).to.equal("failed");
|
||||
if (result.outcome === "failed") {
|
||||
expect(result.consumedSeqs).to.deep.equal([1]);
|
||||
expect(result.reason).to.not.contain("discarded");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not cascade the defensive incomplete-turn case (only a throw cascades)", () => {
|
||||
const clone = fakeCloneFactory({ A: "incomplete" });
|
||||
const result = resolvePremoveQueue(
|
||||
clone,
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
],
|
||||
"sequential"
|
||||
);
|
||||
expect(result.outcome).to.equal("failed");
|
||||
if (result.outcome === "failed") {
|
||||
expect(result.reason).to.equal("premove did not complete a turn");
|
||||
expect(result.consumedSeqs).to.deep.equal([1]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("priority mode", () => {
|
||||
it("fires rank 1 when it's legal and clears the whole queue", () => {
|
||||
const clone = fakeCloneFactory({ A: "ok", B: "ok" });
|
||||
const result = resolvePremoveQueue(
|
||||
clone,
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
],
|
||||
"priority"
|
||||
);
|
||||
expect(result.outcome).to.equal("success");
|
||||
if (result.outcome === "success") {
|
||||
expect(result.move).to.equal("A");
|
||||
expect(result.rank).to.equal(1);
|
||||
expect(result.totalRanks).to.equal(2);
|
||||
expect(result.consumedSeqs).to.deep.equal([1, 2]);
|
||||
}
|
||||
});
|
||||
|
||||
it("silently skips an illegal rank 1 and fires rank 2", () => {
|
||||
const clone = fakeCloneFactory({ B: "ok" });
|
||||
const result = resolvePremoveQueue(
|
||||
clone,
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
{ seq: 3, move: "C" },
|
||||
],
|
||||
"priority"
|
||||
);
|
||||
expect(result.outcome).to.equal("success");
|
||||
if (result.outcome === "success") {
|
||||
expect(result.move).to.equal("B");
|
||||
expect(result.rank).to.equal(2);
|
||||
expect(result.totalRanks).to.equal(3);
|
||||
// Every rank clears together, including the never-tried rank 3.
|
||||
expect(result.consumedSeqs).to.deep.equal([1, 2, 3]);
|
||||
}
|
||||
});
|
||||
|
||||
it("records one failure and clears everything when every rank is illegal", () => {
|
||||
const result = resolvePremoveQueue(
|
||||
fakeCloneFactory({}),
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
],
|
||||
"priority"
|
||||
);
|
||||
expect(result.outcome).to.equal("failed");
|
||||
if (result.outcome === "failed") {
|
||||
expect(result.reason).to.equal("none of your 2 ranked premoves were legal");
|
||||
expect(result.failedMove).to.equal("A / B");
|
||||
expect(result.consumedSeqs).to.deep.equal([1, 2]);
|
||||
}
|
||||
});
|
||||
|
||||
it("tries each rank against the SAME original state, not a mutated previous attempt", () => {
|
||||
let cloneCalls = 0;
|
||||
const factory = () => {
|
||||
cloneCalls++;
|
||||
return fakeCloneFactory({ B: "ok" })();
|
||||
};
|
||||
const result = resolvePremoveQueue(
|
||||
factory,
|
||||
0,
|
||||
[
|
||||
{ seq: 1, move: "A" },
|
||||
{ seq: 2, move: "B" },
|
||||
],
|
||||
"priority"
|
||||
);
|
||||
expect(cloneCalls).to.equal(2); // one fresh clone per rank tried
|
||||
expect(result.outcome).to.equal("success");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
// Phase 3 (docs/lost-fleet/PREMOVE_PLAN.md §10.5) - the one shared decision function for "given a
|
||||
// seat's queued premoves and the engine state at the instant it's genuinely their turn
|
||||
// (Phase.RoundMove already confirmed by the caller), which move (if any) should be committed, and
|
||||
// what happens to the queue afterward". Imported identically by host.ts's client fast-path and by
|
||||
// resolve-automation/logic.ts's edge-function path, so online/offline resolution can never drift -
|
||||
// this is the ONLY place either mode's branching logic is decided (mirrors how auto-decide.ts is the
|
||||
// one shared leech-decision helper for both paths).
|
||||
//
|
||||
// Structural/engine-agnostic on purpose (no "@gaia-project/engine" import here), for the same reason
|
||||
// resolve-automation/logic.ts's own EngineModule/EngineInstance types are structural: it lets each
|
||||
// caller supply whatever Engine implementation it already has in hand (host.ts's real statically-
|
||||
// imported Engine; the edge function's dynamically-bundled one) without this file taking on a build/
|
||||
// bundling dependency of its own.
|
||||
|
||||
export type PremoveMode = "sequential" | "priority";
|
||||
|
||||
/** Exported so callers can distinguish this defensive case (shouldn't normally happen - queuing
|
||||
* already enforces completeness) from a genuine thrown-error failure without string-sniffing an
|
||||
* arbitrary engine error message. */
|
||||
export const INCOMPLETE_TURN_REASON = "premove did not complete a turn";
|
||||
|
||||
export type QueuedPremove = { seq: number; move: string };
|
||||
|
||||
export type EngineLike = {
|
||||
playerToMove: number | undefined;
|
||||
phase: string;
|
||||
round: number;
|
||||
newTurn: boolean;
|
||||
players: unknown[];
|
||||
move(line: string): void;
|
||||
generateAvailableCommandsIfNeeded(): unknown;
|
||||
};
|
||||
|
||||
export type PremoveResolution =
|
||||
| { outcome: "none" }
|
||||
| {
|
||||
outcome: "success";
|
||||
move: string;
|
||||
resultEngine: EngineLike;
|
||||
/** seq values to delete from the seat's queue now that this turn has been decided. */
|
||||
consumedSeqs: number[];
|
||||
/** Priority only: which rank fired (1-based) and how many were ranked, for the success toast
|
||||
* naming the rank when it wasn't rank 1 (§10.6). */
|
||||
rank?: number;
|
||||
totalRanks?: number;
|
||||
}
|
||||
| {
|
||||
outcome: "failed";
|
||||
reason: string;
|
||||
/** The move text to record in premove_failures (a single representative line even when
|
||||
* multiple rows are discarded together). */
|
||||
failedMove: string;
|
||||
consumedSeqs: number[];
|
||||
};
|
||||
|
||||
function attempt(
|
||||
cloneEngine: () => EngineLike,
|
||||
move: string
|
||||
): { ok: true; engine: EngineLike } | { ok: false; threw: boolean; reason: string } {
|
||||
const clone = cloneEngine();
|
||||
try {
|
||||
clone.move(move);
|
||||
clone.generateAvailableCommandsIfNeeded();
|
||||
} catch (err) {
|
||||
return { ok: false, threw: true, reason: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
if (!clone.newTurn) {
|
||||
return { ok: false, threw: false, reason: INCOMPLETE_TURN_REASON };
|
||||
}
|
||||
return { ok: true, engine: clone };
|
||||
}
|
||||
|
||||
/**
|
||||
* `cloneEngine` must produce a FRESH disposable clone of the seat's real current engine state on
|
||||
* every call - Priority mode tries multiple candidates, each against the ORIGINAL committed state,
|
||||
* never against a previous candidate's mutation. A factory (rather than this file cloning directly)
|
||||
* lets each caller keep its own preferred cloning strategy (host.ts: `Engine.fromData(json)`; the
|
||||
* edge function: replaying the move log fresh) instead of this shared file taking a stance on it.
|
||||
*/
|
||||
export function resolvePremoveQueue(
|
||||
cloneEngine: () => EngineLike,
|
||||
seat: number,
|
||||
rows: QueuedPremove[],
|
||||
mode: PremoveMode
|
||||
): PremoveResolution {
|
||||
const ordered = [...rows].sort((a, b) => a.seq - b.seq);
|
||||
if (ordered.length === 0) {
|
||||
return { outcome: "none" };
|
||||
}
|
||||
|
||||
if (mode === "sequential") {
|
||||
const head = ordered[0];
|
||||
const result = attempt(cloneEngine, head.move);
|
||||
if (result.ok) {
|
||||
return { outcome: "success", move: head.move, resultEngine: result.engine, consumedSeqs: [head.seq] };
|
||||
}
|
||||
|
||||
const rest = ordered.slice(1).map((r) => r.seq);
|
||||
// Explicit shape: control-flow narrowing of the result union is unreliable under the older
|
||||
// TS used by some compile paths (engine tsconfig via ts-node), so assert the failure member.
|
||||
const failure = result as { ok: false; threw: boolean; reason: string };
|
||||
if (failure.threw && rest.length > 0) {
|
||||
// A broken link invalidates the plan behind it (§10.5): cascade-discard the rest rather than
|
||||
// attempting them against state their own preview never accounted for.
|
||||
return {
|
||||
outcome: "failed",
|
||||
reason: `${failure.reason} — ${rest.length} more queued premove${
|
||||
rest.length > 1 ? "s" : ""
|
||||
} discarded, they depended on this one`,
|
||||
failedMove: head.move,
|
||||
consumedSeqs: [head.seq, ...rest],
|
||||
};
|
||||
}
|
||||
// Either a plain throw with nothing behind it, or the defensive "applied but didn't complete a
|
||||
// turn" case (shouldn't normally happen - queuing already enforces completeness) - Phase 1's
|
||||
// original behavior, no cascade needed since there's nothing after it or nothing to protect.
|
||||
return { outcome: "failed", reason: failure.reason, failedMove: head.move, consumedSeqs: [head.seq] };
|
||||
}
|
||||
|
||||
// Priority: try ranks in ascending order against the SAME original state; first legal one wins.
|
||||
// An illegal rank is skipped silently - only "every rank illegal" is a reportable failure.
|
||||
for (let i = 0; i < ordered.length; i++) {
|
||||
const row = ordered[i];
|
||||
const result = attempt(cloneEngine, row.move);
|
||||
if (result.ok) {
|
||||
return {
|
||||
outcome: "success",
|
||||
move: row.move,
|
||||
resultEngine: result.engine,
|
||||
consumedSeqs: ordered.map((r) => r.seq),
|
||||
rank: i + 1,
|
||||
totalRanks: ordered.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
outcome: "failed",
|
||||
reason: `none of your ${ordered.length} ranked premoves were legal`,
|
||||
failedMove: ordered.map((r) => r.move).join(" / "),
|
||||
consumedSeqs: ordered.map((r) => r.seq),
|
||||
};
|
||||
}
|
||||
|
|
@ -78,7 +78,7 @@ export function stats(engine: Engine): PlayerTable {
|
|||
}),
|
||||
{
|
||||
shortcut: "L",
|
||||
title: "Leech network",
|
||||
title: "Charge network",
|
||||
color: "--res-power",
|
||||
cell: (p) => skipZero(leechNetwork(engine, p.player)),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,12 +1,6 @@
|
|||
// Decides - and then owns the lifetime of - the counter-transform that keeps both mobile sticky
|
||||
// footer states (#move-buttons on-turn, PremoveBar off-turn) at a constant on-screen size and
|
||||
// position while the game board is pinch-zoomed.
|
||||
//
|
||||
// This file is where the long-running "the fixed bar floats mid-screen" bug keeps being fought, so
|
||||
// it carries the whole mechanism rather than just the arithmetic: the pure decision below, AND the
|
||||
// listener/lifetime wiring (`attachZoomCompensation`). Both bars used to wire their own listeners
|
||||
// from `mounted()`, which is how they drifted apart once already (PremoveBar was left on an exact
|
||||
// `scale === 1` check after Commands moved to a tolerance).
|
||||
// Keeps the mobile action bar at a constant on-screen size and position while the board is
|
||||
// pinch-zoomed. Own both the arithmetic and listener lifetime here so stale viewport transforms
|
||||
// cannot leave the fixed bar floating in the middle of the screen.
|
||||
//
|
||||
// The governing rule, learned the hard way: **a transform written from a viewport snapshot must
|
||||
// never outlive the snapshot.** Every incarnation of this bug has been a transform that was correct
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import Engine, { BoardAction, Command, Faction, GaiaHex, Player, ResearchField } from "@gaia-project/engine";
|
||||
import type { AnyTechTilePos } from "@gaia-project/engine/src/enums";
|
||||
import { ArtifactToken, Spaceship } from "@gaia-project/engine/src/enums";
|
||||
import type { PremoveCommand } from "@gaia-project/engine/src/premove-types";
|
||||
import { CubeCoordinates } from "hexagrid";
|
||||
import Vue, { markRaw } from "vue";
|
||||
import Vuex from "vuex";
|
||||
|
|
@ -8,16 +9,7 @@ import type { ButtonData, GameContext, HexSelection, HighlightHex, SpecialAction
|
|||
import type { FastConversionEvent, MapMode } from "./data/actions";
|
||||
import type { FastConversionTooltips } from "./logic/buttons/types";
|
||||
import { ExecuteBack } from "./logic/buttons/types";
|
||||
import type {
|
||||
CancelTriggerKind,
|
||||
CancelTriggerLeechConfig,
|
||||
CancelTriggerRow,
|
||||
PremoveFailureRow,
|
||||
PremoveMode,
|
||||
PremoveRow,
|
||||
SealedBidEntry,
|
||||
SealedBidStatus,
|
||||
} from "./logic/hosted-types";
|
||||
import type { SealedBidEntry, SealedBidStatus } from "./logic/hosted-types";
|
||||
import type { PresenceState } from "./logic/presence";
|
||||
import type { CommandObject, MovesSlice } from "./logic/recent";
|
||||
import {
|
||||
|
|
@ -82,18 +74,10 @@ export type State = {
|
|||
/** Tutorials mark this move with the normal gold markers. Null keeps the hosted opponent recap;
|
||||
* an empty string marks nothing in a chapter's initial teaching position. */
|
||||
highlightedMove: string | null;
|
||||
/** Hosted mode only (PREMOVE_PLAN.md) - always empty in self-contained hot-seat play. */
|
||||
premoves: PremoveRow[];
|
||||
premoveFailures: PremoveFailureRow[];
|
||||
/** Phase 3 (§10.6) - quiet, in-app-only "played from your queue" notice for the most recent
|
||||
* fast-path success; null once dismissed or superseded. Never sourced from a push - see
|
||||
* host.ts's onPremovePlayed doc comment. */
|
||||
premovePlayedNotice: { seat: number; move: string; rank?: number; totalRanks?: number } | null;
|
||||
/** Premove cancel triggers - hosted mode only, always empty in self-contained hot-seat play. */
|
||||
cancelTriggers: CancelTriggerRow[];
|
||||
/** Quiet, in-app-only "cancelled by trigger" toast for the most recent fast-path match; null once
|
||||
* dismissed or superseded (mirrors premovePlayedNotice above). */
|
||||
cancelTriggerFiredNotice: { seat: number; reason: string } | null;
|
||||
hosted: boolean;
|
||||
playerSettings: Record<string, unknown> | null;
|
||||
pendingPlan: PremoveCommand | null;
|
||||
planError: string | null;
|
||||
/** Hosted mode only - seat -> user id, for matching a seat to its presence entry below. Never
|
||||
* populated in self-contained hot-seat play (no accounts/seats to map). */
|
||||
seatUsers: Record<number, string | null>;
|
||||
|
|
@ -202,11 +186,10 @@ const gaiaViewer = {
|
|||
player: null,
|
||||
highlightedMove: null,
|
||||
avatars: [] as string[],
|
||||
premoves: [],
|
||||
premoveFailures: [],
|
||||
premovePlayedNotice: null,
|
||||
cancelTriggers: [],
|
||||
cancelTriggerFiredNotice: null,
|
||||
hosted: false,
|
||||
playerSettings: null,
|
||||
pendingPlan: null,
|
||||
planError: null,
|
||||
seatUsers: {},
|
||||
seatLastActive: {},
|
||||
presence: {},
|
||||
|
|
@ -323,6 +306,10 @@ const gaiaViewer = {
|
|||
}
|
||||
},
|
||||
|
||||
playerSettings(state: State, data: Record<string, unknown> | null) {
|
||||
state.playerSettings = data;
|
||||
},
|
||||
|
||||
player(state: State, data: { index?: number }) {
|
||||
state.player = data;
|
||||
},
|
||||
|
|
@ -331,31 +318,21 @@ const gaiaViewer = {
|
|||
state.avatars = data;
|
||||
},
|
||||
|
||||
premoveState(state: State, data: { premoves: PremoveRow[]; failures: PremoveFailureRow[] }) {
|
||||
state.premoves = data.premoves;
|
||||
state.premoveFailures = data.failures;
|
||||
hosted(state: State, value: boolean) {
|
||||
state.hosted = value;
|
||||
},
|
||||
|
||||
premovePlayed(state: State, data: { seat: number; move: string; rank?: number; totalRanks?: number }) {
|
||||
state.premovePlayedNotice = data;
|
||||
submittingPlan(state: State, command: PremoveCommand) {
|
||||
state.pendingPlan = command;
|
||||
state.planError = null;
|
||||
},
|
||||
|
||||
dismissPremovePlayedNotice(state: State) {
|
||||
state.premovePlayedNotice = null;
|
||||
planSaved(state: State) {
|
||||
state.pendingPlan = null;
|
||||
state.planError = null;
|
||||
},
|
||||
|
||||
cancelTriggerState(state: State, triggers: CancelTriggerRow[]) {
|
||||
state.cancelTriggers = triggers;
|
||||
planError(state: State, message: string) {
|
||||
state.pendingPlan = null;
|
||||
state.planError = message;
|
||||
},
|
||||
|
||||
cancelTriggerFired(state: State, data: { seat: number; reason: string }) {
|
||||
state.cancelTriggerFiredNotice = data;
|
||||
},
|
||||
|
||||
dismissCancelTriggerFiredNotice(state: State) {
|
||||
state.cancelTriggerFiredNotice = null;
|
||||
},
|
||||
|
||||
seatUsers(state: State, data: Record<number, string | null>) {
|
||||
state.seatUsers = data;
|
||||
},
|
||||
|
|
@ -384,6 +361,7 @@ const gaiaViewer = {
|
|||
},
|
||||
},
|
||||
actions: {
|
||||
updatePlayerSetting(_context, _payload: { name: string; value: string }) {},
|
||||
// No body, used for signalling with store.subscribeAction
|
||||
hexClick(context: any, hex: GaiaHex, highlight?: HighlightHex) {},
|
||||
researchClick(context: any, field: ResearchField) {},
|
||||
|
|
@ -395,50 +373,8 @@ const gaiaViewer = {
|
|||
// API COMMUNICATION
|
||||
playerClick(context: any, player: Player) {},
|
||||
move(context: any, move: string) {},
|
||||
// Premove (PREMOVE_PLAN.md) - accumulates a command against a local preview clone only; never
|
||||
// reaches the launcher's "move" forwarding (see Game.vue's own subscribeAction handler, which
|
||||
// intercepts this type before it would otherwise be a no-op here).
|
||||
premoveMove(context: any, move: string) {},
|
||||
// Cancel trigger compose mode (Game.vue) - same "accumulates against a preview clone only,
|
||||
// intercepted locally, never reaches the launcher's real move forwarding" shape as premoveMove.
|
||||
cancelTriggerMove(context: any, move: string) {},
|
||||
// Analysis mode (docs/lost-fleet/ANALYSIS_MODE_PLAN.md) - the third board-takeover mode, same
|
||||
// "accumulates against a local clone only, intercepted by Game.vue, never reaches the
|
||||
// launcher's real move forwarding" shape as premoveMove/cancelTriggerMove above.
|
||||
analysisMove(context: any, move: string) {},
|
||||
queuePremove(context: any, payload: { seat: number; move: string; mode: PremoveMode }) {},
|
||||
cancelPremove(context: any, payload: { seat: number; seq: number }) {},
|
||||
// Premove UI redesign (Gaia 9) - update-in-place ("stage until confirmed", see host.ts).
|
||||
editPremove(context: any, payload: { seat: number; seq: number; move: string }) {},
|
||||
// Phase 3 (§10.4) - clears a seat's whole queue (mode-toggle confirm, "start over").
|
||||
cancelAllPremoves(context: any, payload: { seat: number }) {},
|
||||
// Phase 3 (§10.4), priority mode only.
|
||||
reorderPremove(context: any, payload: { seat: number; seq: number; direction: "up" | "down" }) {},
|
||||
markPremoveFailureRead(context: any, id: string) {},
|
||||
// Premove cancel triggers - same "no body, forwarded by launcher.ts's subscribeAction" shape.
|
||||
armCancelTrigger(
|
||||
context: any,
|
||||
payload: {
|
||||
seat: number;
|
||||
watchedSeat: number;
|
||||
move: string;
|
||||
atoms: string[];
|
||||
kind: CancelTriggerKind;
|
||||
config: CancelTriggerLeechConfig | Record<string, never>;
|
||||
}
|
||||
) {},
|
||||
disarmCancelTrigger(context: any, payload: { seat: number; seq: number }) {},
|
||||
disarmAllCancelTriggers(context: any, payload: { seat: number }) {},
|
||||
editCancelTrigger(
|
||||
context: any,
|
||||
payload: {
|
||||
seat: number;
|
||||
seq: number;
|
||||
move: string;
|
||||
atoms: string[];
|
||||
config: CancelTriggerLeechConfig | Record<string, never>;
|
||||
}
|
||||
) {},
|
||||
submitPlan(context: any, command: PremoveCommand) {},
|
||||
replayInfo(context: any, info: { start: number; end: number; current: number }) {},
|
||||
// ^ up - down v
|
||||
externalData(context: any, data: Engine) {},
|
||||
|
|
|
|||
|
|
@ -739,33 +739,12 @@ kbd {
|
|||
background-color: var(--ui-surface-muted);
|
||||
}
|
||||
|
||||
// The map renders without a card background by owner request (2026-09) - the space between
|
||||
// sectors is the page's own background again, like the pre-Lost-Fleet viewer. Only the
|
||||
// analysis-mode hazard overlay (below) still paints on this element.
|
||||
// The space between sectors uses the page background, including while planning.
|
||||
.space-map,
|
||||
.space-map-canvas {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
// Analysis mode (docs/lost-fleet/ANALYSIS_MODE_PLAN.md §5.2/§2.10) - dimmed yellow/black hazard
|
||||
// stripes, much lower contrast than Commands.vue's header treatment, read through the SVG's
|
||||
// transparent inter-sector gaps and frame the board as "not live" without fighting planet colours
|
||||
// over what can be a long session. Scoped under .analysis-mode-active (Game.vue's own root class
|
||||
// while analysisMode is true) - the .space-map/.space-map-canvas rule above is shared with setup
|
||||
// and open-game previews, so an unscoped rule here would hazard-tape every one of those too.
|
||||
// Layered as background-image on top of the existing background-color rather than overriding it,
|
||||
// so this is purely additive.
|
||||
.analysis-mode-active .space-map,
|
||||
.analysis-mode-active .space-map-canvas {
|
||||
background-image: repeating-linear-gradient(
|
||||
45deg,
|
||||
rgba(245, 197, 24, 0.13) 0px,
|
||||
rgba(245, 197, 24, 0.13) 16px,
|
||||
rgba(20, 20, 20, 0.13) 16px,
|
||||
rgba(20, 20, 20, 0.13) 32px
|
||||
);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .space-map .space-hex,
|
||||
:root[data-theme="dark"] .space-map-canvas .space-hex {
|
||||
stroke: #7a879d;
|
||||
|
|
@ -785,50 +764,3 @@ kbd {
|
|||
.space-map__chart-button {
|
||||
filter: var(--ui-map-icon-filter);
|
||||
}
|
||||
|
||||
// Analysis mode's map-corner button (§5.4) - the bottom-right mirror of the chart icon above.
|
||||
// Neutral (ui-surface/ui-border/ui-text-muted) while merely offered, so it doesn't read as a
|
||||
// warning before anything is actually happening; switches to the same warning tokens the striped
|
||||
// header/AnalysisPanel already use for the active state, tying the corner control to the rest of
|
||||
// the feature's established visual language.
|
||||
.space-map__analysis-button {
|
||||
cursor: pointer;
|
||||
|
||||
.space-map__analysis-badge {
|
||||
fill: var(--ui-surface);
|
||||
stroke: var(--ui-border);
|
||||
stroke-width: 1;
|
||||
transition:
|
||||
fill 0.1s ease-out,
|
||||
stroke 0.1s ease-out;
|
||||
}
|
||||
|
||||
color: var(--ui-text-muted);
|
||||
|
||||
&:hover .space-map__analysis-badge {
|
||||
stroke: var(--ui-border-strong);
|
||||
}
|
||||
}
|
||||
|
||||
.space-map__analysis-button--active {
|
||||
color: var(--ui-warning-text);
|
||||
|
||||
.space-map__analysis-badge {
|
||||
fill: var(--ui-warning-bg);
|
||||
stroke: var(--ui-warning-border);
|
||||
}
|
||||
|
||||
&:hover .space-map__analysis-badge {
|
||||
stroke: var(--ui-warning-border);
|
||||
}
|
||||
}
|
||||
|
||||
// Undo/Reset with nothing in the line yet. They stay on screen rather than disappearing (so the
|
||||
// toggle beside them never jumps sideways the moment the first sandbox move lands) but must not
|
||||
// look or behave pressable - `pointer-events: none` also stops the hover rule above lighting them
|
||||
// up, which on its own would read as "this does something".
|
||||
.space-map__analysis-button--inert {
|
||||
cursor: default;
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue