diff --git a/components/emperor-auction-gift.tsx b/components/emperor-auction-gift.tsx index 721b125c..a588f976 100644 --- a/components/emperor-auction-gift.tsx +++ b/components/emperor-auction-gift.tsx @@ -22,6 +22,13 @@ export function EmperorAuctionGift({ game, act, busy }: {

{offer.source === 'richese' ? 'The winning bid and its committed ally payment split remain unchanged. Continue settles the Richese sale with that payment after any gift response.' : 'The winning bid and its committed ally payment split remain unchanged. Your ally chooses how to pay after the gift’s Karama response.'}

+ {game.pledgePromiseGuide && <> +

Set your promised ally funding before this purchase can close Bidding.

+ + } setRaw(event.target.value)} /> @@ -29,8 +36,8 @@ export function EmperorAuctionGift({ game, act, busy }: { onClick={() => { if (canShare) act({type:'emperorGift', amount}); }}> Share spice - ; diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index c8061f0f..d795f340 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -17,6 +17,16 @@ open mode gates. ## Current checkpoint and work +**Advanced Emperor auction gifts with expansion factions — 16 November. +Prototyped / Partial.** Supported selected-deck ordinary and Richese cache +auctions now retain the original winning lot and Advanced bank/seller payment +split through an allied gift or Continue. A live Truthtrance funding Yes can +be fulfilled at the opportunity; supported Advanced Semuta and printed Kull +can react to its cancellation. Genuine public-start journeys include waiting +Sandtrout and ordinary/cache auction pledges; 27 related unit files pass 147 cases. Black +Market, broader optional combinations, complete games and deployed acceptance +remain open. [Scope](EMPEROR_ALLIANCE_TIMING.md#advanced-selected-deck-allied-auction-gifts--16-november-2026). + **Advanced No-Field reveal during foreign movement — 16 November. Prototyped / Partial.** Supported foreign Fremen and Ixian movement responses and CHOAM movement decisions retain their original physical move while Richese reveals. @@ -66,9 +76,7 @@ open. [Scope](RICHESE_NO_FIELD_RULES.md#basic-reveal-at-emperor-auction-gifts--1 The latest bounded scan found first versions of the standalone Basic native faction powers inspected, with interaction and complete-game boundaries still -open. Advanced Emperor gifts before Richese cache sales and selected-expansion -ordinary auction payments remain a source-clear candidate; their Advanced -funding and bank routing still need implementation and evidence. +open. **Basic Emperor gifts while Sandtrout waits — 16 November. Prototyped / Partial.** Supported opening, ordinary auction and Richese cache gift windows diff --git a/docs/EMPEROR_ALLIANCE_TIMING.md b/docs/EMPEROR_ALLIANCE_TIMING.md index b9ec7ce6..57e08cd9 100644 --- a/docs/EMPEROR_ALLIANCE_TIMING.md +++ b/docs/EMPEROR_ALLIANCE_TIMING.md @@ -1,5 +1,39 @@ # Emperor alliance gift timing +## Advanced selected-deck allied auction gifts — 16 November 2026 + +**Prototyped / Partial.** Supported Advanced selected-deck games now offer the +Emperor's allied gift before an ordinary auction payment or a Richese Once +Around/Silent cache sale. Continue retains the original winning card, price and +funding split. A direct gift becomes the buyer's own spice; the Emperor's +separately pledged contribution follows the Advanced bank route. Allowing or +canceling the gift leaves the original purchase intact. A waiting Sandtrout does +not prevent an ordinary auction gift after a new alliance forms. + +An outstanding current-phase Truthtrance Yes limits the gift to an amount that +still permits its native ally-funding update. The Emperor may complete that +update within the gift opportunity, without changing the already committed bid +split; Continue waits for it because the purchase may close Bidding. The owner +receives the normal funding guide and bots use it. This ordering is a +provisional online interpretation. Advanced CHOAM-only Semuta can claim or +pass the actual Karama used to cancel this auction gift before the original +purchase resumes. Supported printed Kull can interrupt an ordinary auction +gift cancellation; other Advanced Semuta and Kull parents remain separately +bounded. + +The user-authorized revised rules physical p. 31 / printed p. 29 permit direct +allied transfers at any time; physical p. 15 / printed p. 13 distinguishes +direct gifts from the Emperor's bank-paid auction contributions. Public-start +[ordinary](../tests/emperor-auction-gift-advanced-native.test.ts), +[cache](../tests/emperor-richese-cache-gift-advanced-public.test.ts), +[Sandtrout](../tests/emperor-auction-gift-advanced-waiting-sandtrout.test.ts), +[pledge](../tests/emperor-auction-gift-advanced-pledge.test.ts), +[Semuta](../tests/emperor-auction-gift-advanced-semuta.test.ts) and +[Kull](../tests/emperor-auction-gift-advanced-kull.test.ts) journeys use +actual alliances and sales with disclosed staging of cards, wallets, forces or +unopened Spice order. Black Market, optional modules, broader combinations, +complete games and deployed acceptance remain open. + ## Advanced Emperor gift at a Guild rate response — 16 November 2026 **Prototyped / Partial.** In supported classic-faction Advanced games, the diff --git a/docs/RULE_DECISIONS.md b/docs/RULE_DECISIONS.md index 618e9569..1e5611c9 100644 --- a/docs/RULE_DECISIONS.md +++ b/docs/RULE_DECISIONS.md @@ -1,5 +1,12 @@ # Rule decision index +## Advanced selected-deck Emperor auction gifts — 16 November 2026 + +The existing provisional prepayment gift extends to supported Advanced +selected-deck ordinary and Richese cache auctions. Native split routing stays +unchanged; an outstanding funding Yes can be completed before Continue. +[Scope](EMPEROR_ALLIANCE_TIMING.md#advanced-selected-deck-allied-auction-gifts--16-november-2026). + ## Advanced No-Field reveal during foreign movement — 16 November 2026 The existing provisional reveal ordering extends to supported Advanced foreign diff --git a/game/bots.ts b/game/bots.ts index 373e158c..ddaeafd8 100644 --- a/game/bots.ts +++ b/game/bots.ts @@ -4391,7 +4391,7 @@ export function botActions(g: GameView): Action[] { return (me?.bot || me?.autopilot) && g.status === 'playing' && !g.roomControl?.paused && !g.roomControl?.closed && !g.automaticContinuationPending && g.emperorAuctionGift - ? [{type: 'emperorAuctionGiftContinue', event: g.emperorAuctionGift.event}] : []; + ? [g.pledgePromiseGuide?.action ?? {type: 'emperorAuctionGiftContinue', event: g.emperorAuctionGift.event}] : []; } if (g.victoryContinuation) return g.status === 'playing' && !g.roomControl?.paused && !g.roomControl?.closed && !g.automaticContinuationPending diff --git a/game/engine.ts b/game/engine.ts index 37c015a1..d7ab79d7 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -10248,6 +10248,8 @@ function semutaOfferSupported( continuation.kind === 'battleCleanup' && continuation.source === 'winner' || continuation.kind === 'nullentropyDiscard' || continuation.kind === 'distransDiscard' || continuation.kind === 'residualPoisonDiscard' || continuation.kind === 'choamSaleDiscard' || + continuation.kind === 'karamaEmperorShareDiscard' && + emperorAuctionGiftResumeMatches(g, continuation.use.response, continuation.resume.decision) || ((continuation.kind === 'choamKulonDiscard' || continuation.kind === 'choamLaLaLaDiscard' || continuation.kind === 'choamBalisetDiscard' || continuation.kind === 'choamGamontDiscard' || continuation.kind === 'choamJubbaDiscard') && continuation.nexusEvent === undefined) || @@ -17136,10 +17138,12 @@ function reconcilePledgeCommitments(g: Game, voluntary?: {actor: string; action: })); } function projectedPledgeGuide(g: Game, player: Player): {action: Action} | null { - if (!pledgeQuestionWindow(g) || g.truthtrance || !livePledgePromises(g.pledgePromises ?? [], player.id, g.turn, g.phase) + const auctionGift = g.pendingEmperorAuctionGift?.owner === player.id && !g.response && !g.pendingKarama && !g.pendingKull; + if ((!pledgeQuestionWindow(g) && !auctionGift) || g.truthtrance || !livePledgePromises(g.pledgePromises ?? [], player.id, g.turn, g.phase) .some(row => row.answer)) return null; const action = pledgeCompletion(g, player); - return action ? {action} : null; + return action ? {action:auctionGift + ? {...action, emperorAuctionGiftEvent:g.pendingEmperorAuctionGift!.event} : action} : null; } function alliancePromiseRule(calculate: () => T): T { try { return calculate(); } @@ -19237,9 +19241,9 @@ function emperorAuctionGiftSignature(g: Game): string { return JSON.stringify([g.turn, g.phase, g.active, g.decision ?? emperorAuctionGiftParked(g)?.decision, g.order, g.auction, g.aid]); } function beginEmperorRicheseAuctionGift(g: Game, quote: Extract, bank = false): boolean { - if (g.advanced || g.status !== 'playing' || g.phase !== 3 || g.richeseAuction?.source !== 'cache' || + if (g.status !== 'playing' || g.phase !== 3 || g.richeseAuction?.source !== 'cache' || g.techTokens || g.strongholdCards || g.leaderSkills || g.homeworlds || - g.discoveryEnabled || g.coalitionState || g.ecazTreachery || + (g.advanced && g.nexusCards) || g.discoveryEnabled || g.coalitionState || g.ecazTreachery || g.pendingEmperorAuctionGift || g.response || g.decision || g.phaseOpening || g.truthtrance || g.pendingKarama || g.pendingTreacheryDiscard || g.pendingRicheseGift || g.pendingNullentropy || g.pendingRicheseBetrayal || g.pendingNexusEmperorSellerPurchase || @@ -19255,10 +19259,10 @@ function beginEmperorRicheseAuctionGift(g: Game, quote: Extract !['atreides', 'beneGesserit', 'emperor', 'fremen', 'guild', 'harkonnen'].includes(seat.faction)) - : g.expansions.length > 0 && !selectedPhaseModuleRoster(g)) || + (g.expansions.length > 0 ? !selectedPhaseModuleRoster(g) : + g.advanced && g.players.some(seat => !['atreides', 'beneGesserit', 'emperor', 'fremen', 'guild', 'harkonnen'].includes(seat.faction))) || g.techTokens || g.strongholdCards || g.leaderSkills || g.homeworlds || (g.advanced && g.nexusCards) || - g.discoveryEnabled || (g.advanced && g.sandtrout) || g.coalitionState || g.pendingEmperorAuctionGift || + g.discoveryEnabled || g.coalitionState || g.pendingEmperorAuctionGift || g.response || g.phaseOpening || g.truthtrance || g.pendingKarama || g.pendingTreacheryDiscard || g.pendingRicheseGift || g.pendingNullentropy || g.currentAuctionSale || g.richeseAuction || g.ixAuction || @@ -19317,7 +19321,23 @@ function emperorAuctionGiftMaximum(g: Game, p: Player): number { liveRevivalExpressionPromises(g.revivalExpressionPromises ?? [], p.id, g.turn).some(row => row.answer) || liveTurnActionPromises(g.turnActionPromises ?? [], p.id, g.turn).length || livePhaseBidPromises(g.phaseBidPromises ?? [], p.id, g.turn).some(row => row.answer)) return 0; - return Math.max(0, uncommittedSpice(g, p)); + const maximum = Math.max(0, uncommittedSpice(g, p)); + if (!livePledgePromises(g.pledgePromises ?? [], p.id, g.turn, g.phase).some(row => row.answer)) return maximum; + // The owner can fulfill the native update within this opportunity, before + // the sale consumes its locked aid or the Bidding phase can end. + const trial = structuredClone(g); + const canSpend = (amount: number) => { + const sample = structuredClone(trial), player = getPlayer(sample, p.id); + player.spice -= amount; + return !!pledgeCompletion(sample, player); + }; + if (!canSpend(0)) return 0; + let low = 0, high = maximum; + while (low < high) { + const mid = low + Math.ceil((high - low) / 2); + if (canSpend(mid)) low = mid; else high = mid - 1; + } + return low; } function settleAuction(g: Game, free = false, automatic = false, emperorNexus = false) { const a = g.auction!; @@ -21087,7 +21107,10 @@ function spendKarama(g: Game, p: Player, card: Card, use: KaramaUse, kullOffered stageTreacheryDiscard(g, 'karama:kullCounter', [{card:used, discardedBy:p.id, publicFace:true}], continuation); return; } - const semutaRoleCost = semutaCardProducerEnabled(g) && semutaKaramaRoleCost(g, p.id, card); + const advancedAuctionGiftCost = g.semutaAdvancedOrdinaryPreview === true && bareAdvancedClassicSemutaProfile(g) && + use.kind === 'cancel' && use.response.kind === 'emperorGift' && + emperorAuctionGiftResumeMatches(g, use.response, g.decision); + const semutaRoleCost = (semutaCardProducerEnabled(g) || advancedAuctionGiftCost) && semutaKaramaRoleCost(g, p.id, card); const guildShipmentDiscard = semutaRoleCost && use.kind === 'cancel' && semutaGuildShipmentKaramaResponse(g, use.response); const bgConversionCancelDiscard = semutaRoleCost && @@ -43886,6 +43909,10 @@ export function applyAction(state: Game, id: string, action: Action): Game { * automatic deal payment; it is never supplied by a client action. */ function applyActionWithInitiator(state: Game, id: string, action: Action, initiator: string, options?: {insolventDealPayment?: boolean;publicDealSettlement?:string}): Game { + if (action?.emperorAuctionGiftEvent !== undefined) + requireRule(action.type === 'pledgeAid' && state.pendingEmperorAuctionGift?.owner === id && + state.pendingEmperorAuctionGift.event === action.emperorAuctionGiftEvent, + 'This auction funding guide is no longer current.'); emperorPhaseOpeningGiftIntegrity(state); emperorExtortionGiftIntegrity(state); emperorAuctionGiftIntegrity(state); @@ -45179,9 +45206,23 @@ function applyActionInner( const pending = g.pendingEmperorAuctionGift; if (t === 'advanceBots') return g; requireRule(id === pending.owner, 'Wait for the Emperor to finish the allied gift opportunity.'); + if (t === 'pledgeAid') { + requireRule((Object.keys(action).sort().join(',') === 'amount,type' || + Object.keys(action).sort().join(',') === 'amount,emperorAuctionGiftEvent,type' && + action.emperorAuctionGiftEvent === pending.event) && + livePledgePromises(g.pledgePromises ?? [], id, g.turn, g.phase).some(row => row.answer), + 'Only your current Truthtrance funding update is available during this opportunity.'); + pledgeAid(g, p, action.amount); + g.pledgePromises = pledgeRule(() => recordPromisedPledge( + g.pledgePromises!, p.id, g.turn, g.phase, {ally:p.ally!, amount:action.amount as number})); + pending.signature = emperorAuctionGiftSignature(g); + return g; + } if (t === 'emperorAuctionGiftContinue') { requireRule(Object.keys(action).sort().join(',') === 'event,type' && action.event === pending.event, 'This Emperor auction opportunity is no longer current.'); + requireRule(!livePledgePromises(g.pledgePromises ?? [], id, g.turn, g.phase).some(row => row.answer), + 'Set your promised ally funding before this purchase can close Bidding.'); g.pendingEmperorAuctionGift = null; if (pending.source === 'richese') { requireRule(pending.quote, 'The Richese auction gift lost its committed sale.'); diff --git a/game/reference.ts b/game/reference.ts index 1740a1e8..c27d0b28 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -298,6 +298,7 @@ export const RULE_TOPICS: RuleTopic[] = [ 'The recipient keeps paid spice separately until the next Mentat opening. A payment after the current opening waits for next turn’s opening. Your incoming bribes are shown separately from your spendable supply; they cannot fund bids, shipments or another bribe yet.', 'A waiting Sandtrout does not prevent the supported Basic bribe interruption windows.', 'During supported Basic phase openings, auction payments, Richese cache sales and Extortion decisions, a waiting Sandtrout does not prevent the Emperor gifting spice to an ally formed after the Sandtrout draw.', + 'In supported Advanced selected-deck auctions, the Emperor may gift spice before an allied ordinary purchase or Richese cache sale. The original split remains: direct gifts are the buyer’s spice, while the Emperor’s pledged share goes to the bank. A promised funding update can be completed before continuing.', 'In supported classic Advanced games, the Emperor may share spice before a pending Guild shipment-rate response continues. Allowing or canceling the gift returns to the same rate decision and shipment.', 'You may pay out of turn when no decision or response is pending, including during Mentat after opening collection. In supported Basic games with classic or selected native expansion factions, direct bribes can also interrupt a normal auction-payment decision, Atreides auction inspection, Fremen allied-revival grant, ordinary Fremen or Ixian movement response, or CHOAM movement decision. Supported Basic Ix and Moritani games also allow payments during the Amal opening or an Extortion choice. The original parent and its passes remain pending. You cannot bribe yourself or your ally, or while Inflation shows Double. Emperor gifts to allies use their own power controls.', 'Your payment limit excludes reserved spending and preserves binding Truthtrance answers. If an alliance, pending decision or available supply changes, recheck the recipient and amount. A rejected payment does not change the game.', diff --git a/tests/emperor-auction-gift-advanced-kull.test.ts b/tests/emperor-auction-gift-advanced-kull.test.ts new file mode 100644 index 00000000..009fe1f2 --- /dev/null +++ b/tests/emperor-auction-gift-advanced-kull.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {createGame, joinGame, newPlayer, viewGame, type Game} from '../game/engine'; +import {actKullPurpose as act, advanceKullPurpose as advance, kullPurposeClean as clean, + kullPurposePlayer as seat} from './fixture-kull-purpose'; +import {publicKullInventory as inventory} from './fixture-public-choam-kull'; +import {takeKullCard} from './fixture-choam-kull'; +import {beforeIxSpiceDraw, orderIxSpiceCards} from './fixture-ix-spice-cards'; + +/** Real public Advanced CHOAM+Ix setup with selected printed Kull, natural + * worm/alliance and native ordinary bidding. Unopened Spice order, conserved + * initial board forces, physical cards and auction wallets are staged. */ +function fixture() { + let g=createGame('ADVAUCTIONKULL',newPlayer('choam','CHOAM','choam'),true,['choam','ix']); + for(const id of ['emperor','guild','atreides'] as const)joinGame(g,newPlayer(id,id,id)); + g=act(g,'choam',{type:'moduleOption',module:'kullPreview',enabled:true}); + for(const p of g.players)g=act(g,p.id,{type:'ready'}); + g=act(g,'choam',{type:'start',advancedPreview:true});assert.equal(g.kullPreview,true); + g=advance(g,s=>s.status==='playing'); + for(const p of g.players){p.reserves+=Object.values(p.forces).reduce((sum,n)=>sum+n,0);p.forces={};} + g=advance(g,beforeIxSpiceDraw);orderIxSpiceCards(g,['land','land']); + g=advance(g,s=>s.turn===2&&beforeIxSpiceDraw(s));orderIxSpiceCards(g,['worm','land','land']); + g=advance(g,s=>!!s.nexus&&!s.spiceWindow&&clean(s)); + g=act(g,'emperor',{type:'alliance',target:'guild'});g=act(g,'guild',{type:'alliance',target:'emperor'}); + g=advance(g,s=>s.phase===3&&s.phaseOpening?.initialize===true); + const cards=inventory(g); + for(const p of g.players)g.deck.push(...p.hand.splice(0)); + const kull=takeKullCard(g,'ix-kull-wahad');seat(g,'choam').hand.push(kull); + const cost=takeKullCard(g,'karama');seat(g,'atreides').hand.push(cost); + const counter=takeKullCard(g,'karama');seat(g,'guild').hand.push(counter); + seat(g,'emperor').spice=8;seat(g,'guild').spice=7; + assert.deepEqual(inventory(g),cards); + g=advance(g,s=>s.phase===3&&!!s.auction&&clean(s)); + while(g.auction!.active!=='guild')g=act(g,g.auction!.active,{type:'passBid'}); + const card=g.auction!.cards[g.auction!.index].id; + g=act(g,'emperor',{type:'pledgeAid',amount:1}); + g=act(g,'guild',{type:'bid',amount:3,allyPayment:1}); + for(let n=0;g.auction&&!g.response&&!g.decision&&n<15;n++)g=act(g,g.auction.active,{type:'passBid'}); + assert.equal(g.decision?.kind,'auctionPayment'); + const offer=viewGame(g,'emperor').emperorAuctionGift;assert.ok(offer); + return {g,card,kull:kull.id,cost:cost.id,counter:counter.id,cards,event:offer.event}; +} +function finishGift(g:Game) { + for(let n=0;g.response?.kind==='emperorGift'&&n<20;n++) { + const p=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(p); + g=act(g,p.id,{type:'passResponse'}); + } + return g; +} +function finishSale(g:Game,event:string) { + g=act(g,'emperor',{type:'emperorAuctionGiftContinue',event}); + if(g.decision?.kind==='auctionPayment')g=act(g,'guild',{type:'decision',karama:false}); + for(let n=0;g.response&&n<20;n++) { + const p=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(p); + g=act(g,p.id,{type:'passResponse'}); + } + return g; +} + +for(const mode of ['decline','successful','countered'] as const) void test( + `Advanced printed Kull ${mode} preserves the allied ordinary auction gift and physical cards`,()=>{ + const f=fixture(),before=structuredClone(f.g), lot=structuredClone(f.g.auction),aid=structuredClone(f.g.aid); + let g=act(f.g,'emperor',{type:'emperorGift',amount:2}); + g=act(g,'atreides',{type:'card',mode:'cancel',card:f.cost}); + assert.equal(g.pendingKull?.stage,'offer'); + const event=g.pendingKull!.event; + if(mode==='decline')g=act(g,'choam',{type:'kullDecision',event,decline:true}); + else { + g=act(g,'choam',{type:'kullDecision',event,source:'printed',card:f.kull}); + assert.equal(g.pendingKull?.stage,'counter'); + if(mode==='countered')g=act(g,'guild',{type:'card',mode:'cancel',card:f.counter}); + else for(let n=0;g.pendingKull?.stage==='counter'&&g.response&&n<20;n++) { + const p=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(p); + g=act(g,p.id,{type:'passResponse'}); + } + } + g=finishGift(g); + assert.equal(viewGame(g,'emperor').emperorAuctionGift?.event,f.event); + assert.deepEqual(g.auction,lot);assert.deepEqual(g.aid,aid); + const transferred=mode==='successful'; + assert.equal(seat(g,'guild').spice,seat(before,'guild').spice+(transferred?2:0)); + assert.equal(seat(g,'emperor').spice,seat(before,'emperor').spice-(transferred?2:0)); + assert.equal(seat(g,'atreides').hand.some(card=>card.id===f.cost),transferred); + g=finishSale(g,f.event); + assert.ok(seat(g,'guild').hand.some(card=>card.id===f.card)); + assert.deepEqual(inventory(g),f.cards); + }); diff --git a/tests/emperor-auction-gift-advanced-native.test.ts b/tests/emperor-auction-gift-advanced-native.test.ts new file mode 100644 index 00000000..e2d3e523 --- /dev/null +++ b/tests/emperor-auction-gift-advanced-native.test.ts @@ -0,0 +1,94 @@ +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 {botActions, runBots} from '../game/bots'; +import {DIFFICULTIES} from '../game/bot-profiles'; +import {advanceSemutaNexusTrade} from './fixture-semuta-nexus-trade'; +import {beforeIxSpiceDraw, orderIxSpiceCards} from './fixture-ix-spice-cards'; + +const act=(g:Game,id:string,action:Action)=>applyAction(g,id,action); +const seat=(g:Game,id:string)=>{const p=g.players.find(row=>row.id===id);assert.ok(p);return p;}; +const quiet=(g:Game)=>!g.response&&!g.decision&&!g.phaseOpening&&!g.truthtrance&&!g.pendingTreacheryDiscard; +function inventory(g:Game) { + const cards=[...g.deck,...g.discard,...(g.richeseCache??[]),...(g.richeseRemoved??[]), + ...(g.auction?.cards.slice(g.auction.index+Number(g.currentAuctionSale?.origin==='normal'))??[]), + ...(g.ixAuction?.cards??[]),...g.players.flatMap(p=>p.hand)].map(card=>card.id).sort(); + assert.equal(new Set(cards).size,cards.length);return cards; +} +/** Actual public Advanced selected-deck setup, second-turn worm, mutual + * alliance and native auction. Unopened Spice order, conserved board pieces, + * physical card custody and wallets are selected for this paid example. */ +function fixture() { + let g=createGame('ADVANCEDNATIVEGIFT',newPlayer('c','CHOAM','choam'),true,['choam','ix']); + for(const [id,faction] of [['r','richese'],['e','emperor'],['h','harkonnen'],['a','atreides']] as const) + joinGame(g,newPlayer(id,faction,faction)); + for(const p of g.players)g=act(g,p.id,{type:'ready'}); + g=act(g,'c',{type:'start',advancedPreview:true}); + g=advanceSemutaNexusTrade(g,s=>s.status==='playing'); + const original=inventory(g); + for(const p of g.players) {p.reserves+=Object.values(p.forces).reduce((sum,n)=>sum+n,0);p.forces={};} + g=advanceSemutaNexusTrade(g,beforeIxSpiceDraw);orderIxSpiceCards(g,['land','land']); + g=advanceSemutaNexusTrade(g,s=>s.turn===2&&beforeIxSpiceDraw(s));orderIxSpiceCards(g,['worm','land','land']); + g=advanceSemutaNexusTrade(g,s=>!!s.nexus&&!s.spiceWindow&&quiet(s)); + g=act(g,'e',{type:'alliance',target:'h'});g=act(g,'h',{type:'alliance',target:'e'}); + g=advanceSemutaNexusTrade(g,s=>s.phase===3&&s.phaseOpening?.initialize===true); + for(const p of g.players)g.deck.push(...p.hand.splice(0)); + const counterIndex=g.deck.findIndex(card=>card.effect==='karama');assert.ok(counterIndex>=0); + const [counter]=g.deck.splice(counterIndex,1);seat(g,'a').hand.push(counter); + seat(g,'e').spice=8;seat(g,'h').spice=6; + g=advanceSemutaNexusTrade(g,s=>s.phase===3&&!!s.auction&&!s.richeseAuction&&quiet(s)); + while(g.auction!.active!=='h')g=act(g,g.auction!.active,{type:'passBid'}); + g=act(g,'e',{type:'pledgeAid',amount:2}); + const card=g.auction!.cards[g.auction!.index].id; + g=act(g,'h',{type:'bid',amount:6,allyPayment:2}); + for(let n=0;g.auction&&!g.response&&!g.decision&&n<20;n++)g=act(g,g.auction.active,{type:'passBid'}); + assert.equal(g.decision?.kind,'auctionPayment'); + const offer=viewGame(g,'e').emperorAuctionGift;assert.ok(offer,'Allied buyer receives an Emperor gift opportunity'); + assert.deepEqual(inventory(g),original); + return {g,card,original,counter:counter.id,event:offer.event}; +} +function settleInterrupts(g:Game) { + for(let n=0;n<60;n++) { + if(g.pendingKull?.stage==='offer') {g=act(g,g.pendingKull.player,{type:'kullDecision',event:g.pendingKull.event,decline:true});continue;} + if(g.pendingTreacheryDiscard?.reaction?.stage==='offer') { + const pending=g.pendingTreacheryDiscard,reaction=pending.reaction; + if(!reaction || reaction.stage!=='offer') throw Error('Discard offer disappeared'); + const p=g.players.find(row=>!reaction.passed.includes(row.id));assert.ok(p); + g=act(g,p.id,{type:'semutaPass',event:pending.batch.event});continue; + } + if(g.response) {const p=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(p);g=act(g,p.id,{type:'passResponse'});continue;} + return g; + } + throw Error('Auction response did not settle'); +} + +for(const cancel of [false,true]) void test(`Advanced native auction allied gift ${cancel?'cancels':'allows'} and pays its original split`,()=>{ + const f=fixture(),before=structuredClone(f.g), auction=structuredClone(f.g.auction),aid=structuredClone(f.g.aid); + let g=act(f.g,'e',{type:'emperorGift',amount:2});assert.equal(g.response?.kind,'emperorGift'); + if(cancel)g=act(g,'a',{type:'card',mode:'cancel',card:f.counter}); + g=settleInterrupts(g); + assert.deepEqual(g.auction,auction);assert.deepEqual(g.aid,aid); + assert.equal(g.pendingEmperorAuctionGift?.event,f.event); + assert.equal(seat(g,'h').spice,seat(before,'h').spice+(cancel?0:2)); + assert.equal(seat(g,'e').spice,seat(before,'e').spice-(cancel?0:2)); + for(const difficulty of DIFFICULTIES) { + const view=viewGame(g,'e');view.players.find(p=>p.id==='e')!.bot=difficulty; + const action=botActions(view).find(row=>row.type==='emperorAuctionGiftContinue');assert.ok(action,difficulty); + assert.doesNotThrow(()=>act(g,'e',action),difficulty); + } + g=act(g,'e',{type:'emperorAuctionGiftContinue',event:f.event}); + if(g.decision?.kind==='auctionPayment')g=act(g,'h',{type:'decision',karama:false}); + g=settleInterrupts(g); + assert.ok(seat(g,'h').hand.some(row=>row.id===f.card)); + assert.equal(g.aid.e?.amount??0,0); + assert.equal(seat(g,'h').spice,seat(before,'h').spice+(cancel?0:2)-4); + assert.equal(seat(g,'e').spice,seat(before,'e').spice-(cancel?0:2)+4, + 'Only the buyer-funded share returns as Emperor income; the Emperor pledge goes to the bank'); + assert.deepEqual(inventory(g),f.original); +}); + +void test('an Advanced native bot Emperor can continue the original auction automatically',()=>{ + const {g,card}=fixture();seat(g,'e').bot='Medium'; + const done=runBots(g,8); + assert.ok(seat(done,'h').hand.some(row=>row.id===card)); +}); diff --git a/tests/emperor-auction-gift-advanced-pledge.test.ts b/tests/emperor-auction-gift-advanced-pledge.test.ts new file mode 100644 index 00000000..99de80b9 --- /dev/null +++ b/tests/emperor-auction-gift-advanced-pledge.test.ts @@ -0,0 +1,171 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {handLimit, viewGame, type Game} from '../game/engine'; +import {botActions} from '../game/bots'; +import {DIFFICULTIES} from '../game/bot-profiles'; +import {actTruthAlliance as act, advanceTruthAlliance as advance, createTruthAllianceFixture, + truthAllianceClean as clean, truthAllianceInventory as inventory, + truthAlliancePlayer as player} from './fixture-truth-alliance'; +import {declareTruthBribe} from './fixture-truth-bribe'; + +/** Original Advanced Harkonnen/Atreides/Emperor setup; a real turn-two worm + * and mutual alliance precede the actual Truthtrance and paid winning bid. + * The shared fixture selects only unopened deal and Spice order/lotteries. */ +function fixture(answer:'yes'|'no', soleLot=false, winningAid=0) { + const f=createTruthAllianceFixture({advanced:true,consent:'allied'}); + let game=structuredClone(f.game); + if(soleLot) { + // Before Bidding, make only the allied buyer eligible for a dealt lot. + // All transfers use original physical cards and preserve the inventory. + for(const id of [f.target,f.asker]) { + const holder=player(game,id); + while(holder.hand.length=handLimit(buyer))game.deck.push(buyer.hand.pop()!); + } + game=advance(game,state=>state.phase===3&&!!state.auction&&clean(state)); + if(soleLot)assert.equal(game.auction?.cards.length,1,'Only the buyer had room for a lot'); + if(winningAid)game=act(game,f.target,{type:'pledgeAid',amount:winningAid}); + game=declareTruthBribe(f,game).game; + game=act(game,f.asker,{type:'truthAsk',question:{kind:'pledgeAid',target:f.target, + turn:game.turn,phase:3,ally:f.partner,minimum:4}}); + assert.ok(viewGame(game,f.target).truthPledgeAnswers?.includes(answer)); + game=act(game,f.target,{type:'truthAnswer',answer}); + const originalPromise=structuredClone(game.pledgePromises?.at(-1));assert.ok(originalPromise); + assert.equal(originalPromise.answer,answer==='yes'); + assert.equal(originalPromise.fulfilled??false,false);assert.equal(originalPromise.released??false,false); + while(game.auction?.active!==f.partner) { + assert.ok(game.auction&&!game.decision&&!game.response); + game=act(game,game.auction.active,{type:'passBid'}); + } + game=act(game,f.partner,{type:'bid',amount:1+winningAid,allyPayment:winningAid}); + for(let n=0;game.auction&&!game.decision&&!game.response&&!game.pendingEmperorAuctionGift&&n<15;n++) + game=act(game,game.auction.active,{type:'passBid'}); + assert.equal(game.decision?.kind,'auctionPayment'); + const offer=viewGame(game,f.target).emperorAuctionGift;assert.ok(offer); + assert.equal(offer.recipient,f.partner); + const publicOffer=viewGame(game,f.asker).emperorAuctionGiftPending; + assert.deepEqual(publicOffer,{owner:f.target}); + assert.equal(viewGame(game,f.asker).emperorAuctionGift,null); + return {f,game,offer,originalPromise}; +} +function settleGift(game:Game):Game { + for(let n=0;game.response?.kind==='emperorGift'&&n<20;n++) { + const responder=game.players.find(row=>!game.response!.passed.includes(row.id));assert.ok(responder); + game=act(game,responder.id,{type:'passResponse'}); + } + return game; +} + +void test('a live Advanced pledge Yes allows exactly the excess spice as an allied auction gift',()=>{ + const {f,game,offer,originalPromise}=fixture('yes'); + assert.equal(offer.maximum,player(game,f.target).spice-4); + assert.ok(offer.maximum>0); + const before=structuredClone(game); + assert.throws(()=>act(game,f.target,{type:'emperorGift',amount:offer.maximum+1})); + assert.deepEqual(game,before); + const shared=settleGift(act(game,f.target,{type:'emperorGift',amount:offer.maximum})); + assert.equal(player(shared,f.target).spice,4); + assert.deepEqual(shared.pledgePromises?.at(-1),originalPromise); + const beforeContinue=structuredClone(shared); + assert.throws(()=>act(shared,f.target,{type:'emperorAuctionGiftContinue',event:offer.event})); + assert.deepEqual(shared,beforeContinue); + const guide=viewGame(shared,f.target).pledgePromiseGuide;assert.ok(guide); + const pledged=act(shared,f.target,guide.action); + assert.equal(pledged.pledgePromises?.at(-1)?.fulfilled,true); + assert.deepEqual(pledged.auction,shared.auction); + const continued=act(pledged,f.target,{type:'emperorAuctionGiftContinue',event:offer.event}); + assert.equal(continued.pendingEmperorAuctionGift??null,null); + assert.equal(continued.pledgePromises?.at(-1)?.fulfilled,true); + assert.deepEqual(inventory(continued),f.originalCards); +}); + +void test('a No-only Advanced pledge answer does not suppress an otherwise legal allied auction gift',()=>{ + const {f,game,offer,originalPromise}=fixture('no'); + assert.equal(offer.maximum,player(game,f.target).spice); + assert.ok(offer.maximum>0); + const shared=settleGift(act(game,f.target,{type:'emperorGift',amount:offer.maximum})); + assert.equal(player(shared,f.target).spice,0); + assert.deepEqual(shared.pledgePromises?.at(-1),originalPromise); + const continued=act(shared,f.target,{type:'emperorAuctionGiftContinue',event:offer.event}); + assert.equal(continued.pendingEmperorAuctionGift??null,null); + assert.deepEqual(continued.pledgePromises?.at(-1),originalPromise); + assert.deepEqual(inventory(continued),f.originalCards); +}); + +for(const soleLot of [false,true]) void test( + `a pending Advanced allied gift permits the native pledge guide${soleLot?' on the sole lot':''}` ,()=>{ + const {f,game,offer}=fixture('yes',soleLot); + const lot=structuredClone(game.auction), saleCard=lot!.cards[lot!.index].id; + const guide=viewGame(game,f.target).pledgePromiseGuide;assert.ok(guide); + assert.deepEqual(guide.action,{type:'pledgeAid',amount:4,emperorAuctionGiftEvent:offer.event}); + const beforeStale=structuredClone(game); + assert.throws(()=>act(game,f.target,{...guide.action,emperorAuctionGiftEvent:'stale-event'})); + assert.deepEqual(game,beforeStale); + assert.equal(viewGame(game,f.asker).pledgePromiseGuide,null); + for(const difficulty of DIFFICULTIES) { + const view=viewGame(game,f.target);view.players.find(row=>row.id===f.target)!.bot=difficulty; + const action=botActions(view)[0];assert.ok(action,difficulty); + assert.deepEqual(action,guide.action,`${difficulty} fulfills the pledge before Continue`); + const bot=act(game,f.target,action); + assert.equal(bot.pledgePromises?.at(-1)?.fulfilled,true); + assert.deepEqual(bot.auction,lot); + assert.equal(bot.pendingEmperorAuctionGift?.event,offer.event); + } + const pledged=act(game,f.target,guide.action); + assert.equal(pledged.pledgePromises?.at(-1)?.fulfilled,true); + assert.equal(pledged.aid[f.target]?.amount,4); + assert.deepEqual(pledged.auction,lot); + assert.equal(pledged.auction?.allyPayment,0,'The earlier winning split is not changed'); + assert.equal(pledged.pendingEmperorAuctionGift?.event,offer.event); + let continued=act(pledged,f.target,{type:'emperorAuctionGiftContinue',event:offer.event}); + assert.equal(continued.pendingEmperorAuctionGift??null,null); + assert.throws(()=>act(continued,f.target,guide.action),'A stale guide cannot create a later funding update'); + for(let n=0;!player(continued,f.partner).hand.some(card=>card.id===saleCard)&&n<20;n++) { + if(continued.decision?.kind==='auctionPayment') + continued=act(continued,f.partner,{type:'decision',karama:false}); + else if(continued.response) { + const actor=continued.players.find(row=>!continued.response!.passed.includes(row.id));assert.ok(actor); + continued=act(continued,actor.id,{type:'passResponse'}); + } else throw Error('The original winning purchase lost its payment continuation'); + } + assert.equal(continued.pledgePromises?.at(-1)?.fulfilled,true); + assert.ok(player(continued,f.partner).hand.some(card=>card.id===saleCard)); + assert.deepEqual(inventory(continued),f.originalCards); + }); + +void test('the Advanced pledge guide preserves a winning bid’s existing two-spice allied contribution',()=>{ + const {f,game,offer}=fixture('yes',false,2); + const lot=structuredClone(game.auction);assert.ok(lot); + const card=lot.cards[lot.index].id; + assert.equal(lot.bid,3);assert.equal(lot.allyPayment,2); + assert.equal(game.aid[f.target]?.amount,2); + const buyerBefore=player(game,f.partner).spice,emperorBefore=player(game,f.target).spice; + const guide=viewGame(game,f.target).pledgePromiseGuide;assert.ok(guide); + assert.deepEqual(guide.action,{type:'pledgeAid',amount:4,emperorAuctionGiftEvent:offer.event}); + let next=act(game,f.target,guide.action); + assert.equal(next.pledgePromises?.at(-1)?.fulfilled,true); + assert.equal(next.aid[f.target]?.amount,4); + assert.deepEqual(next.auction,lot); + assert.equal(next.pendingEmperorAuctionGift?.event,offer.event); + next=act(next,f.target,{type:'emperorAuctionGiftContinue',event:offer.event}); + for(let n=0;!player(next,f.partner).hand.some(row=>row.id===card)&&n<20;n++) { + if(next.decision?.kind==='auctionPayment')next=act(next,f.partner,{type:'decision',karama:false}); + else if(next.response) { + const actor=next.players.find(row=>!next.response!.passed.includes(row.id));assert.ok(actor); + next=act(next,actor.id,{type:'passResponse'}); + } else throw Error('The original winning purchase lost its payment continuation'); + } + assert.ok(player(next,f.partner).hand.some(row=>row.id===card)); + for(let n=0;next.response?.kind==='emperorIncome'&&n<20;n++) { + const actor=next.players.find(row=>!next.response!.passed.includes(row.id));assert.ok(actor); + next=act(next,actor.id,{type:'passResponse'}); + } + assert.equal(player(next,f.partner).spice,buyerBefore-1,'The buyer pays the original one-spice share'); + assert.equal(next.aid[f.target]?.amount,2,'Only the original two-spice winning contribution is consumed'); + assert.equal(player(next,f.target).spice,emperorBefore-2+1, + 'The additional pledge remains escrowed; only the buyer-funded share reaches the Emperor'); + assert.equal(next.pledgePromises?.at(-1)?.fulfilled,true); + assert.deepEqual(inventory(next),f.originalCards); +}); diff --git a/tests/emperor-auction-gift-advanced-semuta.test.ts b/tests/emperor-auction-gift-advanced-semuta.test.ts new file mode 100644 index 00000000..a419759e --- /dev/null +++ b/tests/emperor-auction-gift-advanced-semuta.test.ts @@ -0,0 +1,114 @@ +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 {SEMUTA_DRUG_ID} from '../game/semuta-drug'; +import {advanceSemutaNexusTrade, nextSemutaNexusTradeNativeStep} from './fixture-semuta-nexus-trade'; +import {beforeIxSpiceDraw, orderIxSpiceCards} from './fixture-ix-spice-cards'; + +const act=(g:Game,id:string,action:Action)=>applyAction(g,id,action); +const seat=(g:Game,id:string)=>{const p=g.players.find(row=>row.id===id);assert.ok(p);return p;}; +const quiet=(g:Game)=>!g.phaseOpening&&!g.response&&!g.decision&&!g.truthtrance&&!g.pendingTreacheryDiscard; +function inventory(g:Game) { + const ids=[...g.deck,...g.discard,...(g.richeseCache??[]),...(g.richeseRemoved??[]), + ...(g.auction?.cards.slice(g.auction.index+Number(g.currentAuctionSale?.origin==='normal'))??[]), + ...(g.ixAuction?.cards??[]),...g.players.flatMap(row=>row.hand)].map(card=>card.id).sort(); + assert.equal(new Set(ids).size,ids.length);return ids; +} +function take(g:Game,predicate:(card:Game['deck'][number])=>boolean) { + const zones=[g.deck,g.discard,g.richeseCache!,...g.players.map(row=>row.hand)]; + const zone=zones.find(row=>row.some(predicate));assert.ok(zone); + return zone.splice(zone.findIndex(predicate),1)[0]; +} +function passResponse(g:Game) { + for(let n=0;g.response&&n<20;n++) { + const actor=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(actor); + g=act(g,actor.id,{type:'passResponse'}); + } + return g; +} +/** Genuine public Advanced CHOAM-only setup, a real second-turn worm and + * mutual Emperor/Guild alliance. Only unopened Spice order, conserved board + * counters, physical card locations and auction wallets are staged. */ +function fixture(source:'onceAround'|'silent'|'ordinary') { + let g=createGame('ADVSEMUTAAUCTION',newPlayer('e','Emperor','emperor'),true,['choam']); + for(const id of ['g','r','a'] as const) { + const faction={g:'guild',r:'richese',a:'atreides'} as const; + joinGame(g,newPlayer(id,id,faction[id])); + } + for(const p of g.players)g=act(g,p.id,{type:'ready'}); + g=act(g,'e',{type:'start',advancedPreview:true}); + assert.equal(g.semutaAdvancedOrdinaryPreview,true); + g=advanceSemutaNexusTrade(g,s=>s.status==='playing'); + for(const p of g.players){p.reserves+=Object.values(p.forces).reduce((sum,n)=>sum+n,0);p.forces={};} + g=advanceSemutaNexusTrade(g,beforeIxSpiceDraw);orderIxSpiceCards(g,['land','land']); + g=advanceSemutaNexusTrade(g,s=>s.turn===2&&beforeIxSpiceDraw(s));orderIxSpiceCards(g,['worm','land','land']); + g=advanceSemutaNexusTrade(g,s=>!!s.nexus&&!s.spiceWindow&&quiet(s)); + g=act(g,'e',{type:'alliance',target:'g'});g=act(g,'g',{type:'alliance',target:'e'}); + g=advanceSemutaNexusTrade(g,s=>s.phase===2&&quiet(s)); + for(const p of g.players)g.deck.push(...p.hand.splice(0)); + const semuta=take(g,card=>card.id===SEMUTA_DRUG_ID);seat(g,'r').hand.push(semuta); + const karama=take(g,card=>card.effect==='karama');seat(g,'a').hand.push(karama); + seat(g,'g').spice=7;seat(g,'e').spice=8; + const cards=inventory(g); + let card:string; + if(source==='ordinary') { + g=advanceSemutaNexusTrade(g,s=>s.phase===3&&!!s.auction&&!s.richeseAuction&&quiet(s)); + while(g.auction!.active!=='g')g=act(g,g.auction!.active,{type:'passBid'}); + card=g.auction!.cards[g.auction!.index].id; + g=act(g,'e',{type:'pledgeAid',amount:1}); + g=act(g,'g',{type:'bid',amount:3,allyPayment:1}); + for(let n=0;g.auction&&!g.response&&!g.decision&&n<15;n++)g=act(g,g.auction.active,{type:'passBid'}); + } else { + g=advanceSemutaNexusTrade(g,s=>s.decision?.kind==='richeseCache'); + const selected=g.richeseCache![0];assert.ok(selected);card=selected.id; + g=act(g,'r',{type:'decision',event:g.richeseBidding!.event,card,method:source, + ...(source==='onceAround'?{direction:'clockwise' as const}:{})}); + g=act(g,'e',{type:'pledgeAid',amount:1}); + let bid=false; + for(let n=0;!g.pendingEmperorAuctionGift&&n<300;n++) { + const lot=g.richeseAuction; + if(lot&&!lot.outcome&&!g.response&&!g.decision&&lot.method==='onceAround'&&lot.active) { + const buyer=lot.active==='g'&&!bid; + g=act(g,lot.active,{type:'richeseBid',event:lot.event,amount:buyer?3:null,...(buyer?{allyPayment:1}:{})}); + if(buyer)bid=true; + } else if(lot&&!lot.outcome&&!g.response&&!g.decision&&lot.method==='silent') { + const actor=lot.eligible.find(id=>!Object.hasOwn(lot.sealed,id));assert.ok(actor); + const buyer=actor==='g'&&!bid; + g=act(g,actor,{type:'richeseBid',event:lot.event,amount:buyer?3:0,...(buyer?{allyPayment:1}:{})}); + if(buyer)bid=true; + } else {const next=nextSemutaNexusTradeNativeStep(g);g=act(g,next.actor,next.action);} + } + assert.equal(bid,true); + } + assert.ok(g.pendingEmperorAuctionGift,'The allied winner receives the original prepayment opportunity'); + return {g,card,karama:karama.id,semuta:semuta.id,cards}; +} + +for(const source of ['ordinary','onceAround','silent'] as const) for(const claim of [false,true]) void test( + `Advanced ${source} Emperor gift cancellation offers its Karama to Semuta; ${claim?'claim':'pass'} resumes sale`,()=>{ + const f=fixture(source), original=structuredClone(f.g), opportunity=f.g.pendingEmperorAuctionGift!; + let g=act(f.g,'e',{type:'emperorGift',amount:2}); + assert.equal(g.response?.kind,'emperorGift'); + g=act(g,'a',{type:'card',mode:'cancel',card:f.karama}); + assert.equal(g.pendingTreacheryDiscard?.continuation.kind,'karamaEmperorShareDiscard'); + assert.equal(g.pendingTreacheryDiscard?.reaction?.stage,'offer'); + const event=g.pendingTreacheryDiscard!.batch.event; + if(claim)g=act(g,'r',{type:'semutaCommit',event}); + else while(g.pendingTreacheryDiscard?.reaction?.stage==='offer') { + const reaction=g.pendingTreacheryDiscard.reaction; + const actor=g.players.find(row=>!reaction.passed.includes(row.id));assert.ok(actor); + g=act(g,actor.id,{type:'semutaPass',event}); + } + assert.equal(seat(g,'r').hand.some(card=>card.id===f.karama),claim); + assert.equal(g.discard.some(card=>card.id===f.semuta),claim); + assert.equal(seat(g,'e').spice,seat(original,'e').spice); + assert.equal(seat(g,'g').spice,seat(original,'g').spice); + assert.deepEqual(g.auction,original.auction);assert.deepEqual(g.richeseAuction,original.richeseAuction); + assert.deepEqual(g.richeseFunding,original.richeseFunding);assert.deepEqual(g.aid,original.aid); + assert.equal(viewGame(g,'e').emperorAuctionGift?.event,opportunity.event); + g=act(g,'e',{type:'emperorAuctionGiftContinue',event:opportunity.event}); + if(g.decision?.kind==='auctionPayment')g=act(g,'g',{type:'decision',karama:false}); + g=passResponse(g); + assert.ok(seat(g,'g').hand.some(card=>card.id===f.card)); + assert.equal(g.aid.e?.amount??0,0);assert.deepEqual(inventory(g),f.cards); + }); diff --git a/tests/emperor-auction-gift-advanced-waiting-sandtrout.test.ts b/tests/emperor-auction-gift-advanced-waiting-sandtrout.test.ts new file mode 100644 index 00000000..7e405021 --- /dev/null +++ b/tests/emperor-auction-gift-advanced-waiting-sandtrout.test.ts @@ -0,0 +1,101 @@ +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 {territory} from '../game/board'; +import {beforeIxSpiceDraw, orderIxSpiceCards} from './fixture-ix-spice-cards'; +import {nextSemutaNexusTradeNativeStep} from './fixture-semuta-nexus-trade'; + +const act=(g:Game,id:string,action:Action)=>applyAction(g,id,action); +const seat=(g:Game,id:string)=>{const p=g.players.find(row=>row.id===id);assert.ok(p);return p;}; +const quiet=(g:Game)=>!g.response&&!g.decision&&!g.phaseOpening&&!g.truthtrance&&!g.pendingTreacheryDiscard; +function cards(g:Game) { + const ids=[...g.deck,...g.discard,...(g.richeseCache??[]),...(g.richeseRemoved??[]), + ...(g.auction?.cards.slice(g.auction.index+Number(g.currentAuctionSale?.origin==='normal'))??[]), + ...(g.ixAuction?.cards??[]),...g.players.flatMap(p=>p.hand)].map(card=>card.id).sort(); + assert.equal(new Set(ids).size,ids.length);return ids; +} +function advance(g:Game,until:(g:Game)=>boolean) { + for(let n=0;n<2400;n++) { + if(until(g))return g; + assert.notEqual(g.status,'finished'); + if(g.status==='setup'&&g.setupStage==='forces'&&seat(g,'ecaz').reserves===20) + g=act(g,'ecaz',{type:'ecazSetup',placements:{'imperial_basin:9':6}}); + else if(g.decision?.kind==='ecazPlacement'&&!g.response&&!g.phaseOpening) + g=act(g,'ecaz',{type:'decision',decline:true}); + else {const next=nextSemutaNexusTradeNativeStep(g);g=act(g,next.actor,next.action);} + } + throw Error('Advanced native game did not reach the requested auction'); +} +/** Public Advanced setup, genuine Sandtrout, then an actual Ecaz Ambassador + * alliance and the following native auction. Spice prefix, conserved board + * pieces, physical counter custody and wallets are staged. */ +function fixture() { + let g=createGame('ADVANCED-GIFT-SANDTROUT',newPlayer('ecaz','Ecaz','ecaz'),true,['choam','ix','ecaz']); + for(const id of ['emperor','richese','choam','atreides'] as const)joinGame(g,newPlayer(id,id,id)); + for(const p of g.players)g=act(g,p.id,{type:'ready'}); + g=act(g,'ecaz',{type:'start',advancedPreview:true}); + g=advance(g,s=>s.status==='playing');const original=cards(g); + for(const p of g.players){p.reserves+=Object.values(p.forces).reduce((sum,n)=>sum+n,0);p.forces={};} + g=advance(g,beforeIxSpiceDraw);orderIxSpiceCards(g,['sandtrout','land','land']); + g=advance(g,s=>s.phase===4&&!s.response&&!s.phaseOpening&&s.decision?.kind==='ecazPlacement'); + assert.equal(g.sandtrout,true); + const location=['habbanya_ridge_sietch','sietch_tabr','carthag','arrakeen','tueks_sietch'] + .map(id=>({territory:id,sector:territory(id).sectors.find(s=>s!==g.storm)})) + .find((row):row is {territory:string;sector:number}=>row.sector!==undefined);assert.ok(location); + const token=g.ecazAmbassadors!.tokens.find(row=>row.effect==='ecaz');assert.ok(token); + g=act(g,'ecaz',{type:'decision',token:token.id,territory:location.territory}); + g=advance(g,s=>s.phase===5&&quiet(s)&&s.active==='emperor'); + g=act(g,'emperor',{type:'ship',amount:1,...location}); + g=advance(g,s=>!s.response&&s.pendingAmbassador?.stage==='offer'); + const event=g.pendingAmbassador!.event; + g=act(g,'ecaz',{type:'decision',event,trigger:true,beneficiary:'ecaz',choice:'alliance'}); + g=act(g,'emperor',{type:'decision',event,accept:true}); + if(g.pendingAmbassador?.stage==='loan')g=act(g,'ecaz',{type:'decision',event,loan:false}); + assert.equal(seat(g,'ecaz').ally,'emperor');assert.equal(seat(g,'emperor').ally,'ecaz'); + g=advance(g,s=>s.turn===2&&beforeIxSpiceDraw(s));orderIxSpiceCards(g,['land','land']); + g=advance(g,s=>s.phase===3&&s.phaseOpening?.initialize===true); + assert.equal(g.sandtrout,true);assert.equal(seat(g,'ecaz').ally,'emperor'); + for(const p of g.players)g.deck.push(...p.hand.splice(0)); + const index=g.deck.findIndex(card=>card.effect==='karama');assert.ok(index>=0); + const [counter]=g.deck.splice(index,1);seat(g,'atreides').hand.push(counter); + seat(g,'ecaz').spice=7;seat(g,'emperor').spice=8; + g=advance(g,s=>s.phase===3&&!!s.auction&&!s.richeseAuction&&quiet(s)); + while(g.auction!.active!=='ecaz')g=act(g,g.auction!.active,{type:'passBid'}); + const card=g.auction!.cards[g.auction!.index].id; + g=act(g,'emperor',{type:'pledgeAid',amount:1}); + g=act(g,'ecaz',{type:'bid',amount:3,allyPayment:1}); + for(let n=0;g.auction&&!g.response&&!g.decision&&n<20;n++)g=act(g,g.auction.active,{type:'passBid'}); + assert.equal(g.decision?.kind,'auctionPayment');assert.equal(g.sandtrout,true); + const offer=viewGame(g,'emperor').emperorAuctionGift;assert.ok(offer); + assert.deepEqual(cards(g),original);return {g,card,counter:counter.id,original,event:offer.event}; +} +function settle(g:Game) { + for(let n=0;n<60;n++) { + if(g.pendingKull?.stage==='offer') {g=act(g,g.pendingKull.player,{type:'kullDecision',event:g.pendingKull.event,decline:true});continue;} + if(g.pendingTreacheryDiscard?.reaction?.stage==='offer') { + const pending=g.pendingTreacheryDiscard,reaction=pending.reaction; + if(!reaction||reaction.stage!=='offer')throw Error('Discard offer disappeared'); + const player=g.players.find(p=>!reaction.passed.includes(p.id));assert.ok(player); + g=act(g,player.id,{type:'semutaPass',event:pending.batch.event});continue; + } + if(g.response){const p=g.players.find(row=>!g.response!.passed.includes(row.id));assert.ok(p);g=act(g,p.id,{type:'passResponse'});continue;} + return g; + } + throw Error('Gift response did not settle'); +} +for(const cancel of [false,true])void test(`Advanced Emperor auction gift with real waiting Sandtrout ${cancel?'cancels':'allows'} and preserves payment`,()=>{ + const f=fixture(),before=structuredClone(f.g),auction=structuredClone(f.g.auction),aid=structuredClone(f.g.aid); + let g=act(f.g,'emperor',{type:'emperorGift',amount:2});assert.equal(g.response?.kind,'emperorGift'); + if(cancel)g=act(g,'atreides',{type:'card',mode:'cancel',card:f.counter}); + g=settle(g);assert.equal(g.sandtrout,true); + assert.deepEqual(g.auction,auction);assert.deepEqual(g.aid,aid); + assert.equal(g.pendingEmperorAuctionGift?.event,f.event); + assert.equal(seat(g,'ecaz').spice,seat(before,'ecaz').spice+(cancel?0:2)); + assert.equal(seat(g,'emperor').spice,seat(before,'emperor').spice-(cancel?0:2)); + g=act(g,'emperor',{type:'emperorAuctionGiftContinue',event:f.event}); + if(g.decision?.kind==='auctionPayment')g=act(g,'ecaz',{type:'decision',karama:false}); + g=settle(g);assert.ok(seat(g,'ecaz').hand.some(card=>card.id===f.card)); + assert.equal(seat(g,'ecaz').spice,seat(before,'ecaz').spice+(cancel?0:2)-2); + assert.equal(seat(g,'emperor').spice,seat(before,'emperor').spice-(cancel?0:2)+2); + assert.equal(g.aid.emperor?.amount??0,0);assert.equal(g.sandtrout,true);assert.deepEqual(cards(g),f.original); +}); diff --git a/tests/emperor-auction-gift-cache-controls.test.tsx b/tests/emperor-auction-gift-cache-controls.test.tsx index c9eb63a4..118fd9d0 100644 --- a/tests/emperor-auction-gift-cache-controls.test.tsx +++ b/tests/emperor-auction-gift-cache-controls.test.tsx @@ -30,3 +30,12 @@ void test('ordinary auction keeps its original buyer-payment guidance', () => { assert.match(html, /Your ally chooses how to pay after the gift’s Karama response/); assert.doesNotMatch(html, /Continue settles the Richese sale/); }); + +void test('a live ally-funding guide remains actionable before the sale continues', () => { + const game = view('richese'); + game.pledgePromiseGuide = {action:{type:'pledgeAid',amount:4}}; + const html = render(game); + assert.match(html, /Set your promised ally funding before this purchase can close Bidding/); + assert.match(html, /]*disabled)[^>]*>Set required ally funding<\/button>/); + assert.match(html, /]*disabled=""[^>]*>Continue to payment<\/button>/); +}); diff --git a/tests/emperor-richese-cache-gift-advanced-public.test.ts b/tests/emperor-richese-cache-gift-advanced-public.test.ts new file mode 100644 index 00000000..567512fc --- /dev/null +++ b/tests/emperor-richese-cache-gift-advanced-public.test.ts @@ -0,0 +1,151 @@ +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 {botActions} from '../game/bots'; +import {DIFFICULTIES} from '../game/bot-profiles'; +import {takeKullCard} from './fixture-choam-kull'; +import {advanceSemutaNexusTrade, nextSemutaNexusTradeNativeStep} from './fixture-semuta-nexus-trade'; +import {beforeIxSpiceDraw, orderIxSpiceCards} from './fixture-ix-spice-cards'; + +const act=(game:Game,id:string,action:Action)=>applyAction(game,id,action); +const seat=(game:Game,id:string)=>{const player=game.players.find(row=>row.id===id);assert.ok(player);return player;}; +const quiet=(game:Game)=>!game.phaseOpening&&!game.response&&!game.decision&&!game.truthtrance&&!game.pendingTreacheryDiscard; +function inventory(game:Game) { + const cards=[...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(); + assert.equal(new Set(cards).size,cards.length);return cards; +} +function finishResponses(game:Game):Game { + for(let n=0;game.response&&n<20;n++) { + const actor=game.players.find(player=>!game.response!.passed.includes(player.id));assert.ok(actor); + game=act(game,actor.id,{type:'passResponse'}); + } + return game; +} +function finishDiscardOffers(game:Game):Game { + for(let n=0;game.pendingTreacheryDiscard?.reaction?.stage==='offer'&&n<20;n++) { + 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}); + } + return game; +} + +/** Genuine public Advanced setup, real second-turn worm, Emperor/Guild + * alliance and original paid cache sale. Staged unopened Spice order, + * conserved starting board positions, purses and physical hand/deck custody. */ +function fixture(method:'onceAround'|'silent', withPromise=false) { + let game=createGame('ADVRICHGIFT',newPlayer('e','Emperor','emperor'),true,['choam','ix']); + for(const [id,faction] of [['g','guild'],['c','choam'],['r','richese'],['a','atreides']] as const) + joinGame(game,newPlayer(id,faction,faction)); + for(const player of game.players)game=act(game,player.id,{type:'ready'}); + game=act(game,'e',{type:'start',advancedPreview:true}); + game=advanceSemutaNexusTrade(game,state=>state.status==='playing'); + for(const player of game.players){player.reserves+=Object.values(player.forces).reduce((sum,n)=>sum+n,0);player.forces={};} + game=advanceSemutaNexusTrade(game,beforeIxSpiceDraw);orderIxSpiceCards(game,['land','land']); + game=advanceSemutaNexusTrade(game,state=>state.turn===2&&beforeIxSpiceDraw(state)); + orderIxSpiceCards(game,['worm','land','land']); + game=advanceSemutaNexusTrade(game,state=>!!state.nexus&&!state.spiceWindow&&quiet(state)); + game=act(game,'e',{type:'alliance',target:'g'});game=act(game,'g',{type:'alliance',target:'e'}); + game=advanceSemutaNexusTrade(game,state=>state.phase===3&&state.phaseOpening?.initialize===true); + for(const player of game.players)game.deck.push(...player.hand.splice(0)); + const karama=takeKullCard(game,'karama');seat(game,'a').hand.push(karama); + const truth=withPromise ? takeKullCard(game,'truthtrance') : null; + if(truth)seat(game,'a').hand.push(truth); + seat(game,'g').spice=7;seat(game,'e').spice=8; + game=advanceSemutaNexusTrade(game,state=>state.decision?.kind==='richeseCache'); + const selected=game.richeseCache?.[0];assert.ok(selected); + const physical=inventory(game),card=selected.id; + game=act(game,'r',{type:'decision',event:game.richeseBidding!.event,card,method, + ...(method==='onceAround'?{direction:'clockwise'}:{})}); + game=act(game,'e',{type:'pledgeAid',amount:1}); + if(truth) { + game=act(game,'a',{type:'card',card:truth.id}); + for(let n=0;game.truthtrance?.stage==='priority'&&n<20;n++) { + const actor=game.players.find(player=>!game.truthtrance!.passed.includes(player.id));assert.ok(actor); + game=act(game,actor.id,{type:'truthPass'}); + } + assert.equal(game.truthtrance?.stage,'ask'); + game=act(game,'a',{type:'truthAsk',question:{kind:'pledgeAid',target:'e', + turn:game.turn,phase:3,ally:'g',minimum:4}}); + assert.ok(viewGame(game,'e').truthPledgeAnswers?.includes('yes')); + game=act(game,'e',{type:'truthAnswer',answer:'yes'}); + } + let bid=false; + for(let n=0;!game.pendingEmperorAuctionGift&&n<300;n++) { + const lot=game.richeseAuction; + if(lot&&!lot.outcome&&!game.response&&!game.decision&&lot.method==='onceAround'&&lot.active) { + const buyer=lot.active==='g'&&!bid; + game=act(game,lot.active,{type:'richeseBid',event:lot.event,amount:buyer?3:null,...(buyer?{allyPayment:1}:{})}); + if(buyer)bid=true; + } else if(lot&&!lot.outcome&&!game.response&&!game.decision&&lot.method==='silent') { + const actor=lot.eligible.find(id=>!Object.hasOwn(lot.sealed,id));assert.ok(actor); + const buyer=actor==='g'&&!bid; + game=act(game,actor,{type:'richeseBid',event:lot.event,amount:buyer?3:0,...(buyer?{allyPayment:1}:{})}); + if(buyer)bid=true; + } else { + const next=nextSemutaNexusTradeNativeStep(game);game=act(game,next.actor,next.action); + } + } + assert.equal(bid,true);assert.ok(game.pendingEmperorAuctionGift,'Emperor receives the original cache purchase opportunity'); + assert.equal(game.richeseAuction?.outcome?.kind,'sold');assert.equal(game.currentAuctionSale??null,null); + assert.equal(viewGame(game,'e').emperorAuctionGift?.recipient,'g'); + return {game,card,karama:karama.id,physical}; +} + +for(const method of ['onceAround','silent'] as const) for(const mode of ['continue','allow','cancel'] as const) void test( + `Advanced ${method} cache purchase retains funding and bank routing after Emperor ${mode}`,()=>{ + const f=fixture(method),before=structuredClone(f.game),lot=structuredClone(f.game.richeseAuction); + const funding=structuredClone(f.game.richeseFunding),aid=structuredClone(f.game.aid); + const offer=viewGame(f.game,'e').emperorAuctionGift;assert.ok(offer); + for(const difficulty of DIFFICULTIES) { + const view=viewGame(f.game,'e');view.players.find(player=>player.id==='e')!.bot=difficulty; + const action=botActions(view).find(row=>row.type==='emperorAuctionGiftContinue');assert.ok(action,difficulty); + assert.doesNotThrow(()=>act(f.game,'e',action),difficulty); + } + let game=f.game; + if(mode!=='continue') { + game=act(game,'e',{type:'emperorGift',amount:2});assert.equal(game.response?.kind,'emperorGift'); + if(mode==='cancel')game=finishDiscardOffers(act(game,'a',{type:'card',mode:'cancel',card:f.karama})); + else game=finishResponses(game); + } + assert.deepEqual(game.richeseAuction,lot);assert.deepEqual(game.richeseFunding,funding);assert.deepEqual(game.aid,aid); + assert.equal(game.pendingEmperorAuctionGift?.event,offer.event); + assert.equal(seat(game,'e').spice,seat(before,'e').spice-(mode==='allow'?2:0)); + assert.equal(seat(game,'g').spice,seat(before,'g').spice+(mode==='allow'?2:0)); + game=act(game,'e',{type:'emperorAuctionGiftContinue',event:offer.event}); + game=finishResponses(game); + assert.ok(seat(game,'g').hand.some(row=>row.id===f.card)); + assert.equal(seat(game,'g').spice,seat(before,'g').spice+(mode==='allow'?2:0)-2); + assert.equal(seat(game,'e').spice,seat(before,'e').spice-(mode==='allow'?2:0)); + assert.equal(game.aid.e?.amount??0,0); + assert.equal(seat(game,'r').spice,seat(before,'r').spice+2,'Emperor-funded one goes to the bank, buyer-funded two to Richese'); + assert.deepEqual(inventory(game),f.physical); + }); + +void test('Advanced cache gift allows a live pledge Yes without changing the original winning split',()=>{ + const f=fixture('onceAround',true),before=structuredClone(f.game); + const lot=structuredClone(f.game.richeseAuction),funding=structuredClone(f.game.richeseFunding); + const offer=viewGame(f.game,'e').emperorAuctionGift;assert.ok(offer); + assert.equal(f.game.aid.e?.amount,1); + assert.equal(f.game.pendingEmperorAuctionGift?.quote?.allyPayment,1); + assert.ok(f.game.pledgePromises?.at(-1)?.answer); + const guide=viewGame(f.game,'e').pledgePromiseGuide;assert.ok(guide); + assert.deepEqual(guide.action,{type:'pledgeAid',amount:4,emperorAuctionGiftEvent:offer.event}); + let game=act(f.game,'e',guide.action); + assert.equal(game.pledgePromises?.at(-1)?.fulfilled,true); + assert.equal(game.aid.e?.amount,4); + assert.deepEqual(game.richeseAuction,lot);assert.deepEqual(game.richeseFunding,funding); + assert.equal(game.pendingEmperorAuctionGift?.quote?.allyPayment,1); + game=act(game,'e',{type:'emperorAuctionGiftContinue',event:offer.event}); + game=finishResponses(game); + assert.ok(seat(game,'g').hand.some(row=>row.id===f.card)); + assert.equal(seat(game,'g').spice,seat(before,'g').spice-2); + assert.equal(seat(game,'r').spice,seat(before,'r').spice+2); + assert.equal(game.aid.e?.amount,3,'Only the one-spice winning contribution is spent'); + assert.equal(seat(game,'e').spice,seat(before,'e').spice-3); + assert.equal(game.pledgePromises?.at(-1)?.fulfilled,true); + assert.deepEqual(inventory(game),f.physical); +});