Connect Harass & Withdraw to the battle preview

The independent Ecaz Treachery variant now supports Harass in either physical battle-card slot. A category-null Prescience answer keeps its identity private without erasing the selected card. Exact undialed normal/elite counters return before battle losses; opposing successful Traitors cancel withdrawal, ordinary leader deaths still resolve, and the card is discarded exactly once. Controls, all four AI profiles and saved continuation share the same physical quote. Existing Planetologist inspection and literal Truthtrance slot promises retain their meanings.

Unique Basic/Advanced physical allocations are supported. Ambiguous allocations, co-present Ecaz allied armies on either side, Richese card-family configurations and other optional modules remain gated before sealing from public/own context. The pending Stone Burner timing question is not assumed answered. Reveal-before-explosion order and mandatory disposal on an own-Traitor win are explicit source-timing/specificity inferences, consistent with existing Planetologist precedence. Reinforcements and full variant/public mode acceptance remain unfinished.

Independent rules/privacy/persistence review fixed asymmetric selector legality, misleading blocked-card guidance, invalid restored battle pairs, native-only inspection bypass and unsupported allied-army admission. Ixian fixtures preserve all seven physical cyborgs. The first broad run caught a semantic-status lint error in the blocked guidance; replacing the paragraph role with an output element fixed it. A subsequent broad run passed 4,775 of 4,776 tests and exposed an old UI assertion requiring category-null slots to be disabled. The updated regression verifies enabled category-null selectors exclude ordinary held cards, while exact leader/dial locks and submitted values remain bound; focused controls pass 14/14. No game source changed after the eight samples or browser replay. Types, lint, 4776 offline tests, build and 43 HTTP tests pass with unchanged source. Authenticated SQLite cases verify sealed private restoration and competing duplicate traitor actions with one physical resolution.

Eight fixed genuine six-seat games finish: basic/Easy: 1803 actions, 0 Harass plans, 0 withdrawals, 48 periodic restores; basic/Medium: 225 actions, 0 Harass plans, 0 withdrawals, 6 periodic restores; basic/Hard: 2184 actions, 1 Harass plans, 1 withdrawals, 59 periodic restores; basic/Brutal: 2073 actions, 1 Harass plans, 1 withdrawals, 56 periodic restores; advanced/Easy: 2057 actions, 1 Harass plans, 1 withdrawals, 55 periodic restores; advanced/Medium: 532 actions, 0 Harass plans, 0 withdrawals, 14 periodic restores; advanced/Hard: 538 actions, 0 Harass plans, 0 withdrawals, 14 periodic restores; advanced/Brutal: 544 actions, 0 Harass plans, 0 withdrawals, 14 periodic restores. All 218 game-source files match their source-stable runs; exact card/traitor/force custody and periodic/terminal private views are checked. Browser controls verify the full card, category None, Defense-first legality, actual sealing/reveal, four returned forces, ordinary leader death, disposal and refresh. A separate final-source replay verifies the conserved browser fixture and opposing continuation, including Face Dancer replacement. This is bounded playability evidence, not full compliance or AI calibration.

All 936 opening games and their original seat/recovery records remain unchanged (970 after checks); all 937 present immediately before checks are also preserved. Database integrity and foreign keys pass. The healthy server was reused after the power failure without restart, reset or recurring automation.

Verified source tree: be193613c455c5b76b49800fe3a7400504ea879af34c59621ade3d44f0fe019d
This commit is contained in:
Quintine committed 2026-09-14 04:41:30 +10:00
1 parent c04cb93830
commit 04501567d0
26 files changed
+2164 -127

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { baseDeck, treacheryDeck } from '../game/cards';
import { ecazTreacheryCards } from '../game/ecaz-cards';
import {
battleCardSlotEligible,
battleCategoryInspectionValue,
fixedBattleInspectionMatches,
validBattleSlotPair,
} from '../game/battle-card-slots';
const ecaz = Object.fromEntries(ecazTreacheryCards().map((card) => [card.effect, card]));
const base = baseDeck();
const projectile = base.find((card) => card.kind === 'projectile')!;
const shield = base.find((card) => card.kind === 'shield')!;
const worthless = base.find((card) => card.kind === 'worthless')!;
const hajr = base.find((card) => card.effect === 'hajr')!;
void test('slot specials preserve single-card custody and alternate-role category requirements', () => {
const cards = treacheryDeck(['ix']);
const chemistry = cards.find((card) => card.kind === 'chemistry')!;
const weirding = cards.find((card) => card.kind === 'weirdingWay')!;
assert.equal(validBattleSlotPair(ecaz.harassWithdraw, shield), true);
assert.equal(validBattleSlotPair(projectile, ecaz.harassWithdraw), true);
assert.equal(validBattleSlotPair(ecaz.harassWithdraw, ecaz.harassWithdraw), false);
assert.equal(validBattleSlotPair(ecaz.recruits, shield), false);
assert.equal(validBattleSlotPair(ecaz.harassWithdraw, weirding), false);
assert.equal(validBattleSlotPair(chemistry, ecaz.harassWithdraw), false);
assert.equal(validBattleSlotPair(weirding, ecaz.harassWithdraw), true);
assert.equal(validBattleSlotPair(ecaz.harassWithdraw, chemistry), true);
assert.equal(validBattleSlotPair(chemistry, weirding), true);
assert.equal(validBattleSlotPair(hajr, shield, true), true);
assert.equal(validBattleSlotPair(hajr, weirding, true), false);
});
void test('only the two exact canonical Ecaz battle specials occupy either slot', () => {
for (const effect of ['reinforcements', 'harassWithdraw'] as const) {
assert.equal(battleCardSlotEligible('weapon', ecaz[effect]), true);
assert.equal(battleCardSlotEligible('defense', ecaz[effect]), true);
}
for (const forged of [
ecaz.recruits,
{ ...ecaz.reinforcements, name: 'Forged Reinforcements' },
{ ...ecaz.harassWithdraw, extra: true },
{ ...ecaz.reinforcements, id: 'similar-reinforcements' },
]) {
assert.equal(battleCardSlotEligible('weapon', forged), false);
assert.equal(battleCardSlotEligible('defense', forged), false);
}
});
void test('ordinary categories and externally validated Planetologist substitution remain unchanged', () => {
assert.equal(battleCardSlotEligible('weapon', undefined), true);
assert.equal(battleCardSlotEligible('defense', undefined), true);
assert.equal(battleCardSlotEligible('weapon', projectile), true);
assert.equal(battleCardSlotEligible('defense', projectile), false);
assert.equal(battleCardSlotEligible('weapon', shield), false);
assert.equal(battleCardSlotEligible('defense', shield), true);
assert.equal(battleCardSlotEligible('weapon', worthless), true);
assert.equal(battleCardSlotEligible('defense', worthless), true);
assert.equal(battleCardSlotEligible('weapon', hajr), false);
assert.equal(battleCardSlotEligible('weapon', hajr, { planetologistWeapon: true }), true);
assert.equal(battleCardSlotEligible('defense', hajr, { planetologistWeapon: true }), false);
});
void test('category inspection hides Ecaz slot occupants without changing existing Planetologist or ordinary answers', () => {
assert.equal(
battleCategoryInspectionValue('weapon', ecaz.reinforcements.id, ecaz.reinforcements),
null,
);
assert.equal(
battleCategoryInspectionValue('defense', ecaz.harassWithdraw.id, ecaz.harassWithdraw),
null,
);
assert.equal(battleCategoryInspectionValue('weapon', hajr.id, hajr), hajr.id);
assert.equal(battleCategoryInspectionValue('defense', worthless.id, worthless), worthless.id);
assert.equal(battleCategoryInspectionValue('weapon', projectile.id, projectile), projectile.id);
assert.equal(battleCategoryInspectionValue('weapon', ecaz.recruits.id, ecaz.recruits), ecaz.recruits.id);
});
void test('non-card fields, empty slots and unfinished partial values preserve their exact shape', () => {
assert.equal(battleCategoryInspectionValue('dial', 2.5), 2.5);
assert.equal(battleCategoryInspectionValue('leader', 'atreides-0'), 'atreides-0');
assert.equal(battleCategoryInspectionValue('weapon', null), null);
assert.equal(battleCategoryInspectionValue('defense', undefined), undefined);
assert.throws(
() => battleCategoryInspectionValue('weapon', projectile.id, shield),
/does not match/,
);
});
void test('fixed category comparisons keep partial search open and compare resolved category values', () => {
assert.equal(fixedBattleInspectionMatches('weapon', null, undefined), true);
assert.equal(
fixedBattleInspectionMatches('weapon', null, ecaz.reinforcements.id, ecaz.reinforcements),
true,
);
assert.equal(fixedBattleInspectionMatches('weapon', null, projectile.id, projectile), false);
assert.equal(
fixedBattleInspectionMatches('defense', worthless.id, worthless.id, worthless),
true,
);
assert.equal(fixedBattleInspectionMatches('dial', 3.5, 3.5), true);
assert.equal(fixedBattleInspectionMatches('leader', 'atreides-0', null), false);
});
+84
View File
@@ -0,0 +1,84 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { applyAction, viewGame, type Action, type Game } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES, type Difficulty } from '../game/bot-profiles';
import { baseDeck } from '../game/cards';
import { quoteHarassWithdraw } from '../game/harass-withdraw';
import { harassWithdrawGame, harassCustody, takeHarassCard } from './fixture-harass-withdraw';
function projection(game: Game, profile: Difficulty) {
const view = viewGame(game, 'a');
view.players.find(player => player.id === 'a')!.bot = profile;
return view;
}
const usesHarass = (action: Action) =>
action.weapon === 'ecaz-harass-withdraw' || action.defense === 'ecaz-harass-withdraw';
void test('each AI profile can commit Harass in either slot through genuine Basic and Advanced battle setup', () => {
for (const advanced of [false, true]) for (const profile of DIFFICULTIES) {
const game = harassWithdrawGame({ advanced });
const view = projection(game, profile), before = structuredClone(view);
const candidates = botActions(view).filter(action => action.type === 'battlePlan' && usesHarass(action));
assert.deepEqual(view, before);
assert.ok(candidates.length, `${profile}/${advanced} omitted Harass`);
for (const slot of ['weapon', 'defense'] as const) {
const action = candidates.find(action => action[slot] === 'ecaz-harass-withdraw');
assert.ok(action, `${profile}/${advanced} omitted ${slot}`);
quoteHarassWithdraw(view.battle!.harassWithdraw!, Number(action.dial), Number(action.support ?? 0));
const sealed = applyAction(game, 'a', action);
assert.equal(sealed.battle!.plans.a[slot], 'ecaz-harass-withdraw');
harassCustody(sealed);
}
assert.ok(candidates.every(action => action.weapon !== 'ecaz-reinforcements' && action.defense !== 'ecaz-reinforcements'));
}
});
void test('all profiles answer category inspections without revealing Harass and can keep it in a committed empty-category slot', () => {
for (const profile of DIFFICULTIES) {
let game = harassWithdrawGame({ prepare: false });
for (let step = 0; game.response && step < 10; step++) {
const id = game.players.find(player => !game.response!.passed.includes(player.id))!.id;
game = applyAction(game, id, { type: 'passResponse' });
}
assert.equal(game.battle!.preparation?.kind, 'prescience');
game = applyAction(game, 'd', { type: 'prescience', field: 'weapon' });
const answers = botActions(projection(game, profile));
assert.ok(answers.length);
assert.ok(answers.every(action => action.type === 'prescienceAnswer' && action.value === null));
game = applyAction(game, 'a', answers[0]);
const view = projection(game, profile);
const action = botActions(view).find(action => action.type === 'battlePlan' && action.weapon === 'ecaz-harass-withdraw');
assert.ok(action, `${profile} erased the inspected slot occupant`);
const sealed = applyAction(game, 'a', action);
assert.equal(sealed.battle!.prescience!.value, null);
assert.equal(viewGame(sealed, 'd').battle!.insight!.value, null);
assert.equal(viewGame(sealed, 't').battle!.harassWithdraw, null);
harassCustody(sealed);
}
});
void test('hidden opponent card swaps leave the Harass planner input and actions identical', () => {
const game = harassWithdrawGame();
takeHarassCard(game, 'd', baseDeck()[0].id);
takeHarassCard(game, 't', baseDeck()[1].id);
const changed = structuredClone(game);
[changed.players[1].hand[0], changed.players[2].hand[0]] = [changed.players[2].hand[0], changed.players[1].hand[0]];
for (const profile of DIFFICULTIES) {
const before = projection(game, profile), after = projection(changed, profile);
assert.deepEqual(after, before);
assert.deepEqual(botActions(after), botActions(before));
}
harassCustody(changed);
});
void test('the planner excludes a publicly blocked Harass module without reading opposing holdings', () => {
const game = harassWithdrawGame();
for (const profile of DIFFICULTIES) {
const view = projection(game, profile);
view.battle!.harassWithdraw = { ...view.battle!.harassWithdraw!, blocked: 'This configured card combination awaits a ruling.' };
const actions = botActions(view);
assert.ok(actions.length);
assert.ok(actions.every(action => !usesHarass(action)));
}
});
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { registerHooks } from 'node:module';
import { readFileSync } from 'node:fs';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { createGame, newPlayer, viewGame, type GameView } from '../game/engine';
import { baseDeck, ixBattleCards } from '../game/cards';
import { ecazTreacheryCards } from '../game/ecaz-cards';
import { battlePlanCardValue, battlePlanCardOptions, bindBattlePlanCommitments, BattlePreparation } from '../components/battle-preparation';
import { harassWithdrawControlState, HarassWithdrawGuide } from '../components/harass-withdraw';
const aliases = registerHooks({
resolve(specifier, context, next) {
return next(specifier === 'next/image' ? 'vinext/shims/image' : specifier === 'next/link' ? 'vinext/shims/link' : specifier, context);
},
load(url, context, next) {
if (!url.endsWith('.module.css')) return next(url, context);
const css = readFileSync(new URL(url), 'utf8');
const classes = Object.fromEntries([...css.matchAll(/\.([a-zA-Z_][\w-]*)/g)].map(match => [match[1], match[1]]));
return { format: 'module', source: `export default ${JSON.stringify(classes)}`, shortCircuit: true };
},
});
const { GameTable } = await import('../components/game-table');
aliases.deregister();
const harass = ecazTreacheryCards().find(card => card.effect === 'harassWithdraw')!;
const projectile = baseDeck().find(card => card.kind === 'projectile')!;
// Rendering fixture only; engine and recovery tests earn these projections.
function fixture(): GameView {
const g = createGame('ECAZBATTLEUI', newPlayer('a', 'Atreides', 'atreides'));
g.players.push(newPlayer('h', 'Harkonnen', 'harkonnen'));
Object.assign(g, { status: 'playing', phase: 6, turn: 2, storm: 18, active: 'a', order: ['a', 'h'] });
g.deck = baseDeck();
for (const player of g.players) {
player.hand = [];
player.forces = { 'arrakeen:10': 4 };
player.reserves = 16;
player.spice = 10;
player.traitors = [];
}
g.battle = { event: 'battle-ecaz-ui', territory: 'arrakeen', attacker: 'a', defender: 'h',
prepared: true, plans: {}, revealed: false, traitorCalls: {} };
const view = viewGame(g, 'h');
view.players[1].hand = [projectile, ...ecazTreacheryCards()];
view.battle!.harassWithdraw = {
card: 'ecaz-harass-withdraw', blocked: null,
forces: { normal: 4, elite: 0, eliteStrength: 1, freeSupport: true },
locations: { 'arrakeen:10': { normal: 4, elite: 0 } },
};
view.battle!.ownCommitments = [{ source: 'native', beneficiary: 'a', target: 'h', field: 'weapon', value: null }];
return view;
}
void test('a no-category inspection preserves a selected Harass card while binding other committed elements', () => {
const view = fixture();
view.battle!.ownCommitments.push({ source: 'nexus', beneficiary: 'a', target: 'h', field: 'dial', value: 2 });
const action = { type: 'battlePlan', dial: 0, leader: 'harkonnen-0', weapon: harass.id, defense: null };
assert.equal(battlePlanCardValue(view, 'weapon', harass.id), harass.id);
assert.deepEqual(bindBattlePlanCommitments(view, action), { ...action, dial: 2 });
assert.equal(action.dial, 0);
assert.equal(bindBattlePlanCommitments(view, { ...action, weapon: projectile.id }).weapon, null);
assert.equal(bindBattlePlanCommitments(view, { ...action, weapon: 'unknown-card' }).weapon, null);
view.players[1].hand = [{ ...harass, name: 'Forged card' }];
assert.equal(bindBattlePlanCommitments(view, action).weapon, null);
});
void test('named card inspections still lock their exact physical card, including existing Planetologist behavior', () => {
const view = fixture();
const atomics = baseDeck().find(card => card.effect === 'atomics')!;
view.players[1].hand!.push(atomics);
for (const card of [projectile, atomics]) {
view.battle!.ownCommitments[0].value = card.id;
assert.equal(battlePlanCardValue(view, 'weapon', harass.id), card.id);
assert.equal(bindBattlePlanCommitments(view, { type: 'battlePlan', weapon: harass.id }).weapon, card.id);
}
});
void test('the table keeps a no-category slot selectable and offers Harass without unfinished Reinforcements', () => {
const view = fixture();
const html = renderToStaticMarkup(createElement(GameTable, { game: view, send: async () => {}, onExit() {}, busy: false }));
const select = html.match(/<select[^>]*id="battle-weapon"[^>]*>[\s\S]*?<\/select>/)?.[0];
assert.ok(select);
assert.doesNotMatch(select, /disabled|ecaz-reinforcements|ecaz-recruits|value="treachery-/);
assert.match(select, /value="ecaz-harass-withdraw"/);
assert.match(html, /Harass and Withdraw battle guidance/);
});
void test('the category answer control explains None without exposing a special as a named answer', () => {
const view = fixture();
view.battle!.preparation = { kind: 'prescienceAnswer', owner: 'h', beneficiary: 'a' };
view.battle!.prescience = { player: 'a', field: 'weapon', answered: false };
const html = renderToStaticMarkup(createElement(BattlePreparation, { game: view, send: async () => {}, busy: false }));
assert.match(html, /Choose None/);
assert.doesNotMatch(html, /<option[^>]*value="ecaz-/);
view.battle!.harassWithdraw = { ...view.battle!.harassWithdraw!, blocked: 'This card combination awaits a ruling.' };
const blocked = renderToStaticMarkup(createElement(BattlePreparation, { game: view, send: async () => {}, busy: false }));
assert.doesNotMatch(blocked, /Choose None/);
});
void test('choosing Harass in Defense first excludes a duplicate physical card and Chemistry from Weapon', () => {
const view = fixture();
view.battle!.ownCommitments = [];
const chemistry = ixBattleCards().find(card => card.kind === 'chemistry')!;
view.players[1].hand!.push(chemistry);
const choices = battlePlanCardOptions(view, 'weapon', 'harkonnen-0', '', harass.id);
assert.ok(choices.some(card => card.id === projectile.id));
assert.ok(!choices.some(card => card.id === harass.id || card.id === chemistry.id));
assert.ok(battlePlanCardOptions(view, 'weapon', 'harkonnen-0', '', chemistry.id).some(card => card.id === harass.id));
});
void test('the guide uses the physical return quote and gives an actionable reason for unsupported commitments', () => {
const preview = fixture().battle!.harassWithdraw!;
const state = harassWithdrawControlState(preview, true, 1, 0);
assert.deepEqual(state.returned, { normal: 3, elite: 0 });
const html = renderToStaticMarkup(createElement(HarassWithdrawGuide, { preview, state }));
assert.match(html, /Return 3 ordinary and 0 elite/);
assert.match(html, /successful traitor call cancels/);
assert.equal(harassWithdrawControlState(preview, false, 1, 0).blocked, null);
assert.ok(harassWithdrawControlState(preview, true, 1.5, 0).blocked);
const blocked = { ...preview, blocked: 'Finish the unsupported combined module first.' };
assert.equal(harassWithdrawControlState(blocked, true, 1, 0).blocked, blocked.blocked);
});
+221
View File
@@ -0,0 +1,221 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { DatabaseSync } from "node:sqlite";
import { viewGame, type Action, type Game } from "../game/engine";
import type { RoomsClock } from "../db/rooms";
import { unitStore } from "./fixture-nexus-room-store";
import { harassCustody, harassWithdrawGame } from "./fixture-harass-withdraw";
const clock: RoomsClock = { now: () => 83000, sleep: async () => {} };
const rows = (sqlite: DatabaseSync) => ({
rooms: sqlite.prepare("SELECT * FROM rooms ORDER BY code").all(),
seats: sqlite.prepare("SELECT * FROM seats ORDER BY player_id").all(),
});
async function fixture(t: test.TestContext, advanced: boolean) {
const store = unitStore();
t.after(() => store.sqlite.close());
const made = await store.rooms.createRoom(
"Ecaz battle recovery",
"emperor",
advanced,
["ix"],
);
const code = made.view.code;
const tokens = [
made.token,
(await store.rooms.joinRoom(code, "Atreides", "atreides")).token!,
(await store.rooms.joinRoom(code, "Tleilaxu", "tleilaxu")).token!,
];
const auths = await Promise.all(
tokens.map((token) => store.rooms.authenticate(code, token)),
);
const ids = auths.map((auth) => auth.playerId) as [string, string, string];
const game = harassWithdrawGame({
advanced,
ids,
factions: ["emperor", "atreides", "tleilaxu"],
prepare: false,
});
game.code = code;
game.version = (await store.rooms.readRoom(code)).version;
harassCustody(game);
store.sqlite
.prepare("UPDATE rooms SET state=?, version=? WHERE code=?")
.run(JSON.stringify(game), game.version, code);
store.writes.length = 0;
return { ...store, code, tokens, auths, ids };
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
async function act(f: Fixture, player: string, action: Action) {
const rooms = f.restart();
const index = f.ids.indexOf(player);
assert.ok(index >= 0);
const auth = await rooms.authenticate(f.code, f.tokens[index]);
const before = await rooms.readRoom(f.code);
await rooms.act(f.code, auth, before.version, action, clock);
const after = await rooms.readRoom(f.code);
harassCustody(after);
return after;
}
async function restored(f: Fixture) {
const game = await f.restart().readRoom(f.code);
const before = rows(f.sqlite);
for (const [index, token] of f.tokens.entries()) {
const rooms = f.restart();
const auth = await rooms.authenticate(f.code, token);
const view = await rooms.readSeatView(f.code, auth);
assert.deepEqual(view, viewGame(game, f.ids[index]));
assert.deepEqual(
view,
viewGame(JSON.parse(JSON.stringify(game)) as Game, f.ids[index]),
);
for (const rival of view.players.filter((p) => p.id !== auth.playerId))
for (const field of ["hand", "traitors", "spice", "faceDancers"])
assert.equal(field in rival, false);
}
assert.deepEqual(rows(f.sqlite), before);
harassCustody(game);
return game;
}
async function declineFullPlanOffer(f: Fixture) {
const game = await f.restart().readRoom(f.code);
if (game.decision?.kind === "fullPlanOffer")
await act(f, game.decision.player, { type: "decision", decline: true });
}
void test("sealed Harass plan and category-null Prescience survive authenticated private restoration", async (t) => {
for (const advanced of [false, true]) {
const f = await fixture(t, advanced);
await act(f, f.ids[1], { type: "prescience", field: "weapon" });
await act(f, f.ids[0], { type: "prescienceAnswer", value: null });
await declineFullPlanOffer(f);
const sealed = await act(f, f.ids[0], {
type: "battlePlan",
dial: 1,
support: 0,
leader: "emperor-0",
weapon: "ecaz-harass-withdraw",
defense: null,
});
assert.equal(sealed.battle?.plans[f.ids[0]].weapon, "ecaz-harass-withdraw");
assert.equal(sealed.battle?.prescience?.value, null);
const restoredGame = await restored(f);
const atreides = viewGame(restoredGame, f.ids[1]).battle!;
assert.deepEqual(atreides.insight, {
field: "weapon",
value: null,
label: "None",
});
assert.deepEqual(atreides.plans, {});
const observer = viewGame(restoredGame, f.ids[2]).battle!;
assert.equal(observer.insight, null);
assert.deepEqual(observer.plans, {});
assert.deepEqual(observer.cards, []);
assert.equal(
JSON.stringify(observer).includes("ecaz-harass-withdraw"),
false,
);
}
});
void test("competing final traitor declines resolve one withdrawal and one discard after restart", async (t) => {
for (const advanced of [false, true]) {
const f = await fixture(t, advanced);
const seatRows = rows(f.sqlite).seats;
await act(f, f.ids[1], { type: "prescience", field: "weapon" });
await act(f, f.ids[0], { type: "prescienceAnswer", value: null });
await declineFullPlanOffer(f);
await act(f, f.ids[0], {
type: "battlePlan",
dial: 1,
support: advanced ? 1 : 0,
leader: "emperor-0",
weapon: "ecaz-harass-withdraw",
defense: null,
});
await act(f, f.ids[1], {
type: "battlePlan",
dial: 1,
support: advanced ? 1 : 0,
leader: "atreides-0",
weapon: null,
defense: null,
});
await act(f, f.ids[0], { type: "traitorCall", call: false });
const rooms = f.restart();
const auth = await rooms.authenticate(f.code, f.tokens[1]);
const before = await rooms.readRoom(f.code);
const writeStart = f.writes.length;
let entered = 0;
let release!: () => void;
const both = new Promise<void>((resolve) => {
release = resolve;
});
f.hooks.beforeWrite = async () => {
if (++entered === 2) release();
await both;
};
const attempts = await Promise.allSettled(
[0, 1].map(() =>
rooms.act(
f.code,
auth,
before.version,
{ type: "traitorCall", call: false },
clock,
),
),
);
f.hooks.beforeWrite = undefined;
assert.equal(
attempts.filter((result) => result.status === "fulfilled").length,
1,
);
assert.deepEqual(
f.writes
.slice(writeStart)
.map((write) => write.changes)
.sort((a, b) => a - b),
[0, 1],
);
const resolved = await restored(f);
assert.equal(resolved.version, before.version + 1);
assert.equal(resolved.battle, null);
assert.equal(resolved.decision?.kind, "faceDance");
assert.equal(resolved.players[0].reserves, 19);
assert.equal(resolved.players[0].tanks, 1);
assert.deepEqual(resolved.players[0].forces, {});
assert.equal(
resolved.discard.filter((card) => card.id === "ecaz-harass-withdraw")
.length,
1,
);
assert.equal(
resolved.log.filter((entry) =>
entry.text.includes("used Harass & Withdraw to return 4"),
).length,
1,
);
await act(f, f.ids[2], { type: "decision", reveal: false });
const terminal = await restored(f);
assert.equal(terminal.battle, null);
assert.equal(terminal.decision, null);
assert.equal(terminal.response, null);
assert.equal(terminal.pendingTreacheryDiscard, null);
assert.equal(terminal.phase, 7);
assert.equal(
terminal.discard.filter((card) => card.id === "ecaz-harass-withdraw")
.length,
1,
);
assert.deepEqual(rows(f.sqlite).seats, seatRows);
}
});
+4 -3
View File
@@ -123,7 +123,7 @@ void test('verified inventory and source rules remain distinct from unimplemente
assert.equal(definition.verification.sourceRules, 'verified');
assert.equal(
definition.verification.runtime,
definition.card.effect === 'recruits' ? 'prototype' : 'not-implemented',
definition.card.effect === 'reinforcements' ? 'not-implemented' : 'prototype',
);
assert.equal(definition.verification.combinedInteractions, 'incomplete');
assert.ok(definition.verification.unresolved.length > 0);
@@ -154,9 +154,10 @@ void test('every canonical Ecaz face receives its full original gameplay guide a
assert.equal(serialized.includes(note), false);
assert.equal(serialized.includes('sourceRules'), false);
assert.equal(serialized.includes('not-implemented'), false);
assert.deepEqual(presentation.topics.map((topic) => topic.id), ['card-recruits']);
assert.deepEqual(presentation.topics.map((topic) => topic.id), [card.effect === 'harassWithdraw' ? 'card-harass-withdraw' : 'card-recruits']);
assert.match(presentation.availability ?? '', card.effect === 'recruits'
? /development controls during Revival/ : /battle effect is still being implemented/);
? /development controls during Revival/ : card.effect === 'harassWithdraw'
? /development controls in either battle-card slot/ : /battle effect is still being implemented/);
}
});
+186
View File
@@ -0,0 +1,186 @@
import assert from 'node:assert/strict';
import {
applyAction,
createGame,
initializeEcazTreacheryGameForAudit,
joinGame,
newPlayer,
viewGame,
type Game,
} from '../game/engine';
import { botActions } from '../game/bots';
import { treacheryDeck, type Card } from '../game/cards';
import { faction, type FactionId } from '../game/catalog';
import { ecazTreacheryCards } from '../game/ecaz-cards';
import { traitorDeck } from '../game/traitors';
export function takeHarassCard(g: Game, owner: string, cardId: string): Card {
const target = g.players.find((p) => p.id === owner)!;
for (const zone of [g.deck, g.discard, ...g.players.map((p) => p.hand)]) {
const index = zone.findIndex((c) => c.id === cardId);
if (index < 0) continue;
const [card] = zone.splice(index, 1);
target.hand.push(card);
return card;
}
throw new Error(`Missing physical fixture card ${cardId}`);
}
export function finishHarassPreparation(game: Game): Game {
for (let count = 0; count < 60; count++) {
if (
game.battle?.preLeader &&
!game.battle.preLeader.closed &&
!game.response &&
!game.decision
) {
const player = [game.battle.attacker, game.battle.defender].find(
(id) => !game.battle!.preLeader!.ready.includes(id),
)!;
game = applyAction(game, player, {
type: 'battlePreparationReady',
event: game.battle.preLeader.event,
});
} else if (game.response) {
const player = game.players.find(
(p) => !game.response!.passed.includes(p.id),
)!;
game = applyAction(game, player.id, { type: 'passResponse' });
} else if (game.battle?.preparation) {
game = applyAction(game, game.battle.preparation.owner, {
type: 'declineBattlePower',
});
} else if (game.decision?.kind === 'fullPlanOffer') {
game = applyAction(game, game.decision.player, {
type: 'decision',
decline: true,
});
} else return game;
}
throw new Error('Battle preparation did not complete.');
}
/** Genuine variant setup; hands and Arrakeen losses/positions are explicitly staged with conserved pieces. */
export function harassWithdrawGame({
advanced = false,
factions = ['emperor', 'atreides', 'tleilaxu'] as readonly FactionId[],
ids = ['a', 'd', 't'] as readonly string[],
normal = 5,
elite = 0,
prepare = true,
territory = 'arrakeen',
sector = 10,
} = {}): Game {
assert.equal(factions.length, ids.length);
const expansions = [
...new Set(
factions.map((id) => faction(id).expansion).filter((id) => id !== 'base'),
),
] as ('ix' | 'choam' | 'ecaz')[];
let g = createGame(
'HARASSQA',
newPlayer(ids[0], factions[0], factions[0]),
advanced,
expansions,
);
factions
.slice(1)
.forEach((id, index) => joinGame(g, newPlayer(ids[index + 1], id, id)));
for (const player of g.players)
g = applyAction(g, player.id, { type: 'ready' });
g = initializeEcazTreacheryGameForAudit(g);
for (let step = 0; g.status === 'setup' && step < 80; step++) {
let next: Game | undefined;
for (const player of g.players) {
const view = viewGame(g, player.id);
view.players.find((p) => p.id === player.id)!.bot = 'Medium';
const action = botActions(view)[0];
if (action) {
next = applyAction(g, player.id, action);
break;
}
}
assert.ok(next);
g = next;
}
assert.equal(g.status, 'playing');
for (const [index, player] of g.players.entries()) {
g.deck.push(...player.hand);
player.hand = [];
const amount = index === 0 ? normal + elite : index === 1 ? 5 : 0;
player.forces = amount ? { [`${territory}:${sector}`]: amount } : {};
player.reserves = 20 - amount;
player.tanks = 0;
player.spice = 30;
player.battleLosses = 0;
if (player.elites) {
const total =
player.faction === 'emperor' ? 5 : player.faction === 'ixians' ? 7 : 3;
const selected = index === 0 ? elite : 0;
assert.ok(selected <= total);
player.elites = {
reserves: total - selected,
tanks: 0,
forces: selected ? { [`${territory}:${sector}`]: selected } : {},
revived: 0,
};
} else assert.ok(index !== 0 || !elite);
}
takeHarassCard(g, ids[0], 'ecaz-harass-withdraw');
Object.assign(g, {
turn: 2,
phase: 6,
storm: 18,
order: [...ids],
active: ids[0],
ready: [],
decision: null,
response: null,
phaseOpening: null,
});
g = applyAction(g, ids[0], {
type: 'chooseBattle',
territory,
target: ids[1],
});
return prepare ? finishHarassPreparation(g) : g;
}
export function harassCustody(g: Game) {
const cards = [...g.deck, ...g.discard, ...g.players.flatMap((p) => p.hand)];
assert.deepEqual(
cards.map((c) => c.id).sort(),
[...treacheryDeck(g.expansions), ...ecazTreacheryCards()]
.map((c) => c.id)
.sort(),
);
assert.deepEqual(
[
...(g.traitorReserve ?? []),
...g.players.flatMap((p) => [
...p.traitors,
...(p.faceDancers ?? []).map((c) => c.leader),
]),
].sort(),
traitorDeck(g.players, g.expansions.includes('ix')).sort(),
);
for (const p of g.players) {
assert.equal(
p.reserves + p.tanks + Object.values(p.forces).reduce((a, b) => a + b, 0),
20,
);
assert.ok(
[p.reserves, p.tanks, ...Object.values(p.forces)].every(
(n) => Number.isSafeInteger(n) && n >= 0,
),
);
if (p.elites) {
assert.equal(
p.elites.reserves +
p.elites.tanks +
Object.values(p.elites.forces).reduce((a, b) => a + b, 0),
p.faction === 'emperor' ? 5 : p.faction === 'ixians' ? 7 : 3,
);
assert.ok(p.elites.reserves <= p.reserves && p.elites.tanks <= p.tanks);
for (const [key, amount] of Object.entries(p.elites.forces))
assert.ok(amount <= (p.forces[key] ?? 0));
}
}
}
+718
View File
@@ -0,0 +1,718 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, viewGame, type Action, type Game } from '../game/engine';
import { quoteHarassWithdraw } from '../game/harass-withdraw';
import {
quoteBattleResolution,
type BattleResolutionInput,
} from '../game/battle-resolution-quote';
import {
finishHarassPreparation,
harassCustody,
harassWithdrawGame,
takeHarassCard,
} from './fixture-harass-withdraw';
const ownLeader = (g: Game) =>
[...g.players[0].leaders].sort((a, b) => b.strength - a.strength)[0].id;
const otherLeader = (g: Game) =>
[...g.players[1].leaders].sort((a, b) => a.strength - b.strength)[0].id;
function ownPlan(g: Game, extra: Partial<Action> = {}): Action {
return {
type: 'battlePlan',
dial: 2,
support: g.advanced ? 2 : 0,
leader: ownLeader(g),
defense: 'ecaz-harass-withdraw',
...extra,
};
}
function seal(
g: Game,
own: Partial<Action> = {},
other: Partial<Action> = {},
): Game {
g = applyAction(g, g.players[0].id, ownPlan(g, own));
return applyAction(g, g.players[1].id, {
type: 'battlePlan',
dial: 0,
support: 0,
leader: otherLeader(g),
...other,
});
}
function resolve(g: Game, own = false, other = false): Game {
g = applyAction(g, g.players[0].id, { type: 'traitorCall', call: own });
for (const p of g.players)
assert.deepEqual(
viewGame(JSON.parse(JSON.stringify(g)), p.id),
viewGame(g, p.id),
);
const before = JSON.stringify(g);
const done = applyAction(g, g.players[1].id, {
type: 'traitorCall',
call: other,
});
assert.equal(JSON.stringify(g), before);
harassCustody(done);
for (const p of done.players)
assert.deepEqual(
viewGame(JSON.parse(JSON.stringify(done)), p.id),
viewGame(done, p.id),
);
return done;
}
function reject(g: Game, player: string, action: Action, reason: RegExp) {
const before = JSON.stringify(g);
assert.throws(() => applyAction(g, player, action), reason);
assert.equal(JSON.stringify(g), before);
}
function setIdentity(
g: Game,
target: { get(): string; set(value: string): void },
identity: string,
) {
const entries = [
...(g.traitorReserve ?? []).map((_, i) => ({
get: () => g.traitorReserve![i],
set: (value: string) => {
g.traitorReserve![i] = value;
},
})),
...g.players.flatMap((p) => [
...p.traitors.map((_, i) => ({
get: () => p.traitors[i],
set: (value: string) => {
p.traitors[i] = value;
},
})),
...(p.faceDancers ?? []).map((_, i) => ({
get: () => p.faceDancers![i].leader,
set: (value: string) => {
p.faceDancers![i].leader = value;
},
})),
]),
];
const source = entries.find((entry) => entry.get() === identity)!;
assert.ok(source);
const old = target.get();
source.set(old);
target.set(identity);
}
function heldTraitor(g: Game, player: number, identity: string) {
const p = g.players[player];
setIdentity(
g,
{
get: () => p.traitors[0],
set: (value) => {
p.traitors[0] = value;
},
},
identity,
);
}
void test('Harass & Withdraw returns only undialed forces for Basic/Advanced winners and losers in either slot', () => {
for (const advanced of [false, true])
for (const slot of ['weapon', 'defense'])
for (const winning of [false, true]) {
let g = harassWithdrawGame({ advanced });
const start = g.players[0].reserves;
g = seal(
g,
slot === 'weapon'
? { weapon: 'ecaz-harass-withdraw', defense: null }
: {},
winning
? {}
: {
dial: 5,
support: advanced ? 5 : 0,
leader: g.players[1].leaders[0].id,
},
);
const done = resolve(g);
assert.equal(done.lastBattleContext?.winner, winning ? 'a' : 'd');
assert.equal(done.players[0].reserves, start + 3);
assert.equal(done.players[0].tanks, 2);
assert.deepEqual(done.players[0].forces, {});
assert.equal(
done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
assert.equal(
done.log.filter((entry) =>
entry.text.includes('used Harass & Withdraw'),
).length,
1,
);
assert.equal(
done.players[0].leaders.find((l) => l.id === ownLeader(g))!.dead,
false,
);
reject(
done,
'd',
{ type: 'traitorCall', call: false },
/battle|traitor|pending|response|Waiting|Resolve/i,
);
}
});
void test('zero dial and unique half-strength elite allocation preserve exact reserve and Tanks subpools', () => {
let g = harassWithdrawGame();
let done = resolve(seal(g, { dial: 0 }));
assert.equal(done.players[0].reserves, 20);
assert.equal(done.players[0].tanks, 0);
g = harassWithdrawGame({ advanced: true, normal: 1, elite: 2 });
const context = viewGame(g, 'a').battle!.harassWithdraw!;
const quote = quoteHarassWithdraw(context, 1, 0);
assert.deepEqual(quote.returned, { normal: 1, elite: 1 });
done = resolve(seal(g, { dial: 1, support: 0 }));
assert.equal(done.players[0].reserves, 19);
assert.equal(done.players[0].tanks, 1);
assert.equal(done.players[0].elites!.reserves, 4);
assert.equal(done.players[0].elites!.tanks, 1);
assert.deepEqual(done.players[0].elites!.forces, {});
});
void test('own successful traitor retains dialed forces but the used Harass card is a mandatory discard', () => {
let g = harassWithdrawGame({ advanced: true });
heldTraitor(g, 0, otherLeader(g));
harassCustody(g);
g = seal(g);
const done = resolve(g, true, false);
assert.equal(done.lastBattleContext?.result, 'traitor');
assert.equal(done.players[0].reserves, 18);
assert.equal(done.players[0].tanks, 0);
assert.deepEqual(done.players[0].forces, { 'arrakeen:10': 2 });
assert.equal(
done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
assert.equal(
done.players[0].spice,
30 + g.players[1].leaders.find((l) => l.id === otherLeader(g))!.strength,
);
});
void test('opposing and mutual traitor calls cancel withdrawal before forces return', () => {
for (const mutual of [false, true]) {
let g = harassWithdrawGame();
heldTraitor(g, 1, ownLeader(g));
if (mutual) heldTraitor(g, 0, otherLeader(g));
g = seal(g);
const done = resolve(g, mutual, true);
assert.equal(done.players[0].reserves, 15);
assert.equal(done.players[0].tanks, 5);
assert.equal(
done.log.filter((entry) =>
entry.text.includes('Harass & Withdraw was canceled'),
).length,
1,
);
assert.equal(
done.log.filter((entry) => entry.text.includes('used Harass & Withdraw'))
.length,
0,
);
assert.equal(
done.players[0].leaders.find((l) => l.id === ownLeader(g))!.dead,
true,
);
assert.equal(
done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
}
});
void test('weapon deaths and Lasgun/Shield explosion occur after undialed returns', () => {
let g = harassWithdrawGame();
const weapon = g.deck.find((c) => c.kind === 'projectile')!;
takeHarassCard(g, 'd', weapon.id);
let done = resolve(seal(g, {}, { weapon: weapon.id }));
assert.equal(done.players[0].reserves, 18);
assert.equal(done.players[0].tanks, 2);
assert.equal(
done.players[0].leaders.find((l) => l.id === ownLeader(g))!.dead,
true,
);
g = harassWithdrawGame({ advanced: true });
const shield = g.deck.find((c) => c.kind === 'shield')!,
lasgun = g.deck.find((c) => c.kind === 'lasgun')!;
takeHarassCard(g, 'a', shield.id);
takeHarassCard(g, 'd', lasgun.id);
g.players[2].forces = { 'arrakeen:10': 3 };
g.players[2].reserves -= 3;
done = resolve(
seal(
g,
{ weapon: 'ecaz-harass-withdraw', defense: shield.id },
{ weapon: lasgun.id },
),
);
assert.equal(done.lastBattleContext?.result, 'explosion');
assert.equal(done.players[0].reserves, 18);
assert.equal(done.players[0].tanks, 2);
assert.equal(done.players[1].tanks, 5);
assert.equal(done.players[2].tanks, 3);
assert.equal(done.players[2].reserves, 17);
assert.deepEqual(done.players[2].forces, {});
assert.equal(
done.players[0].leaders.find((l) => l.id === ownLeader(g))!.dead,
true,
);
assert.equal(
done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
});
void test('a later Face Dancer can replace only the dialed survivors, never returned reserves', () => {
let g = harassWithdrawGame();
heldTraitor(g, 0, otherLeader(g));
const t = g.players[2];
setIdentity(
g,
{
get: () => t.faceDancers![0].leader,
set: (value) => {
t.faceDancers![0].leader = value;
},
},
ownLeader(g),
);
g = resolve(seal(g), true, false);
assert.equal(g.decision?.kind, 'faceDance');
reject(
g,
't',
{ type: 'decision', reveal: true, sources: { reserves: 3 }, sector: 10 },
/more forces than the winner/,
);
g = applyAction(JSON.parse(JSON.stringify(g)), 't', {
type: 'decision',
reveal: true,
sources: { reserves: 2 },
sector: 10,
});
assert.equal(g.players[0].reserves, 20);
assert.equal(g.players[0].tanks, 0);
assert.equal(g.players[2].forces['arrakeen:10'], 2);
assert.equal(g.players[2].reserves, 18);
harassCustody(g);
});
void test('Harkonnen capture follows withdrawal and mandatory discard without recapturing returned counters', () => {
let g = harassWithdrawGame({
advanced: true,
factions: ['emperor', 'harkonnen', 'guild'],
});
const leader = [...g.players[0].leaders].sort(
(a, b) => a.strength - b.strength,
)[0].id;
const winnerLeader = [...g.players[1].leaders].sort(
(a, b) => b.strength - a.strength,
)[0].id;
g = resolve(
seal(g, { leader }, { dial: 5, support: 5, leader: winnerLeader }),
);
assert.equal(g.lastBattleContext?.winner, 'd');
assert.equal(g.players[0].leaders.find((l) => l.id === leader)!.dead, false);
assert.equal(g.players[0].reserves, 18);
assert.equal(g.players[0].tanks, 2);
assert.equal(
g.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
assert.equal(g.decision?.kind, 'captureOffer');
g = applyAction(JSON.parse(JSON.stringify(g)), 'd', {
type: 'decision',
accept: true,
});
while (g.response) {
const p = g.players.find((p) => !g.response!.passed.includes(p.id))!;
g = applyAction(g, p.id, { type: 'passResponse' });
}
assert.equal(g.decision?.kind, 'capturedLeader');
assert.equal(
g.players[0].leaders.filter((l) => l.capturedBy === 'd').length,
1,
);
for (const p of g.players)
assert.deepEqual(
viewGame(JSON.parse(JSON.stringify(g)), p.id),
viewGame(g, p.id),
);
g = applyAction(g, 'd', { type: 'decision', mode: 'keep' });
assert.equal(g.players[0].reserves, 18);
assert.equal(g.players[0].tanks, 2);
assert.equal(
g.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
harassCustody(g);
});
void test('Moritani ally retention excludes the used Harass card while preserving an ordinary played card', () => {
let g = harassWithdrawGame({ factions: ['emperor', 'atreides', 'moritani'] });
g.players[0].ally = 't';
g.players[2].ally = 'a';
const weapon = takeHarassCard(
g,
'a',
g.deck.find((c) => c.kind === 'projectile')!.id,
);
const shield = takeHarassCard(
g,
'd',
g.deck.find((c) => c.kind === 'shield')!.id,
);
g = resolve(
seal(
g,
{ weapon: weapon.id },
{
dial: 5,
leader: [...g.players[1].leaders].sort(
(a, b) => b.strength - a.strength,
)[0].id,
defense: shield.id,
},
),
);
assert.equal(g.lastBattleContext?.winner, 'd');
assert.equal(g.players[0].reserves, 18);
assert.equal(g.players[0].tanks, 2);
// The winner may still choose its ordinary discard before the ally benefit.
if (g.decision?.kind === 'battleCards')
g = applyAction(g, g.decision.player, { type: 'decision', discard: [] });
assert.equal(g.decision?.kind, 'moritaniRetention');
assert.deepEqual(g.moritaniRetention!.eligible, [weapon.id]);
reject(
g,
'a',
{ type: 'decision', keep: 'ecaz-harass-withdraw' },
/eligible|retain|Choose/i,
);
g = applyAction(JSON.parse(JSON.stringify(g)), 'a', {
type: 'decision',
keep: weapon.id,
});
while (g.response) {
const p = g.players.find((p) => !g.response!.passed.includes(p.id))!;
g = applyAction(g, p.id, { type: 'passResponse' });
}
assert.ok(g.players[0].hand.some((c) => c.id === weapon.id));
assert.equal(
g.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
harassCustody(g);
});
void test('co-present reciprocal Ecaz allies are publicly guarded before sealing either combat side', () => {
for (const side of [0, 1]) {
const g = harassWithdrawGame({ factions: ['emperor', 'atreides', 'ecaz'] });
g.players[side].ally = 't';
g.players[2].ally = g.players[side].id;
g.players[2].forces = { 'arrakeen:10': 3 };
g.players[2].reserves = 17;
assert.match(
viewGame(g, 'a').battle!.harassWithdraw!.blocked!,
/combined-army/,
);
reject(g, 'a', ownPlan(g), /combined-army/);
// The guard depends on the visible coalition, not its cards or leader choice.
const hidden = structuredClone(g);
takeHarassCard(
hidden,
'd',
hidden.deck.find((c) => c.kind === 'poison')!.id,
);
assert.deepEqual(
viewGame(hidden, 'a').battle!.harassWithdraw,
viewGame(g, 'a').battle!.harassWithdraw,
);
g.players[2].forces = {};
g.players[2].reserves = 20;
assert.equal(viewGame(g, 'a').battle!.harassWithdraw!.blocked, null);
assert.doesNotThrow(() => applyAction(g, 'a', ownPlan(g)));
harassCustody(g);
}
});
void test('ambiguous unit mixes and sector allocations reject before sealing without hidden opponent dependence', () => {
let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 });
reject(
g,
'a',
ownPlan(g, { dial: 2, support: 1 }),
/ambiguous regular\/elite/,
);
g = harassWithdrawGame({ territory: 'imperial_basin', sector: 9 });
g.players[0].forces = { 'imperial_basin:9': 2, 'imperial_basin:10': 3 };
const preview = viewGame(g, 'a').battle!.harassWithdraw!;
assert.throws(
() => quoteHarassWithdraw(preview, 2, 0),
/ambiguous allocation among sectors/,
);
reject(g, 'a', ownPlan(g), /ambiguous allocation among sectors/);
const hidden = structuredClone(g);
takeHarassCard(
hidden,
'd',
hidden.deck.find((c) => c.kind === 'projectile')!.id,
);
assert.deepEqual(viewGame(hidden, 'a').battle!.harassWithdraw, preview);
assert.doesNotThrow(() => applyAction(g, 'a', ownPlan(g, { dial: 0 })));
assert.doesNotThrow(() => applyAction(g, 'a', ownPlan(g, { dial: 5 })));
});
void test('Prescience binds no category while retaining the exact private Harass slot and ordinary reveal', () => {
let g = harassWithdrawGame({ prepare: false });
const named = takeHarassCard(
g,
'a',
g.deck.find((c) => c.kind === 'projectile')!.id,
);
assert.equal(g.battle?.preparation?.kind, 'prescience');
g = applyAction(g, 'd', { type: 'prescience', field: 'weapon' });
while (g.response) {
const next = g.players.find((p) => !g.response!.passed.includes(p.id))!;
g = applyAction(g, next.id, { type: 'passResponse' });
}
reject(
g,
'a',
{ type: 'prescienceAnswer', value: 'ecaz-harass-withdraw' },
/legal battle plan/,
);
g = applyAction(g, 'a', { type: 'prescienceAnswer', value: null });
g = finishHarassPreparation(g);
g = applyAction(
g,
'a',
ownPlan(g, { weapon: 'ecaz-harass-withdraw', defense: null }),
);
for (const player of ['a', 'd'])
assert.equal(viewGame(g, player).battle!.insight!.value, null);
const observer = viewGame(g, 't');
assert.equal(observer.battle!.insight, null);
assert.equal(observer.battle!.harassWithdraw, null);
assert.deepEqual(observer.battle!.plans, {});
assert.deepEqual(observer.battle!.cards, []);
const roundtrip = JSON.parse(JSON.stringify(g));
for (const p of g.players)
assert.deepEqual(viewGame(roundtrip, p.id), viewGame(g, p.id));
assert.equal(g.battle!.nexusInspection, undefined);
for (const change of ['replace', 'move', 'remove-field']) {
const corrupt: Game = JSON.parse(JSON.stringify(g));
corrupt.battle!.plans.a.weapon = named.id;
corrupt.battle!.plans.a.defense =
change === 'move' ? 'ecaz-harass-withdraw' : null;
if (change === 'remove-field')
Reflect.deleteProperty(corrupt.battle!.plans.a, 'weapon');
const before = JSON.stringify(corrupt);
for (const p of corrupt.players)
assert.throws(() => viewGame(corrupt, p.id), /inspected commitment/);
assert.equal(JSON.stringify(corrupt), before);
reject(
corrupt,
'a',
{ type: 'setAutopilot', difficulty: 'Easy' },
/inspected commitment/,
);
reject(
corrupt,
'd',
{ type: 'battlePlan', dial: 0, leader: otherLeader(g) },
/inspected commitment/,
);
}
g = applyAction(roundtrip, 'd', {
type: 'battlePlan',
dial: 0,
leader: otherLeader(g),
});
assert.equal(viewGame(g, 't').battle!.plans.a.weapon, 'ecaz-harass-withdraw');
assert.ok(
viewGame(g, 't').battle!.cards.some((c) => c.id === 'ecaz-harass-withdraw'),
);
resolve(g);
});
void test('saved Harass pairs cannot supply an actual defense for Chemistry or weapon for Weirding Way', () => {
for (const invalid of ['ix-chemistry', 'ix-weirding-way']) {
let g = harassWithdrawGame();
takeHarassCard(g, 'a', invalid);
const context = viewGame(g, 'a').battle!.harassWithdraw!;
g = seal(
g,
invalid === 'ix-chemistry'
? {}
: { weapon: 'ecaz-harass-withdraw', defense: null },
);
const side = (index: number) => {
const p = g.players[index],
plan = g.battle!.plans[p.id];
return {
id: p.id,
faction: p.faction,
spice: p.spice,
hand: p.hand,
plan,
leader: p.leaders.find((l) => l.id === plan.leader),
forces:
index === 0
? context.forces
: {
normal: 5,
elite: 0,
eliteStrength: 1 as const,
freeSupport: true,
},
...(index === 0 ? { harassWithdraw: context } : {}),
};
};
const input: BattleResolutionInput = {
advanced: false,
turn: g.turn,
territory: g.battle!.territory,
attacker: side(0),
defender: side(1),
voters: g.players
.slice(0, 2)
.map((p) => ({
id: p.id,
beneficiary: p.id,
called: false,
traitors: p.traitors,
})),
participants: g.players.map((p) => ({ id: p.id, faction: p.faction })),
physicalCards: [
...g.deck,
...g.discard,
...g.players.flatMap((p) => p.hand),
],
pendingAuditorPresent: false,
pendingRetentionPresent: false,
};
assert.doesNotThrow(() => quoteBattleResolution(input));
g.battle!.plans.a[invalid === 'ix-chemistry' ? 'weapon' : 'defense'] =
invalid;
const before = JSON.stringify(g),
quoteBefore = JSON.stringify(input);
assert.throws(
() => quoteBattleResolution(input),
/invalid weapon and defense pair/,
);
assert.equal(JSON.stringify(input), quoteBefore);
for (const p of g.players)
assert.throws(() => viewGame(g, p.id), /invalid weapon and defense pair/);
assert.equal(JSON.stringify(g), before);
reject(
g,
'a',
{ type: 'setAutopilot', difficulty: 'Easy' },
/invalid weapon and defense pair/,
);
reject(
g,
'd',
{ type: 'traitorCall', call: false },
/invalid weapon and defense pair/,
);
harassCustody(g);
}
});
void test('Basic and Advanced Ixian half-dial withdrawal preserves all seven physical cyborgs', () => {
for (const advanced of [false, true]) {
let g = harassWithdrawGame({
advanced,
factions: ['ixians', 'atreides', 'tleilaxu'],
normal: 2,
elite: 2,
});
harassCustody(g);
const quoted = quoteHarassWithdraw(
viewGame(g, 'a').battle!.harassWithdraw!,
0.5,
0,
);
assert.deepEqual(quoted.returned, { normal: 1, elite: 2 });
g = resolve(seal(g, { dial: 0.5, support: 0 }));
assert.equal(g.lastBattleContext?.winner, 'a');
assert.equal(g.players[0].reserves, 19);
assert.equal(g.players[0].tanks, 1);
assert.equal(g.players[0].elites!.reserves, 7);
assert.equal(g.players[0].elites!.tanks, 0);
assert.deepEqual(g.players[0].forces, {});
assert.equal(
g.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
harassCustody(g);
}
});
void test('Reinforcements and public Richese/optional-module contexts remain guarded', () => {
let g = harassWithdrawGame();
takeHarassCard(g, 'a', 'ecaz-reinforcements');
reject(
g,
'a',
ownPlan(g, { defense: 'ecaz-reinforcements' }),
/Reinforcements.*still/,
);
const richese = harassWithdrawGame({
factions: ['emperor', 'atreides', 'richese'],
});
assert.match(
viewGame(richese, 'a').battle!.harassWithdraw!.blocked!,
/Richese card family/,
);
reject(richese, 'a', ownPlan(richese), /Richese card family/);
g = harassWithdrawGame({ factions: ['emperor', 'atreides', 'choam'] });
assert.equal(viewGame(g, 'a').battle!.harassWithdraw!.blocked, null);
const forged = structuredClone(g);
forged.nexusCards = { cards: null, phase: null };
reject(forged, 'a', ownPlan(forged), /optional modules|Nexus/i);
});
void test('malformed sealed withdrawal allocations reject private reads and both ordinary/autopilot actions', () => {
let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 });
g = applyAction(g, 'a', ownPlan(g, { dial: 0, support: 0 }));
g.battle!.plans.a.dial = 2;
g.battle!.plans.a.support = 1;
for (const p of g.players)
assert.throws(() => viewGame(g, p.id), /ambiguous regular\/elite/);
reject(
g,
'a',
{ type: 'setAutopilot', difficulty: 'Easy' },
/ambiguous regular\/elite/,
);
reject(
g,
'd',
{ type: 'battlePlan', dial: 0, leader: otherLeader(g) },
/ambiguous regular\/elite/,
);
g = harassWithdrawGame();
g.players[0].reserves = Number.MAX_SAFE_INTEGER;
reject(g, 'a', ownPlan(g), /reserve and elite counters/);
g = harassWithdrawGame();
g = applyAction(g, 'a', ownPlan(g));
g.battle!.plans.a.leader = 'ecaz-harass-withdraw';
g.battle!.plans.a.defense = null;
for (const p of g.players)
assert.throws(
() => viewGame(g, p.id),
/exactly one ordinary Battle Plan card slot/,
);
});
+10 -2
View File
@@ -155,11 +155,16 @@ void test('every simultaneous own commitment overrides plan submission, includin
assert.deepEqual(battlePlanCommitments(view), {});
});
void test('the actual battle table locks each native-plus-Nexus field pair to the same values used by submission', () => {
void test('the actual table binds native-plus-Nexus values while category-None selectors exclude ordinary cards', () => {
for (const fields of [['dial', 'defense'], ['leader', 'weapon']] as const) {
const view = fixture('h');
view.nexusAtreides = null;
view.nexusCards = null;
// An empty selector must follow the inspected category, not merely an empty hand.
view.players.find((p) => p.id === 'h')!.hand = [
baseDeck().find((card) => card.kind === 'projectile')!,
baseDeck().find((card) => card.kind === 'shield')!,
];
const values = { dial: 0, defense: null, leader: view.players.find((p) => p.id === 'h')!.leaders[0].id, weapon: null };
view.battle!.ownCommitments = fields.map((field, index) => ({ source: index ? 'nexus' : 'native', beneficiary: 'a', target: 'h', field, value: values[field] }));
const html = tableHtml(view);
@@ -167,12 +172,15 @@ void test('the actual battle table locks each native-plus-Nexus field pair to th
const id = field === 'dial' ? 'forces-dialed' : `battle-${field}`;
const control = html.match(new RegExp(`<[^>]+id="${id}"[^>]*>`))?.[0];
assert.ok(control, `${field} control is visible`);
assert.match(control, /disabled=""|aria-disabled="true"/);
const categoryNone = (field === 'weapon' || field === 'defense') && values[field] === null;
if (categoryNone) assert.doesNotMatch(control, /disabled=""|aria-disabled="true"/);
else assert.match(control, /disabled=""|aria-disabled="true"/);
if (field === 'dial') assert.match(control, /value="0"/);
else {
const select = html.match(new RegExp(`<select[^>]+id="${id}"[^>]*>[\\s\\S]*?</select>`))?.[0];
assert.ok(select);
assert.match(select, new RegExp(`<option[^>]+value="${values[field] ?? ''}"[^>]+selected=""`));
if (categoryNone) assert.equal((select.match(/<option\b/g) ?? []).length, 1, 'only None is legal without a supported slot-only special');
}
}
for (const field of ['leader', 'weapon', 'defense'] as const) if (!(fields as readonly string[]).includes(field)) {
+3 -2
View File
@@ -169,8 +169,9 @@ void test('base, Ix and Ecaz guides remain separate from Richese replacement-car
assert.equal(presentation.category, 'Special treachery');
assert.ok(presentation.gameplay!.length >= 4);
assert.match(presentation.availability ?? '', card.effect === 'recruits'
? /development controls during Revival/ : /battle effect is still being implemented/);
assert.deepEqual(presentation.topics.map((topic) => topic.id), ['card-recruits']);
? /development controls during Revival/ : card.effect === 'harassWithdraw'
? /development controls in either battle-card slot/ : /battle effect is still being implemented/);
assert.deepEqual(presentation.topics.map((topic) => topic.id), [card.effect === 'harassWithdraw' ? 'card-harass-withdraw' : 'card-recruits']);
}
assert.equal(treacheryDeck().length, 33);
assert.equal(treacheryDeck(['ix']).length, 47);