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 { botActions } from '../game/bots'; import { DIFFICULTIES } from '../game/bot-profiles'; import { SEMUTA_DRUG_ID } from '../game/semuta-drug'; import { takeKullCard } from './fixture-choam-kull'; import { nextHarkonnenBetrayalNativeStep } from './fixture-nexus-harkonnen-betrayal'; import { nextRicheseStrongholdsNativeStep } from './fixture-richese-strongholds'; import { swapSemutaNexusTradeIdentity } from './fixture-semuta-nexus-trade'; const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action); const seat = (game: Game, id: string) => { const player = game.players.find(row => row.id === id); assert.ok(player); return player; }; const clean = (game: Game) => !game.response && !game.decision && !game.phaseOpening; function stock(game: Game): string[] { return [...game.deck, ...game.discard, ...(game.richeseCache ?? []), ...(game.richeseRemoved ?? []), ...(game.auction?.cards.slice(game.auction.index + Number(game.currentAuctionSale?.origin === 'normal')) ?? []), ...(game.ixAuction?.cards ?? []), ...game.players.flatMap(player => player.hand)].map(card => card.id).sort(); } function advance(game: Game, until: (game: Game) => boolean): Game { let last: unknown; for (let n = 0; n < 1800; n++) { if (until(game)) return game; assert.notEqual(game.status, 'finished'); if (game.pendingTreacheryDiscard?.reaction?.stage === 'offer') { const pending = game.pendingTreacheryDiscard, reaction = pending.reaction; assert.ok(reaction && reaction.stage === 'offer'); const actor = game.players.find(player => !reaction.passed.includes(player.id)); assert.ok(actor); game = act(game, actor.id, {type:'semutaPass',event:pending.batch.event}); continue; } if (game.pendingGuildBetrayal) { const pending = game.pendingGuildBetrayal, actor = pending.required.find(id => !pending.passed.includes(id)); assert.ok(actor); game = act(game, actor, {type:'guildBetrayalPass',event:pending.invoice.event}); continue; } if (!game.response && !game.phaseOpening && game.decision?.kind === 'ecazPlacement') { const token = game.ecazAmbassadors!.tokens.find(row => row.effect === 'ecaz' && row.zone === 'supply'); game = act(game, game.decision.player, token ? {type:'decision',token:token.id,territory:'arrakeen'} : {type:'decision',decline:true}); continue; } if (!game.response && !game.phaseOpening && game.decision?.kind === 'moritaniPlacement') { const token = game.moritaniTerror!.tokens.find(row => row.kind === 'robbery' && row.status === 'available'); game = act(game, game.decision.player, token ? {type:'decision',token:token.id,territory:'carthag'} : {type:'decision',decline:true}); continue; } const next = !game.response && !game.phaseOpening && (game.decision?.kind.startsWith('richese') || game.richeseAuction && !game.richeseAuction.outcome) ? nextRicheseStrongholdsNativeStep(game)! : nextHarkonnenBetrayalNativeStep(game); last = next; try { game = act(game, next.actor, next.action); } catch (error) { throw Error(`Native ${game.status}/${game.turn}/${game.phase}/${game.decision?.kind}: ${JSON.stringify(next)}: ${String(error)}`); } } throw Error(`Native three-expansion Nexus Kull journey stalled: ${game.turn}/${game.phase} ${JSON.stringify({last,stormPending:game.stormPending,stormDials:game.stormDials,stormDialers:game.stormDialers,phaseOpening:game.phaseOpening,response:game.response,decision:game.decision,ready:game.ready})}`); } function orderSpice(game: Game, kinds: readonly ('land'|'worm')[]): void { for (const [position, kind] of kinds.entries()) { const index = game.spiceDeck.findIndex((card, i) => i >= position && (kind === 'land' ? 'territory' in card : 'worm' in card && !card.greatMaker && !card.suppressed)); assert.ok(index >= position); game.spiceDeck.splice(position, 0, game.spiceDeck.splice(index, 1)[0]); } } /** Public three-expansion native setup, real alliance and two earned Nexus draws. Unopened * Spice order, identities of genuinely drawn Nexus cards, board positions and * physical Treachery holdings are staged while conserving every component. */ function fixture(includeRichese = true) { let game = createGame('NXKULLE3', newPlayer('ix','Ixians','ixians'), false, ['ix','choam','ecaz']); const peers = [ ['m','moritani'], ['c','choam'], ['r',includeRichese ? 'richese' : 'guild'], ['a','atreides'], ['e','ecaz'] ] as const; for (const [id,faction] of peers) joinGame(game, newPlayer(id,faction,faction)); game = act(game,'ix',{type:'moduleOption',module:'nexusCards',enabled:true}); for (const player of game.players) game = act(game,player.id,{type:'ready'}); game = act(game,'ix',{type:'start'}); assert.equal(game.kullPreview,true); assert.equal(game.nexusKullPreview,true); assert.equal(game.semutaPreview === true,includeRichese); assert.equal(game.nexusIxianBetrayalPreview,true); game = advance(game,state => state.status === 'playing'); assert.equal(game.ecazOccupyPreview,true); assert.equal(Object.values(seat(game,'e').forces).reduce((sum,n)=>sum+n,0),6); const original = stock(game); for (const player of game.players) { player.reserves += Object.values(player.forces).reduce((sum,n)=>sum+n,0); player.forces = {}; if (player.elites) { player.elites.reserves += Object.values(player.elites.forces).reduce((sum,n)=>sum+n,0); player.elites.forces={}; } } orderSpice(game,['land','land']); game = advance(game,state=>state.turn===2 && state.phase===1 && clean(state)); assert.ok(game.ecazAmbassadors!.tokens.some(row => row.effect === 'ecaz' && row.location === 'arrakeen')); assert.ok(game.moritaniTerror!.tokens.some(row => row.kind === 'robbery' && row.location === 'carthag')); orderSpice(game,['worm','land','land']); game = advance(game,state=>state.nexus && !state.spiceWindow && !state.spiceResolution && clean(state)); game = act(game,'ix',{type:'alliance',target:'m'}); game = act(game,'m',{type:'alliance',target:'ix'}); game = advance(game,state=>state.nexusCards?.phase?.stage==='drawing' && clean(state)); for (const id of ['a','c']) { assert.ok(game.nexusCards!.phase!.eligible.includes(id)); game = act(game,id,{type:'nexusCardChoice',turn:game.turn,card:null,choice:'draw',ownRedraws:0}); swapSemutaNexusTradeIdentity(game,id,id==='a'?'ixians':'choam'); } game = advance(game,state=>state.phase===2 && clean(state)); for (const player of game.players) game.deck.push(...player.hand.splice(0)); const originalKarama = takeKullCard(game,'karama'); seat(game,'e').hand.push(originalKarama); const counter = takeKullCard(game,'karama'); seat(game,'a').hand.push(counter); game = advance(game,state=>state.response?.kind==='ixAuction'); assert.equal(game.ixAuction?.cards.length,0); // Stage conserved held cards at the open native response, after CHOAM's // earlier market opportunity cannot sell the intended physical Kull. const printed = takeKullCard(game,'ix-kull-wahad'); seat(game,'c').hand.push(printed); const fuel = takeKullCard(game,'ix-hunter-seeker'); seat(game,'c').hand.push(fuel); const semuta = includeRichese ? takeKullCard(game,SEMUTA_DRUG_ID) : null; if (semuta) seat(game,'r').hand.push(semuta); assert.deepEqual(stock(game),original); game = act(game,'e',{type:'card',mode:'cancel',card:originalKarama.id}); assert.ok(game.pendingKull); assert.equal(game.pendingKull.resume.response?.kind,'ixAuction'); return {game,original,printed:printed.id,fuel:fuel.id,karama:originalKarama.id,counter:counter.id,semuta:semuta?.id,event:game.pendingKull.event}; } function passKullCounter(state: Game): Game { let game=state; while (game.pendingKull) { const actor = game.players.find(player => { const controls=viewGame(game,player.id).responseControls; return controls && !controls.hasPassed && controls.cancelCards.length > 0; }); game = actor ? act(game,actor.id,{type:'passResponse'}) : normalizeAutomaticGame(game); } return game; } function semutaReaction(state: Game, claim: boolean): Game { let game = state; const event = game.pendingTreacheryDiscard?.batch.event; assert.ok(event); if (claim) { game = act(game,'r',{type:'semutaCommit',event}); if (game.pendingTreacheryDiscard?.reaction?.stage === 'select') game = act(game,'r',{type:'semutaSelect',event,card:game.pendingTreacheryDiscard.batch.entries[0].card.id}); } else while (game.pendingTreacheryDiscard?.batch.event === event && game.pendingTreacheryDiscard.reaction?.stage === 'offer') { const reaction = game.pendingTreacheryDiscard.reaction; const actor = game.players.find(player => !reaction.passed.includes(player.id)); assert.ok(actor); game = act(game,actor.id,{type:'semutaPass',event}); } assert.notEqual(game.pendingTreacheryDiscard?.batch.event,event); return game; } for (const source of ['printed','nexus'] as const) for (const claim of [false,true]) void test( `Basic Ecaz/Moritani/Richese/Ixian Nexus auction survives ${source} Kull and Semuta ${claim?'claim':'pass'}`, () => { const f=fixture(); for (const difficulty of DIFFICULTIES) { const view=viewGame(f.game,'c'); view.players.find(player=>player.id==='c')!.bot=difficulty; const choice=botActions(view).find(action=>action.type==='kullDecision'); assert.ok(choice); assert.doesNotThrow(()=>act(f.game,'c',choice)); } assert.ok(viewGame(f.game,'c').kullReaction?.plays.some(play => play.source === source && play.card.id === (source === 'printed' ? f.printed : f.fuel)), `Missing ${source} option; hand: ${seat(f.game,'c').hand.map(card=>card.id).join(', ')}; discard: ${f.game.discard.map(card=>card.id).join(', ')}`); const cost = source === 'printed' ? f.printed : f.fuel; let game=act(f.game,'c',{type:'kullDecision',event:f.event,source,card:cost}); game=passKullCounter(game); assert.equal(game.pendingKull,null); assert.equal(seat(game,'e').hand.some(card=>card.id===f.karama),true); assert.equal(game.pendingTreacheryDiscard?.batch.entries[0].card.id,cost); assert.equal(game.pendingTreacheryDiscard?.batch.entries[0].publicFace,source === 'printed'); game=semutaReaction(game,claim); assert.equal(seat(game,'r').hand.some(card=>card.id===cost),claim); assert.equal(game.nexusCards!.cards!.hands.c,source === 'printed' ? 'choam' : null); game=advance(game,state=>!!state.pendingNexusIxianBetrayal); const nexus=game.pendingNexusIxianBetrayal!; assert.equal(viewGame(game,'a').nexusIxianBetrayalReaction?.canUse,true); for (const use of [false,true]) { let resumed = structuredClone(game); if (use) resumed=act(resumed,'a',{type:'nexusIxianBetrayalUse',event:nexus.source.event}); else while (resumed.pendingNexusIxianBetrayal) { const pending=resumed.pendingNexusIxianBetrayal; const actor=pending.required.find(id=>!pending.passed.includes(id)); assert.ok(actor); resumed=act(resumed,actor,{type:'nexusIxianBetrayalPass',event:pending.source.event}); } assert.equal(resumed.pendingNexusIxianBetrayal,null); if (!use) { assert.equal(resumed.decision?.kind,'ixAuction'); assert.ok(resumed.ixAuction?.cards.length); resumed=act(resumed,'ix',{type:'decision',card:resumed.ixAuction.cards[0].id,position:'top'}); } assert.equal(resumed.ixAuction,null); assert.ok(resumed.auction); assert.deepEqual(stock(resumed),f.original); } }); for (const claim of [false,true]) void test( `Basic Ecaz/Moritani/Richese/Ixian Nexus auction resumes original cancellation after Kull counter and Semuta ${claim?'claim':'pass'}`, () => { const f=fixture(); let game=act(f.game,'c',{type:'kullDecision',event:f.event,source:'nexus',card:f.fuel}); game=act(game,'a',{type:'card',mode:'cancel',card:f.counter}); assert.equal(game.pendingTreacheryDiscard?.batch.entries[0].card.id,f.counter); game=semutaReaction(game,claim); if (game.pendingTreacheryDiscard) { assert.equal(game.pendingTreacheryDiscard.batch.entries[0].card.id,f.karama); game=semutaReaction(game,false); } assert.equal(game.pendingKull,null); assert.equal(game.pendingNexusIxianBetrayal,null); assert.equal(game.ixAuction,null); assert.ok(game.auction); assert.equal(game.discard.some(card=>card.id===f.karama),true); assert.equal(seat(game,'c').hand.some(card=>card.id===f.fuel),true); assert.equal(game.nexusCards!.cards!.hands.c,null); assert.deepEqual(stock(game),f.original); }); for (const source of ['printed','nexus'] as const) void test( `Basic three-expansion Nexus auction retains ${source} Kull without Richese`, () => { const f = fixture(false), cost = source === 'printed' ? f.printed : f.fuel; let game = act(f.game,'c',{type:'kullDecision',event:f.event,source,card:cost}); game = passKullCounter(game); assert.equal(game.pendingKull,null); assert.equal(game.pendingTreacheryDiscard ?? null,null); assert.equal(game.discard.filter(card=>card.id===cost).length,1); assert.equal(game.nexusCards!.cards!.hands.c,source === 'printed' ? 'choam' : null); game = advance(game,state=>!!state.pendingNexusIxianBetrayal); const pending = game.pendingNexusIxianBetrayal!; game = act(game,'a',{type:'nexusIxianBetrayalUse',event:pending.source.event}); assert.equal(game.ixAuction,null); assert.ok(game.auction); assert.deepEqual(stock(game),f.original); }); void test('Basic three-expansion Nexus keeps Semuta when the host opts out of Kull', () => { let game = createGame('NXE3OPTOUT',newPlayer('ix','Ixians','ixians'),false,['ix','choam','ecaz']); for (const [id,faction] of [['m','moritani'],['c','choam'],['r','richese'],['a','atreides'],['e','ecaz']] as const) joinGame(game,newPlayer(id,faction,faction)); game = act(game,'ix',{type:'moduleOption',module:'nexusCards',enabled:true}); game = act(game,'ix',{type:'moduleOption',module:'kullPreview',enabled:false}); for (const player of game.players) game = act(game,player.id,{type:'ready'}); game = act(game,'ix',{type:'start'}); assert.equal(game.semutaPreview,true); assert.notEqual(game.kullPreview,true); assert.notEqual(game.nexusKullPreview,true); game = advance(game,state=>state.status==='playing'); assert.equal(game.ecazOccupyPreview,true); assert.equal(Object.values(seat(game,'e').forces).reduce((sum,n)=>sum+n,0),6); const original = stock(game); // Avoid unrelated battles while retaining every physical counter. for (const player of game.players) { player.reserves += Object.values(player.forces).reduce((sum,n)=>sum+n,0); player.forces={}; if (player.elites) {player.elites.reserves += Object.values(player.elites.forces).reduce((sum,n)=>sum+n,0); player.elites.forces={};} } orderSpice(game,['land','land']); game = advance(game,state=>state.turn===2 && state.phase===1 && clean(state)); assert.ok(game.ecazAmbassadors!.tokens.some(row=>row.effect==='ecaz' && row.location==='arrakeen')); assert.ok(game.moritaniTerror!.tokens.some(row=>row.kind==='robbery' && row.location==='carthag')); orderSpice(game,['land','land']); game = advance(game,state=>state.phase===5 && !!state.active && state.active!=='r' && clean(state)); const actor = game.active!; // Move existing cards, preserving the original physical stock. for (const player of game.players) game.deck.push(...player.hand.splice(0)); const hajr = takeKullCard(game,'hajr'); seat(game,actor).hand.push(hajr); const semuta = takeKullCard(game,SEMUTA_DRUG_ID); seat(game,'r').hand.push(semuta); assert.deepEqual(stock(game),original); const pending = act(game,actor,{type:'card',card:hajr.id}); assert.equal(pending.pendingTreacheryDiscard?.batch.cause,'ordinary:hajr'); assert.equal(viewGame(pending,'r').semutaReaction?.canCommit,true); for (const claim of [false,true]) { const resumed = semutaReaction(structuredClone(pending),claim); assert.equal(resumed.pendingTreacheryDiscard,null); assert.ok(resumed.hajr.includes(actor)); assert.equal(seat(resumed,'r').hand.some(card=>card.id===hajr.id),claim); assert.equal(resumed.discard.some(card=>card.id===semuta.id),claim); assert.deepEqual(stock(resumed),original); } });