Prototype Harkonnen Nexus with standalone E3 factions
Verify and publish checkpoint container / container (push) Successful in 14m6s

This commit is contained in:
Quintine committed 2026-11-16 21:03:08 +11:00
1 parent 6a30fdf376
commit 007508185e
14 files changed
+647 -18

No files matched your search

+9 -4
View File
@@ -104,14 +104,11 @@ void test('selected independent Ecaz cards and an unused selected E3 deck retain
assert.equal(emperorNexusBankPurchaseModeSupported(unusedEcaz), true);
});
void test('the missing module, Sandtrout and seated Emperor stay gated', () => {
void test('a missing Nexus module and a seated Emperor stay gated', () => {
const withoutNexus = lobby(['atreides', 'harkonnen', 'fremen'], []);
withoutNexus.nexusCards = undefined;
const sandtrout = lobby(['atreides', 'harkonnen', 'fremen'], []);
sandtrout.sandtrout = true;
const blocked: [string, Game][] = [
['a missing Nexus module', withoutNexus],
['Sandtrout', sandtrout],
['an Emperor seat', lobby(['atreides', 'harkonnen', 'emperor'], [])],
['an Emperor seat on a native roster', lobby(['harkonnen', 'richese', 'emperor'], ['choam'])],
];
@@ -119,6 +116,14 @@ void test('the missing module, Sandtrout and seated Emperor stay gated', () => {
assert.equal(emperorNexusBankPurchaseModeSupported(g), false, label);
});
void test('a waiting Sandtrout retains the supported Basic Kull bank profile', () => {
const game = lobby(['choam', 'ixians', 'atreides'], ['ix', 'choam']);
game.kullPreview = true;
game.nexusKullPreview = true;
game.sandtrout = true;
assert.equal(emperorNexusBankPurchaseModeSupported(game), true);
});
void test('unsupported rosters and unsupported module envelopes stay gated', () => {
const blocked: [string, Game][] = [
['an Ecaz seat on a classic roster', lobby(['atreides', 'ecaz'], [])],
+213
View File
@@ -0,0 +1,213 @@
import assert from 'node:assert/strict';
import {test} from 'node:test';
import {applyAction, createGame, joinGame, newPlayer, viewGame, type Action, type Game} from '../game/engine';
import {TERRITORIES} from '../game/board';
import {traitorDeck} from '../game/traitors';
import {withoutEcazLoyalty} from '../game/ecaz-loyalty';
import {validateNexusTraitorSnapshot} from '../game/nexus-traitor-exchange';
import {botActions} from '../game/bots';
import { registerHooks } from 'node:module';
import { readFileSync } from 'node:fs';
import { Children, createElement, isValidElement } from 'react';
import type { ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import {DIFFICULTIES} from '../game/bot-profiles';
import {nextHarkonnenBetrayalNativeStep, settleHarkonnenBetrayalNativeCounters,
} from './fixture-nexus-harkonnen-betrayal';
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 { NexusHarkonnenBetrayal } = await import('../components/nexus-harkonnen-betrayal');
const act = (game:Game, actor:string, action:Action) => applyAction(game,actor,action);
const player = (game:Game, id:string) => {const seat=game.players.find(p=>p.id===id);assert.ok(seat);return seat;};
const step = (game:Game) => {
if(game.pendingGuildBetrayal) {const frame=game.pendingGuildBetrayal;const actor=frame.required.find(id=>!frame.passed.includes(id));assert.ok(actor);return act(game,actor,{type:'guildBetrayalPass',event:frame.invoice.event});}
const next=nextHarkonnenBetrayalNativeStep(game); try {return act(game,next.actor,next.action);} catch (error) {throw Error(`Step ${game.turn}/${game.phase}/${game.decision?.kind} ${JSON.stringify(next)}: ${String(error)}`);}};
function advance(game:Game, until:(game:Game)=>boolean, limit=1800):Game {
for(let i=0;i<limit;i++) {if(until(game)) return game; assert.notEqual(game.status,'finished',`Unexpected end at turn ${game.turn} phase ${game.phase}; log ${JSON.stringify(game.log.slice(-5))}`); game=step(game);}
throw Error(`Native E3 Nexus journey stalled at ${game.status}/${game.turn}/${game.phase}/${game.decision?.kind}`);
}
function inventory(game:Game):string[] {
return [...game.deck,...game.discard,...(game.richeseCache??[]),...(game.richeseRemoved??[]),
...(game.auction?.cards.slice(game.auction.index)??[]),...game.players.flatMap(p=>p.hand)].map(card=>card.id).sort();
}
function traitors(game:Game):void {
validateNexusTraitorSnapshot({reserve:game.traitorReserve!,players:game.players.map(({id,faction,traitors,faceDancers})=>({id,faction,traitors,...(faceDancers?{faceDancers}: {})}))},withoutEcazLoyalty(traitorDeck(game.players,game.expansions.includes('ix')),game.ecazLoyalty));
}
/** Native public standalone Ecaz/Moritani start, original setup and second-turn Nexus
* draw. Conserved unopened deck order, one held traitor and two physical
* reserve positions are staged; battle selection, plans and call are real. */
function fixture(target:'ecaz'|'moritani') {
const faction = target;
let game=createGame('ADVHARKEXPANDED',newPlayer('i',faction,faction),true,['ecaz']);
const partner = 'atreides';
for(const [id,faction] of [['h','harkonnen'],['r',partner],['g','guild']] as const)
joinGame(game,newPlayer(id,faction,faction));
game=act(game,'i',{type:'moduleOption',module:'nexusCards',enabled:true});
for(const seat of game.players) game=act(game,seat.id,{type:'ready'});
game=act(game,'i',{type:'start',advancedPreview:true});
assert.equal(game.nexusHarkonnenBetrayalPreview,true);
game=advance(game,state=>state.status==='playing');
const physical=inventory(game);traitors(game);
assert.ok(Object.values(game.nexusCards!.cards!.hands).every(card=>card===null));
const identity=player(game,'i').leaders.find(leader=>!leader.dead && leader.id!==game.ecazLoyalty?.card)!.id;
const h=player(game,'h');
if(!h.traitors.includes(identity)) {
const replacement=h.traitors[0];
const owner=game.players.find(seat=>seat.id!=='h'&&seat.traitors.includes(identity));
if(owner) owner.traitors[owner.traitors.indexOf(identity)]=replacement;
else {
const dancer=game.players.flatMap(seat=>seat.faceDancers??[]).find(card=>card.leader===identity);
if(dancer) dancer.leader=replacement;
else {const index=game.traitorReserve!.indexOf(identity);assert.ok(index>=0);game.traitorReserve![index]=replacement;}
}
h.traitors[0]=identity;
}
traitors(game);
const nexus=game.nexusCards!.cards!;
const nx=nexus.deck.indexOf('harkonnen');assert.ok(nx>=0);
nexus.deck.unshift(nexus.deck.splice(nx,1)[0]);
for(let pos=0;pos<2;pos++) {
const index=game.spiceDeck.findIndex((card,i)=>i>=pos&&'territory'in card);assert.ok(index>=pos);
game.spiceDeck.splice(pos,0,game.spiceDeck.splice(index,1)[0]);
}
game=advance(game,state=>state.turn===2&&state.phase===1&&!state.response&&!state.decision);
const worm=game.spiceDeck.findIndex(card=>'worm'in card&&!card.greatMaker&&!card.suppressed);assert.ok(worm>=0);
game.spiceDeck.unshift(game.spiceDeck.splice(worm,1)[0]);
// Keep Sandtrout from breaking the alliance during the second Spice Blow
// before the genuine Nexus closes and awards its held card.
for(let pos=1;pos<=2;pos++) {
const index=game.spiceDeck.findIndex((card,i)=>i>=pos&&'territory'in card);assert.ok(index>=pos);
game.spiceDeck.splice(pos,0,game.spiceDeck.splice(index,1)[0]);
}
game=advance(game,state=>state.nexus&&!state.spiceWindow&&!state.spiceResolution&&!state.response&&!state.decision);
game=act(game,'h',{type:'alliance',target:'r'});game=act(game,'r',{type:'alliance',target:'h'});
game=advance(game,state=>state.turn>2||state.nexusCards?.phase?.stage==='drawing');
assert.equal(game.turn,2,`Nexus drawing was skipped: ${JSON.stringify(game.log.slice(-25))}`);
assert.ok(game.nexusCards!.phase!.eligible.includes('i'));
game=act(game,'i',{type:'nexusCardChoice',turn:game.turn,card:null,choice:'draw',ownRedraws:0});
assert.equal(game.nexusCards!.cards!.hands.i,'harkonnen');
game=advance(game,state=>state.phase===5&&!state.response&&!state.decision);
const territory=TERRITORIES.find(t=>t.type==='sand'&&!t.sectors.includes(game.storm)&&
game.players.every(p=>!Object.keys(p.forces).some(key=>key.startsWith(`${t.id}:`))));assert.ok(territory);
for(const id of ['h','i']) {const seat=player(game,id);assert.ok(seat.reserves>0);seat.reserves--;seat.forces[`${territory.id}:${territory.sectors[0]}`]=1;}
game=advance(game,state=>state.phase===6&&!!state.active&&!state.phaseOpening&&!state.response&&!state.decision);
const chooser=game.active!;assert.ok(['h','i'].includes(chooser), `chooser ${chooser}; battle ${JSON.stringify(game.battle)}; decision ${JSON.stringify(game.decision)}; pending ${JSON.stringify(game.pendingGuildBetrayal)}; armies ${JSON.stringify(game.players.map(p=>[p.id,p.forces]))}`);
game=act(game,chooser,{type:'chooseBattle',territory:territory.id,target:chooser==='h'?'i':'h'});
game=advance(game,state=>!!state.battle&&!state.response&&!state.decision&&!state.battle.preparation&&
(!state.battle.preLeader||state.battle.preLeader.closed));
for(const id of [game.battle!.attacker,game.battle!.defender]) {
const leader=id==='i'?identity:player(game,id).leaders.find(l=>!l.dead&&!l.usedAt)!.id;
game=act(game,id,{type:'battlePlan',dial:0,leader});
}
assert.equal(game.battle!.revealed,true);
game=advance(game,state=>!state.response&&!state.decision);
game=act(game,'h',{type:'traitorCall',call:true});
game=settleHarkonnenBetrayalNativeCounters(game);
const reaction=viewGame(game,'i').nexusHarkonnenBetrayalReaction;
assert.ok(reaction,'The actual expansion-roster traitor call opens native Betrayal');
assert.equal(reaction.canUse,true);assert.equal(reaction.identity,identity);
assert.deepEqual(inventory(game),physical);traitors(game);
return {game,event:reaction.event,identity,physical};
}
function click(node: ReactNode, selector: string): boolean {
for (const child of Children.toArray(node)) {
if (!isValidElement<{children?: ReactNode; onClick?: () => void; 'data-testid'?: string}>(child)) continue;
if (child.props['data-testid'] === selector && child.props.onClick) {
child.props.onClick();
return true;
}
if (click(child.props.children, selector)) return true;
}
return false;
}
function select(game: ReturnType<typeof viewGame>, choice: 'use'|'pass', busy = false): Action | undefined {
let action: Action | undefined;
click(NexusHarkonnenBetrayal({game, busy, act(value) { action = value; }}), `nexus-harkonnen-betrayal-${choice}`);
return action;
}
function markup(game: ReturnType<typeof viewGame>): string {
return renderToStaticMarkup(createElement(NexusHarkonnenBetrayal, {game, busy: false, act() {}}));
}
for (const target of ['ecaz', 'moritani'] as const) {
void test(`Advanced ${target} owner controls use and pass the real Harkonnen betrayal`, () => {
const f = fixture(target);
const owner = viewGame(f.game, 'i');
assert.ok(markup(owner).includes('Declared Harkonnen traitor acknowledgement'));
assert.ok(markup(owner).includes('Inspect Harkonnen Nexus card'));
assert.ok(markup(owner).includes(owner.allLeaders.find(leader => leader.id === f.identity)!.name));
const use = select(owner, 'use');
assert.deepEqual(use, {type: 'nexusHarkonnenBetrayalUse', event: f.event});
assert.equal(select(owner, 'use', true), undefined);
assert.equal(select(owner, 'pass', true), undefined);
// Public declaration, not private Harkonnen cards or the owner's face.
for (const seat of f.game.players.filter(seat => seat.id !== 'i')) {
const other = viewGame(f.game, seat.id);
const html = markup(other);
assert.ok(html.includes(other.allLeaders.find(leader => leader.id === f.identity)!.name));
assert.equal(html.includes('Inspect Harkonnen Nexus card'), false);
for (const hidden of player(f.game, 'h').traitors.filter(id => id !== f.identity)) {
assert.equal(html.includes(other.allLeaders.find(leader => leader.id === hidden)!.name), false);
}
assert.equal(select(other, 'use'), undefined);
}
// Event binding rejects a forged and previously consumed control without mutation.
const before = structuredClone(f.game);
assert.throws(() => act(f.game, 'i', {type: 'nexusHarkonnenBetrayalUse', event: `${f.event}-stale`}));
assert.deepEqual(f.game, before);
assert.ok(use);
const used = act(f.game, 'i', use);
assert.equal(used.pendingNexusHarkonnenBetrayal, null);
assert.equal(used.nexusCards!.cards!.hands.i, null);
assert.equal(player(used, 'h').traitors.includes(f.identity), false);
assert.equal(used.pendingNexusHarkonnenReplacement?.identity, f.identity);
assert.equal(select(viewGame(used, 'i'), 'use'), undefined);
assert.throws(() => act(used, 'i', use));
assert.deepEqual(inventory(used), f.physical);
traitors(used);
let passed = f.game;
for (const id of passed.pendingNexusHarkonnenBetrayal!.required) {
const pass = select(viewGame(passed, id), 'pass');
assert.deepEqual(pass, {type: 'nexusHarkonnenBetrayalPass', event: f.event});
assert.ok(pass);
passed = act(passed, id, pass);
}
assert.equal(passed.pendingNexusHarkonnenBetrayal, null);
assert.equal(passed.nexusCards!.cards!.hands.i, 'harkonnen');
assert.equal(player(passed, 'h').traitors.includes(f.identity), true);
assert.equal(passed.pendingNexusHarkonnenReplacement ?? null, null);
assert.deepEqual(inventory(passed), f.physical);
traitors(passed);
});
void test(`Advanced ${target} bot has a legal Harkonnen Nexus response`, () => {
const f = fixture(target);
for (const difficulty of DIFFICULTIES) {
const own = viewGame(f.game, 'i');
own.players.find(seat => seat.id === 'i')!.bot = difficulty;
const use = botActions(own).find(action => action.type === 'nexusHarkonnenBetrayalUse');
assert.deepEqual(use, {type: 'nexusHarkonnenBetrayalUse', event: f.event});
assert.ok(use);
const result = act(structuredClone(f.game), 'i', use);
assert.equal(result.nexusCards!.cards!.hands.i, null);
assert.equal(result.pendingNexusHarkonnenReplacement?.identity, f.identity);
}
});
}
aliases.deregister();
+88
View File
@@ -0,0 +1,88 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { applyAction, createGame, joinGame, newPlayer, viewGame, type Action, type Game } from '../game/engine';
import { emperorNexusPools } from '../game/nexus-emperor-secret-ally';
import { orderE3NexusEcazSpice } from './fixture-e3-nexus-ecaz';
import { advanceNexusEmperorBank, nexusEmperorBankInventory,
nexusEmperorBankPlayer as player } from './fixture-nexus-emperor-bank';
const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action);
const clean = (game: Game) => !game.phaseOpening && !game.response && !game.decision &&
!game.truthtrance && !game.pendingTreacheryDiscard;
/** Public Advanced E3 start, full first turn, real second-turn worm/alliance,
* and an original Nexus draw. Only the still-undealt Spice and Nexus singleton
* ordering is selected; no started room or held card is fabricated. */
function closing(native: 'ecaz' | 'moritani'): Game {
let game = createGame('HARKE3PRESERVE', newPlayer('e3', native, native), true, ['ecaz']);
for (const [id, faction] of [['h', 'harkonnen'], ['g', 'guild'], ['a', 'atreides']] as const)
joinGame(game, newPlayer(id, faction, faction));
game = act(game, 'e3', { type: 'moduleOption', module: 'nexusCards', enabled: true });
for (const seat of game.players) game = act(game, seat.id, { type: 'ready' });
game = act(game, 'e3', { type: 'start', advancedPreview: true });
assert.equal(game.advanced, true);
assert.equal(game.nexusHarkonnenBetrayalPreview, true);
game = advanceNexusEmperorBank(game, state => state.status === 'playing');
if (native === 'ecaz') assert.ok(game.ecazLoyalty?.card);
else assert.equal(game.moritaniAssassinatePreview, true);
nexusEmperorBankInventory(game);
orderE3NexusEcazSpice(game);
game = advanceNexusEmperorBank(game, state => state.turn === 2 && state.phase === 1 && clean(state) &&
!state.spiceSequence && !state.spiceResolution && !state.spiceWindow);
orderE3NexusEcazSpice(game, true);
game = advanceNexusEmperorBank(game, state => !!state.nexus && !state.spiceWindow && !state.spiceResolution && clean(state));
game = act(game, 'h', { type: 'alliance', target: 'g' });
game = act(game, 'g', { type: 'alliance', target: 'h' });
game = advanceNexusEmperorBank(game, state => state.nexusCards?.phase?.stage === 'drawing' && clean(state));
const cards = game.nexusCards!.cards!, index = cards.deck.indexOf('emperor'); assert.ok(index >= 0);
cards.deck.unshift(cards.deck.splice(index, 1)[0]);
assert.ok(game.nexusCards!.phase!.eligible.includes('e3'));
game = act(game, 'e3', { type: 'nexusCardChoice', turn: game.turn, card: null, choice: 'draw', ownRedraws: 0 });
assert.equal(game.nexusCards!.cards!.hands.e3, 'emperor');
game = advanceNexusEmperorBank(game, state => state.nexusCards?.phase?.stage === 'complete' && clean(state));
nexusEmperorBankInventory(game);
return game;
}
for (const native of ['ecaz', 'moritani'] as const) {
void test(`public Advanced ${native} retains Emperor Nexus normal bank purchase with the Harkonnen reaction stamp`, () => {
let game = closing(native);
game = advanceNexusEmperorBank(game, state => state.phase === 3 && !!state.auction && clean(state));
while (game.auction!.active !== 'e3') game = act(game, game.auction!.active, { type: 'passBid' });
const card = game.auction!.cards[game.auction!.index], wallet = player(game, 'e3').spice;
assert.ok(wallet >= 1);
game = act(game, 'e3', { type: 'bid', amount: 1, allyPayment: 0 });
game = advanceNexusEmperorBank(game, state => state.decision?.kind === 'auctionPayment');
const offer = viewGame(game, 'e3').nexusEmperorSecretAlly;
assert.ok(offer?.purchase && !offer.purchase.blocked, 'The physical Nexus must remain available at the native purchase boundary.');
const paid = act(game, 'e3', { type: 'nexusEmperorPurchase', event: offer.event });
assert.equal(player(paid, 'e3').spice, wallet);
assert.equal(paid.nexusCards!.cards!.hands.e3, null);
assert.equal(paid.nexusCards!.cards!.discard.filter(c => c === 'emperor').length, 1);
assert.equal(player(paid, 'e3').hand.filter(c => c.id === card.id).length, 1);
assert.equal(paid.nexusHarkonnenBetrayalPreview, true);
nexusEmperorBankInventory(paid);
assert.throws(() => act(paid, 'e3', { type: 'nexusEmperorPurchase', event: offer.event }));
});
void test(`public Advanced ${native} retains Emperor Nexus revival with the Harkonnen reaction stamp`, () => {
let game = closing(native);
game = advanceNexusEmperorBank(game, state => state.phase === 4 && clean(state));
// Conserved physical staging only: move three actual reserve forces to the
// Tanks at the real Revival boundary, preserving all force totals.
const seat = player(game, 'e3'); assert.ok(seat.reserves >= 3);
seat.reserves -= 3; seat.tanks += 3;
const before = emperorNexusPools(seat), offer = viewGame(game, 'e3').nexusEmperorSecretAlly;
assert.ok(offer && !offer.revival.blocked, 'The original held face must expose its native Revival action.');
const action: Action = { type: 'nexusEmperorRevive', event: offer.event, elite: 0 };
game = act(game, 'e3', action);
assert.equal(player(game, 'e3').reserves, before.reserves + 3);
assert.equal(player(game, 'e3').tanks, before.tanks - 3);
assert.equal(player(game, 'e3').revived, before.revived);
assert.equal(game.nexusCards!.cards!.hands.e3, null);
assert.equal(game.nexusCards!.cards!.discard.filter(c => c === 'emperor').length, 1);
assert.equal(game.nexusHarkonnenBetrayalPreview, true);
nexusEmperorBankInventory(game);
assert.throws(() => act(game, 'e3', action));
});
}
+111
View File
@@ -0,0 +1,111 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { leaders, treacheryDeck } from '../game/cards';
import { DUKE_VIDAL_ID } from '../game/duke-vidal';
import {
createMoritaniAssassinateOpportunity,
moritaniAssassinateChoices,
quoteMoritaniAssassinate,
} from '../game/moritani-assassinate';
import { NEXUS_FACTIONS } from '../game/nexus-cards';
import {
closeHarkonnenBetrayalSource,
createHarkonnenBetrayalReplacement,
createHarkonnenBetrayalSource,
drawHarkonnenBetrayalReplacement,
initialHarkonnenBetrayalCursor,
validateHarkonnenBetrayalSource,
type HarkonnenBetrayalContext,
} from '../game/nexus-harkonnen-betrayal';
import { createTraitorDeclaration } from '../game/traitor-declarations';
import { traitorDeck } from '../game/traitors';
/** E3 p8 Loyalty excludes one ordinary Ecaz card; Duke has no Traitor Card.
* A prior Moritani assassination has permanently retired atreides-2. */
function fixture(): HarkonnenBetrayalContext {
const players: HarkonnenBetrayalContext['players'] = [
{ id: 'h', faction: 'harkonnen', ally: null },
{ id: 'e', faction: 'ecaz', ally: null },
{ id: 'm', faction: 'moritani', ally: null },
{ id: 'a', faction: 'atreides', ally: null },
];
const expansions = ['ecaz'];
const ecazLoyalty = { player: 'e', card: 'ecaz-0' };
const universe = traitorDeck(players.map(player => ({ leaders: leaders(player.faction) })), false)
.filter(card => card !== ecazLoyalty.card);
const held = ['moritani-0', 'ecaz-1'];
const removed = ['atreides-2'];
return {
status: 'playing', phase: 6, turn: 2, advanced: true, sequence: 0,
expansions, players, ecazLoyalty, universe,
physicalCards: treacheryDeck(expansions),
cards: { version: 1, deck: NEXUS_FACTIONS.filter(card => card !== 'harkonnen'),
discard: [], hands: { h: null, e: null, m: null, a: 'harkonnen' } },
traitors: { reserve: universe.filter(card => !held.includes(card) && !removed.includes(card)),
removed, players: players.map(player => ({ id: player.id, faction: player.faction,
traitors: player.id === 'h' ? [held[0]] : player.id === 'm' ? [held[1]] : [] })) },
battle: { event: 'e3-battle', attacker: 'h', defender: 'm',
plans: { h: { leader: 'harkonnen-0' }, m: { leader: 'moritani-0' } }, heroLeaderIds: [] },
};
}
function authority(ctx: HarkonnenBetrayalContext) {
const declaration = createTraitorDeclaration({ ...ctx.battle,
players: ctx.players.map(player => ({ ...player,
traitors: ctx.traitors.players.find(seat => seat.id === player.id)!.traitors })) }, 'h');
return { provider: 'h', declaration, nativeWindow: 'direct' as const,
nativeContext: 'native', nativeRequired: [], nativePassed: [] };
}
void test('E3 Betrayal binds Loyalty, the original declaration and permanent assassination markers', () => {
const ctx = fixture(), native = authority(ctx);
const before = structuredClone(ctx);
const source = createHarkonnenBetrayalSource(ctx, native, 'battle-parent');
assert.equal(source.declaration.identity, 'moritani-0');
assert.equal(source.universe.includes('ecaz-0'), false);
assert.equal(source.universe.includes(DUKE_VIDAL_ID), false);
assert.equal(source.universe.includes('atreides-2'), true);
assert.deepEqual(JSON.parse(source.inventory)[1].removed, ['atreides-2']);
validateHarkonnenBetrayalSource(ctx, source, native, 'battle-parent');
assert.deepEqual(ctx, before);
for (const mutate of [
(bad: HarkonnenBetrayalContext) => { bad.ecazLoyalty!.card = 'ecaz-1'; },
(bad: HarkonnenBetrayalContext) => { bad.ecazLoyalty!.card = DUKE_VIDAL_ID; },
(bad: HarkonnenBetrayalContext) => { bad.universe = [...bad.universe, DUKE_VIDAL_ID]; },
(bad: HarkonnenBetrayalContext) => { bad.traitors.reserve.push('atreides-2'); },
(bad: HarkonnenBetrayalContext) => { bad.traitors.removed = []; },
]) {
const bad = structuredClone(ctx);
mutate(bad);
const changed = structuredClone(bad);
assert.throws(() => createHarkonnenBetrayalSource(bad, native, 'battle-parent'));
assert.deepEqual(bad, changed);
}
});
void test('a retired Moritani marker cannot fund the Harkonnen replacement', () => {
const ctx = fixture(), source = createHarkonnenBetrayalSource(ctx, authority(ctx), 'battle-parent');
const { receipt, cursor } = closeHarkonnenBetrayalSource(source, 'use', 'a', initialHarkonnenBetrayalCursor());
const replacement = createHarkonnenBetrayalReplacement(receipt);
assert.throws(() => drawHarkonnenBetrayalReplacement(replacement, [receipt], cursor, 'atreides-2', ctx.universe), /set-aside/);
const drawn = drawHarkonnenBetrayalReplacement(replacement, [receipt], cursor, ctx.traitors.reserve[0], ctx.universe);
assert.equal(drawn.status, 'drawn');
assert.equal(drawn.drawn, ctx.traitors.reserve[0]);
assert.equal(replacement.status, 'due');
});
void test('Moritani can select a held native Ecaz identity against Duke, never Loyalty or a retired card', () => {
const ctx = fixture();
const receipt = createMoritaniAssassinateOpportunity({ advanced: true, owner: 'm', ownerFaction: 'moritani',
opponent: 'e', faction: 'ecaz', event: 'duke-battle', turn: 2, territory: 'arrakeen',
opposingLeader: DUKE_VIDAL_ID, opposingLeaderSurvived: true, normalBattle: true,
lostBattle: true, traitorCalled: false });
const assassinate = { state: { version: 1 as const, owner: 'm', normalTraitorCall: false,
opportunities: [receipt] }, receipt,
held: ctx.traitors.players.find(player => player.id === 'm')!.traitors,
normallyRevealed: [], leaders: leaders('ecaz') };
assert.deepEqual(moritaniAssassinateChoices(assassinate).cards.map(choice => choice.card), ['ecaz-1']);
assert.equal(quoteMoritaniAssassinate(assassinate, 'ecaz-1').leader, 'ecaz-1');
for (const invalid of ['ecaz-0', 'atreides-2', DUKE_VIDAL_ID])
assert.throws(() => quoteMoritaniAssassinate(assassinate, invalid), /eligible/);
});
+158
View File
@@ -0,0 +1,158 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { applyAction, createGame, joinGame, newPlayer, normalizeAutomaticGame, viewGame, type Action, type Game } from '../game/engine';
import { TERRITORIES } from '../game/board';
import { NEXUS_FACTIONS } from '../game/nexus-cards';
import { traitorDeck } from '../game/traitors';
import { validateNexusTraitorSnapshot } from '../game/nexus-traitor-exchange';
import { nextHarkonnenBetrayalNativeStep, settleHarkonnenBetrayalNativeCounters } from './fixture-nexus-harkonnen-betrayal';
const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action);
function player(game: Game, id: string) {
const seat = game.players.find(p => p.id === id); assert.ok(seat); return seat;
}
function step(game: Game): Game {
if (game.pendingGuildBetrayal) {
const frame = game.pendingGuildBetrayal;
const actor = frame.required.find(id => !frame.passed.includes(id)); assert.ok(actor);
return act(game, actor, { type: 'guildBetrayalPass', event: frame.invoice.event });
}
const next = nextHarkonnenBetrayalNativeStep(game);
try { return act(game, next.actor, next.action); }
catch (error) { throw Error(`Native E3 step ${game.turn}/${game.phase}/${game.decision?.kind} ${JSON.stringify(next)}: ${String(error)}`); }
}
function advance(game: Game, until: (game: Game) => boolean): Game {
for (let i = 0; i < 1800; i++) {
if (until(game)) return game;
assert.notEqual(game.status, 'finished'); game = step(game);
}
throw Error(`Native E3 journey stalled at ${game.status}/${game.turn}/${game.phase}/${game.decision?.kind}`);
}
function inventory(game: Game): string[] {
return [...game.deck, ...game.discard, ...(game.auction?.cards.slice(game.auction.index) ?? []),
...game.players.flatMap(p => p.hand)].map(card => card.id).sort();
}
function physical(game: Game): void {
const nx = game.nexusCards!.cards!;
assert.deepEqual([...nx.deck, ...nx.discard, ...Object.values(nx.hands).filter(c => c !== null)].sort(), [...NEXUS_FACTIONS].sort());
const universe = traitorDeck(game.players).filter(id => id !== game.ecazLoyalty?.card);
validateNexusTraitorSnapshot({ reserve: game.traitorReserve!, players: game.players.map(({id, faction, traitors, faceDancers}) =>
({ id, faction, traitors, ...(faceDancers ? { faceDancers } : {}) })) }, universe);
}
/** Fresh public Advanced E3 setup and a real second-turn Nexus draw. The unopened
* Nexus/Spice decks are reordered, one already-dealt Traitor is exchanged with
* its actual owner or the reserve, and one reserve force from each battle side
* is placed on an otherwise empty sand territory. For the Moritani variant,
* a held Harkonnen identity is also exchanged with the reserve so a random
* unrelated post-loss assassination cannot obscure this test's replacement.
* No cards or forces are created.
* Battle selection, sealed plans, Traitor call, response and Mentat are native. */
function fixture(native: 'ecaz' | 'moritani') {
let game = createGame('HARKE3', newPlayer('e3', native, native), true, ['ecaz']);
for (const [id, faction] of [['h', 'harkonnen'], ['g', 'guild'], ['a', 'atreides']] as const)
joinGame(game, newPlayer(id, faction, faction));
game = act(game, 'e3', { type: 'moduleOption', module: 'nexusCards', enabled: true });
for (const seat of game.players) game = act(game, seat.id, { type: 'ready' });
game = act(game, 'e3', { type: 'start', advancedPreview: true });
assert.equal(game.advanced, true);
assert.equal(game.nexusHarkonnenBetrayalPreview, true);
game = advance(game, state => state.status === 'playing');
if (native === 'ecaz') {
assert.equal(game.ecazLoyalty?.player, 'e3'); assert.ok(game.ecazLoyalty?.card);
} else assert.equal(game.moritaniAssassinatePreview, true);
const cards = inventory(game); physical(game);
const identity = player(game, 'e3').leaders.find(l => !l.dead && l.id !== game.ecazLoyalty?.card)!.id;
const h = player(game, 'h');
if (!h.traitors.includes(identity)) {
const replacement = h.traitors[0]; assert.ok(replacement);
const owner = game.players.find(seat => seat.id !== 'h' && seat.traitors.includes(identity));
if (owner) owner.traitors[owner.traitors.indexOf(identity)] = replacement;
else {
const index = game.traitorReserve!.indexOf(identity); assert.ok(index >= 0);
game.traitorReserve![index] = replacement;
}
h.traitors[0] = identity;
}
if (native === 'moritani') {
const nativeLeaderIds = new Set(h.leaders.map(leader => leader.id));
const moritani = player(game, 'e3');
for (let i = 0; i < moritani.traitors.length; i++) {
if (!nativeLeaderIds.has(moritani.traitors[i])) continue;
const index = game.traitorReserve!.findIndex(id => !nativeLeaderIds.has(id));
assert.ok(index >= 0);
[moritani.traitors[i], game.traitorReserve![index]] = [game.traitorReserve![index], moritani.traitors[i]];
}
}
physical(game);
const nexus = game.nexusCards!.cards!, index = nexus.deck.indexOf('harkonnen'); assert.ok(index >= 0);
nexus.deck.unshift(nexus.deck.splice(index, 1)[0]);
for (let pos = 0; pos < 2; pos++) {
const i = game.spiceDeck.findIndex((card, n) => n >= pos && 'territory' in card); assert.ok(i >= pos);
game.spiceDeck.splice(pos, 0, game.spiceDeck.splice(i, 1)[0]);
}
game = advance(game, state => state.turn === 2 && state.phase === 1 && !state.response && !state.decision);
const worm = game.spiceDeck.findIndex(card => 'worm' in card && !card.greatMaker && !card.suppressed); assert.ok(worm >= 0);
game.spiceDeck.unshift(game.spiceDeck.splice(worm, 1)[0]);
game = advance(game, state => state.nexus && !state.spiceWindow && !state.spiceResolution && !state.response && !state.decision);
game = act(game, 'h', { type: 'alliance', target: 'g' });
game = act(game, 'g', { type: 'alliance', target: 'h' });
game = advance(game, state => state.nexusCards?.phase?.stage === 'drawing');
assert.ok(game.nexusCards!.phase!.eligible.includes('e3'));
game = act(game, 'e3', { type: 'nexusCardChoice', turn: game.turn, card: null, choice: 'draw', ownRedraws: 0 });
assert.equal(game.nexusCards!.cards!.hands.e3, 'harkonnen');
game = advance(game, state => state.phase === 5 && !state.response && !state.decision && !state.pendingGuildBetrayal);
const territory = TERRITORIES.find(t => t.type === 'sand' && !t.sectors.includes(game.storm) &&
game.players.every(p => !Object.keys(p.forces).some(key => key.startsWith(`${t.id}:`)))); assert.ok(territory);
for (const id of ['h', 'e3']) {
const seat = player(game, id); assert.ok(seat.reserves > 0); seat.reserves--;
seat.forces[`${territory.id}:${territory.sectors[0]}`] = 1;
}
game = advance(game, state => state.phase === 6 && !!state.active && !state.phaseOpening && !state.response && !state.decision);
const chooser = game.active!; assert.ok(['h', 'e3'].includes(chooser));
game = act(game, chooser, { type: 'chooseBattle', territory: territory.id, target: chooser === 'h' ? 'e3' : 'h' });
game = advance(game, state => !!state.battle && !state.response && !state.decision && !state.battle.preparation &&
(!state.battle.preLeader || state.battle.preLeader.closed));
for (const id of [game.battle!.attacker, game.battle!.defender]) {
const leader = id === 'e3' ? identity : player(game, id).leaders.find(l => !l.dead && !l.usedAt)!.id;
game = act(game, id, { type: 'battlePlan', dial: 0, leader });
}
assert.equal(game.battle!.revealed, true);
game = advance(game, state => !state.response && !state.decision);
game = act(game, 'h', { type: 'traitorCall', call: true });
game = settleHarkonnenBetrayalNativeCounters(game);
const reaction = viewGame(game, 'e3').nexusHarkonnenBetrayalReaction; assert.ok(reaction);
assert.equal(reaction.canUse, true); assert.equal(reaction.identity, identity);
assert.deepEqual(inventory(game), cards); physical(game);
return { game, identity, event: reaction.event, cards };
}
for (const native of ['ecaz', 'moritani'] as const) for (const use of [false, true])
void test(`Advanced public ${native} Harkonnen Nexus ${use ? 'Use' : 'Pass'} resolves the real native Traitor call and Mentat`, () => {
const f = fixture(native); let game = f.game;
if (use) game = act(game, 'e3', { type: 'nexusHarkonnenBetrayalUse', event: f.event });
else for (const id of game.pendingNexusHarkonnenBetrayal!.required)
game = act(game, id, { type: 'nexusHarkonnenBetrayalPass', event: f.event });
assert.equal(game.pendingNexusHarkonnenBetrayal, null);
assert.equal(game.nexusCards!.cards!.hands.e3, use ? null : 'harkonnen');
assert.equal(game.battle!.traitorCalls.h, !use);
assert.equal(player(game, 'h').traitors.includes(f.identity), !use);
assert.equal(game.pendingNexusHarkonnenReplacement?.status ?? null, use ? 'due' : null);
assert.deepEqual(inventory(game), f.cards); physical(game);
const top = game.traitorReserve![0];
game = advance(game, state => state.phase === 8 && !state.pendingNexusHarkonnenReplacement && !state.phaseOpening);
assert.equal(game.lastBattleContext!.result, use ? 'normal' : 'traitor');
assert.equal(game.nexusHarkonnenReplacementHistory!.length, use ? 1 : 0);
if (use) {
assert.equal(game.nexusHarkonnenReplacementHistory![0].drawn, top);
assert.ok(player(game, 'h').traitors.includes(top));
}
assert.equal(player(game, 'h').traitors.length, 4);
assert.deepEqual(inventory(game), f.cards); physical(game);
const before = JSON.stringify(game);
for (const p of game.players) viewGame(game, p.id);
assert.equal(JSON.stringify(game), before);
assert.deepEqual(normalizeAutomaticGame(game), game);
assert.throws(() => act(game, 'e3', { type: 'nexusHarkonnenBetrayalUse', event: f.event }));
assert.equal(JSON.stringify(game), before);
});