From ecd892b368635eb6599eae1f1ea459f0da68a021 Mon Sep 17 00:00:00 2001 From: Quintine <15965533+Quintine@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:53:01 +1100 Subject: [PATCH] Allow Richese special purchase during CHOAM market --- docs/CURRENT_STATUS.md | 8 + docs/RICHESE_ACQUISITION_RULES.md | 19 +++ game/engine.ts | 41 +++++- game/reference.ts | 1 + .../richese-special-market-controls.test.tsx | 125 ++++++++++++++++ tests/richese-special-market-runtime.test.ts | 137 ++++++++++++++++++ tests/richese-special-market-semuta.test.ts | 133 +++++++++++++++++ 7 files changed, 461 insertions(+), 3 deletions(-) create mode 100644 tests/richese-special-market-controls.test.tsx create mode 100644 tests/richese-special-market-runtime.test.ts create mode 100644 tests/richese-special-market-semuta.test.ts diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index 75a0acba..6e4e163d 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -17,6 +17,14 @@ open mode gates. ## Current checkpoint and work +**Richese special purchase during the CHOAM market — 16 November. Prototyped / +Partial.** A clean market or allied trade decision resumes after the Advanced +purchase and any Emperor income response. Cards already selected for the +trade remain reserved, including a Semuta cost; the Semuta response can claim +or pass the original discard. Twenty-one related offline files pass 147 cases; +types, lint and the production build pass. Other timing, combinations and deployed acceptance remain +open. [Scope](RICHESE_ACQUISITION_RULES.md#choam-market-and-trade--16-november-2026). + **Advanced Emperor gifts during Ix phase openings — 16 November. Prototyped / Partial.** The existing clean-opening gift now also works in supported Advanced games, retaining original passes, native cancellation and the human Emperor's diff --git a/docs/RICHESE_ACQUISITION_RULES.md b/docs/RICHESE_ACQUISITION_RULES.md index 4c82e491..e193a0b6 100644 --- a/docs/RICHESE_ACQUISITION_RULES.md +++ b/docs/RICHESE_ACQUISITION_RULES.md @@ -13,6 +13,25 @@ Targeted searches found discussion titles concerning full hands and alliance can ## 1. Advanced special Karama purchase +### CHOAM market and trade — 16 November 2026 + +**Prototyped / Partial.** The user-authorized revised Advanced rulebook physical +p. 20 lists Richese's special purchase at any time. It can now interrupt a +clean CHOAM market decision, allied trade reply or trade confirmation. The +market and the exact original decision survive the purchase, including the +separate Emperor-income response; an absent Emperor still sends the price to +the bank. A card already selected for the original trade cannot be spent as +the activation Karama or as a Semuta cost. The existing Semuta response may +claim or pass the physical discarded Karama before the purchase continues. + +The online ordering is a provisional application of the printed timing; it is +not a publisher ruling about nested priority. Completed-sale responses and +other parent windows retain their existing boundaries. [Runtime cases](../tests/richese-special-market-runtime.test.ts), +[Semuta and reserved-card cases](../tests/richese-special-market-semuta.test.ts) +and [controls](../tests/richese-special-market-controls.test.tsx) exercise the +native decisions with genuine setup and explicitly staged, conserved cards and +alliances. Complete rules and deployed acceptance remain open. + ### Ix phase-opening purchase — 16 November 2026 **Prototyped / Partial.** The user-authorized revised rulebook physical p. 20 diff --git a/game/engine.ts b/game/engine.ts index d9022f88..4ccef5dc 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -7731,6 +7731,7 @@ function specialKaramaDiscardSignature(g: Game, c: SpecialKaramaDiscardContinuat rides: g.wormRides, nexus: g.nexusCards, emperorPurchases: g.nexusEmperorPurchaseHistory, auction: g.auction, sale: g.currentAuctionSale, + ...(g.choamMarket ? {market: g.choamMarket} : {}), richeseAuction: g.richeseAuction, richeseBidding: g.richeseBidding, cache: g.richeseCache?.map(card => card.id), deck: g.deck.map(card => card.id), revivalPrevention: g.revivalPrevention, @@ -10446,7 +10447,9 @@ function semutaOfferSupported( (richeseGiftDiscard || !g.pendingRicheseGift) && (richeseGiftDiscard || (continuation.kind === 'karamaIncomeDiscard' && continuation.use.response.kind === 'richesePurchaseIncome') || !g.pendingRichesePurchaseIncome) && - (richeseGiftDiscard || saleCostDiscard || marketGholaDiscard || marketGholaIncomeDiscard || (continuation.kind === 'choamSaleDiscard' + (richeseGiftDiscard || saleCostDiscard || marketGholaDiscard || marketGholaIncomeDiscard || + continuation.kind === 'specialKaramaDiscard' && continuation.intent.kind === 'richese' && + richeseSpecialMarketParent(g, continuation.resume.decision) || (continuation.kind === 'choamSaleDiscard' ? !!g.choamMarket && !g.choamMarket.sale && !g.choamMarket.trade && !g.biddingEnd && !g.currentAuctionSale : continuation.kind === 'kaitainDiscard' @@ -10480,6 +10483,8 @@ function semutaCandidates(g: Game, owner: Player) { /** A committed prevention releases only its selected Technology/gift * reservation for Semuta's cost response. Other commitments remain live. */ function semutaSpendingBlock(g: Game, owner: Player, card: Card): string | null { + if (choamTradeCardReserved(g, owner, card)) + return 'This card is reserved for the current CHOAM trade.'; const c=g.pendingTreacheryDiscard?.continuation; const gift=g.pendingRicheseGift; const preventedTechnology=c?.kind==='karamaAuctionAdvantageDiscard' && @@ -15724,6 +15729,7 @@ function richeseBetrayalSourceSignature(g: Game, frame: NonNullable player.id === market.owner && player.faction === 'choam'); + if (!owner) return false; + if (decision.kind === 'choamMarket') return decision.player === owner.id && !market.trade; + const trade = market.trade, ally = g.players.find(player => player.id === trade?.ally); + if (!trade || !ally || owner.ally !== ally.id || ally.ally !== owner.id || + !owner.hand.some(card => card.id === trade.offered)) return false; + if (decision.kind === 'choamTradeReply') return decision.player === ally.id && !trade.returned; + return decision.kind === 'choamTradeConfirm' && decision.player === owner.id && + !!trade.returned && ally.hand.some(card => card.id === trade.returned); +} + /** Validates and copies a selection without spending resources, continuing play, or drawing RNG. */ export function prepareSpecialKaramaIntent( g: Game, @@ -42947,7 +42977,8 @@ export function prepareSpecialKaramaIntent( 'Play Amal or pass the phase opening before taking other actions.', ); requireRule( - !g.choamMarket, + !g.choamMarket || p.faction === 'richese' && !g.response && !g.phaseOpening && + !g.pendingKarama && !g.pendingKull && !g.pendingTreacheryDiscard && richeseSpecialMarketParent(g, g.decision), 'Finish the end-of-phase exchange before another special power.', ); requireRule( @@ -42970,6 +43001,8 @@ export function prepareSpecialKaramaIntent( requireRule(card, 'Choose a Karama card in your hand.'); const activationBlock = karamaSpendingBlock(g, p, card, kullSpecialPurpose(p.faction)); requireRule(!activationBlock, activationBlock ?? 'This Karama is committed elsewhere.'); + requireRule(p.faction !== 'richese' || !choamTradeCardReserved(g, p, card), + 'This Karama is reserved for the current CHOAM trade.'); const base = { owner: p.id, card: card.id, turn: g.turn, phase: g.phase }; if (p.faction === 'ecaz') { requireRule(!g.response && !g.decision && !g.battle?.preparation && @@ -43643,6 +43676,7 @@ function richeseSpecialKaramaView(g: Game, p: Player) { (c) => canUseAsKaramaRole(g, p, c) && !karamaSpendingBlock(g, p, c, kullSpecialPurpose(p.faction)) && + !choamTradeCardReserved(g, p, c) && !( g.richeseAuction?.source === 'blackMarket' && !g.currentAuctionSale && @@ -45524,7 +45558,8 @@ function applyActionInner( } if (t === 'card' && action.mode === 'special') { requireRule( - !g.choamMarket, + !g.choamMarket || p.faction === 'richese' && !g.response && !g.phaseOpening && + !g.pendingKarama && !g.pendingKull && !g.pendingTreacheryDiscard && richeseSpecialMarketParent(g, g.decision), 'Finish the end-of-phase exchange before another special power.', ); requireRule( diff --git a/game/reference.ts b/game/reference.ts index b4e3d577..7faffdf6 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -623,6 +623,7 @@ export const RULE_TOPICS: RuleTopic[] = [ steps: [ 'In advanced development tables, Richese can use its special Karama once per game. Select an available Karama in your hand and one eligible card from your own cache. The activating Karama is discarded; the chosen card enters your hand secretly.', 'In a supported clean Ix phase opening, this purchase can occur without abandoning earlier passes. If the Emperor is present, the opening waits while the separate income response is resolved; its existing passes then resume. Some optional-module combinations remain guarded.', + 'During a supported CHOAM market or allied trade decision, your purchase can interrupt and then resume that same decision. A Karama or Semuta already selected for the pending trade stays reserved for the exchange.', 'This is a purchase for Richese itself. Pay three of your available spice to Emperor when present, otherwise the bank. The general Emperor purchase-income rule supplies this payment destination. An ally receives no Harkonnen bonus or Ixian replacement from this direct cache acquisition.', 'With Emperor absent, an actual unallied Emperor Nexus holder may use the private joint option after proving three own uncommitted spice. Original Karama and Nexus both spend at purchase commit, one exact cache card enters your hand and native once-use/capacity/reservations remain. No bank money, reimbursement, ally bonus or fake auction is created. The separate Betrayal preview may pause before those costs. This purchase composition is visibly provisional; ordinary paid use remains available.', 'A Karama cannot cancel the special purchase itself. Emperor income has a separate response: canceling that income does not undo the purchase or restore the spent special power.', diff --git a/tests/richese-special-market-controls.test.tsx b/tests/richese-special-market-controls.test.tsx new file mode 100644 index 00000000..8016a12c --- /dev/null +++ b/tests/richese-special-market-controls.test.tsx @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { isValidElement, type ReactElement, type ReactNode } from 'react'; +import * as jsxRuntime from 'react/jsx-runtime'; +import ts from 'typescript'; +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 { nextStrongholdFactionsNativeStep } from './fixture-stronghold-factions'; +import type { RicheseSpecialKarama } from '../components/richese-special-karama'; + +type Element = ReactElement<{children?:ReactNode; [key:string]:unknown}>; +function elements(node:ReactNode): Element[] { + if (Array.isArray(node)) return node.flatMap(elements); + if (!isValidElement<{children?:ReactNode; [key:string]:unknown}>(node)) return []; + return [node, ...elements(node.props.children)]; +} +const seat = (game:Game,id:string) => { const p=game.players.find(player => player.id === id); assert.ok(p); return p; }; + +/** Genuine Advanced Richese/CHOAM/Emperor setup and native market. For the + * control scenario only, an actual Karama is exchanged into Richese's hand; + * the mutual alliance and one extra physical return card are explicitly staged. */ +function market():Game { + let game = createGame('RICHMARKETCONTROL',newPlayer('r','Richese','richese'),true,['choam']); + joinGame(game,newPlayer('c','CHOAM','choam')); + joinGame(game,newPlayer('e','Emperor','emperor')); + for (const player of game.players) game = applyAction(game,player.id,{type:'ready'}); + game = applyAction(game,'r',{type:'start',advancedPreview:true}); + for (let count=0; count<600 && !(game.status === 'playing' && game.decision?.kind === 'choamMarket'); count++) { + const step=nextStrongholdFactionsNativeStep(game); assert.ok(step,`Missing native step at ${game.status}/${game.phase}`); + game=applyAction(game,step.actor,step.action); + } + assert.equal(game.decision?.kind,'choamMarket'); assert.ok(game.choamMarket); + const richese=seat(game,'r'), choam=seat(game,'c'); + richese.ally='c'; choam.ally='r'; + if (!richese.hand.some(card => card.effect === 'karama')) { + const source=[game.deck,...game.players.filter(player => player.id !== 'r').map(player => player.hand)] + .find(cards => cards.some(card => card.effect === 'karama')); + assert.ok(source && richese.hand.length); const index=source.findIndex(card => card.effect === 'karama'); + [richese.hand[0],source[index]]=[source[index],richese.hand[0]]; + } + if (!richese.hand.some(card => card.effect !== 'karama')) { + const index=game.deck.findIndex(card => card.effect !== 'karama'); assert.ok(index>=0); + richese.hand.push(...game.deck.splice(index,1)); + } + assert.ok(choam.hand.length); assert.ok(richese.spice>=3); + return game; +} + +function control(game:ReturnType,busy=false) { + const states:unknown[] = [], sent:Action[] = []; let cursor=0; + const exported:{RicheseSpecialKarama?:typeof RicheseSpecialKarama}={}; + runInNewContext(ts.transpileModule(readFileSync(new URL('../components/richese-special-karama.tsx',import.meta.url),'utf8'),{ + compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}, + }).outputText,{exports:exported,require(name:string) { + if (name==='react/jsx-runtime') return jsxRuntime; + if (name==='react') return {useId:()=> 'test',useState(initial:unknown) { + const index=cursor++; if (!(index in states)) states[index]=initial; + return [states[index],(next:unknown)=>{states[index]=next;}]; + }}; + if (name==='./ui/button') return {Button:'button'}; + if (name==='./card-inspector') return {CardInspector:'span',CardRules:'span'}; + throw Error(`Unexpected import ${name}`); + }}); + assert.ok(exported.RicheseSpecialKarama); + const render=()=>{cursor=0; return elements(exported.RicheseSpecialKarama!({game,busy,act(action){sent.push(action);}}));}; + return {render,sent}; +} + +function stage(kind:'market'|'reply'|'confirm'):Game { + let game=market(); + if (kind !== 'market') { + const offered=seat(game,'c').hand[0]; assert.ok(offered); + game=applyAction(game,'c',{type:'decision',mode:'trade',card:offered.id}); + assert.equal(game.decision?.kind,'choamTradeReply'); + if (kind === 'confirm') { + const returned=seat(game,'r').hand.find(card => card.effect !== 'karama'); assert.ok(returned); + game=applyAction(game,'r',{type:'decision',card:returned.id}); + assert.equal(game.decision?.kind,'choamTradeConfirm'); + } + } + return game; +} + +for (const kind of ['market','reply','confirm'] as const) void test(`Richese special purchase control retains the ${kind} market parent`,()=>{ + const game=stage(kind), parent=structuredClone(game.decision), marketParent=structuredClone(game.choamMarket); + const view=viewGame(game,'r'), quote=view.richeseSpecialKarama; assert.ok(quote && !quote.blocked); + assert.ok(quote.karamas.length && quote.cards.length); + const ui=control(view), button=ui.render().find(row=>row.type==='button'); assert.ok(button); + assert.equal(button.props.disabled,false); (button.props.onClick as ()=>void)(); + assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'card',mode:'special', + card:quote.karamas[0].id,acquire:quote.cards[0].id}]); + const after=applyAction(game,'r',ui.sent[0]); + assert.equal(seat(after,'r').specialKaramaUsed,true); + assert.deepEqual(after.choamMarket,marketParent); + assert.deepEqual(after.response ? after.pendingRichesePurchaseIncome?.resume.decision : after.decision,parent); + assert.equal(viewGame(game,'e').richeseSpecialKarama,null); + const locked=control(view,true).render().find(row=>row.type==='button'); assert.ok(locked); + assert.equal(locked.props.disabled,true); +}); + +void test('a Karama committed as the return card cannot be spent by the purchase control',()=>{ + let game=stage('reply'); + const reserved=seat(game,'r').hand.find(card=>card.effect==='karama'); assert.ok(reserved); + game=applyAction(game,'r',{type:'decision',card:reserved.id}); + assert.equal(game.decision?.kind,'choamTradeConfirm'); + const view=viewGame(game,'r'), quote=view.richeseSpecialKarama; assert.ok(quote); + assert.ok(!quote.karamas.some(card=>card.id===reserved.id)); + const button=control(view).render().find(row=>row.type==='button'); assert.ok(button); + assert.equal(button.props.disabled,true); + const before=structuredClone(game), acquire=game.richeseCache?.[0]; assert.ok(acquire); + assert.throws(()=>applyAction(game,'r',{type:'card',mode:'special',card:reserved.id,acquire:acquire.id})); + assert.deepEqual(game,before); +}); + +void test('all bot profiles can continue the actual CHOAM market decision',()=>{ + const game=stage('market'); + for (const difficulty of DIFFICULTIES) { + const view=viewGame(game,'c'); view.players.find(player=>player.id==='c')!.bot=difficulty; + const action=botActions(view)[0]; assert.ok(action,`${difficulty} needs a legal market action`); + assert.doesNotThrow(()=>applyAction(game,'c',action),difficulty); + } +}); diff --git a/tests/richese-special-market-runtime.test.ts b/tests/richese-special-market-runtime.test.ts new file mode 100644 index 00000000..547cf4b0 --- /dev/null +++ b/tests/richese-special-market-runtime.test.ts @@ -0,0 +1,137 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createGame, joinGame, newPlayer, viewGame, type Action, type Game } from '../game/engine'; +import { actTruthMovementNativeEarly as act, nextTruthMovementNativeEarlyStep } from './fixture-truth-movement-native-early'; +import { truthMovementInventory } from './fixture-truth-movement'; + +const player = (game:Game,id:string) => { + const seat = game.players.find(row => row.id === id); assert.ok(seat); return seat; +}; +function advance(game:Game, until:(game:Game)=>boolean):Game { + for (let count = 0; count < 600; count++) { + if (until(game)) return game; + const step = nextTruthMovementNativeEarlyStep(game); + assert.ok(step, `The native source needs a continuation at ${game.turn}/${game.phase}/${game.decision?.kind}`); + game = act(game,step.actor,step.action); + } + throw Error('The native source did not reach the requested market boundary.'); +} + +/** Genuine Advanced CHOAM/Richese setup and native phase progression. After + * the real starting deal, explicitly move physical cards from the real deck + * to supplement Richese's hand and stage the reciprocal CHOAM alliance; no + * market, decision, spice or cache state is installed. */ +function source(emperor:boolean) { + let game = createGame('RICHMARKET',newPlayer('r','Richese','richese'),true,['choam']); + joinGame(game,newPlayer('c','CHOAM','choam')); + joinGame(game,newPlayer('a','Atreides','atreides')); + if (emperor) joinGame(game,newPlayer('e','Emperor','emperor')); + for (const seat of game.players) game = act(game,seat.id,{type:'ready'}); + game = act(game,'r',{type:'start',advancedPreview:true}); + assert.equal(game.status,'setup'); + const shield = game.deck.find(card => card.kind === 'shield'); assert.ok(shield); + const ordinary = game.deck.filter(card => ['projectile','poison','snooper'].includes(card.kind)).slice(0,game.players.length - 1); + assert.equal(ordinary.length,game.players.length - 1); + for (const [position,card] of [shield,...ordinary].entries()) { + const from = game.deck.findIndex(candidate => candidate.id === card.id); assert.ok(from >= position); + [game.deck[position],game.deck[from]] = [game.deck[from],game.deck[position]]; + } + game = advance(game,state => state.status === 'playing'); + const original = truthMovementInventory(game); + const hold = (id:string, predicate:(card:Game['deck'][number])=>boolean) => { + const index = game.deck.findIndex(predicate); assert.ok(index >= 0); + const [card] = game.deck.splice(index,1); player(game,id).hand.push(card); return card.id; + }; + const karama = hold('r',card => card.effect === 'karama'); + const spare = hold('a',card => card.effect === 'karama'); + const cancel = emperor ? spare : undefined; + player(game,'r').ally = 'c'; player(game,'c').ally = 'r'; + assert.deepEqual(truthMovementInventory(game),original); + game = advance(game,state => state.decision?.kind === 'choamMarket' && !state.response && !state.phaseOpening); + assert.equal(game.choamMarket?.owner,'c'); + const acquire = game.richeseCache?.[0]; assert.ok(acquire); + return {game,karama,spare,cancel,acquire:acquire.id,inventory:truthMovementInventory(game)}; +} +const cache = new Map>(); +function fixture(emperor:boolean) { + let f = cache.get(emperor); if (!f) { f = source(emperor); cache.set(emperor,f); } + return {...f,game:structuredClone(f.game)}; +} +const purchase = (card:string,acquire:string):Action => ({type:'card',mode:'special',card,acquire}); +function trade(game:Game, returned?:string) { + const offered = player(game,'c').hand[0]; assert.ok(offered); + game = act(game,'c',{type:'decision',mode:'trade',card:offered.id}); + assert.equal(game.decision?.kind,'choamTradeReply'); + if (returned !== undefined) { + game = act(game,'r',{type:'decision',card:returned}); + assert.equal(game.decision?.kind,'choamTradeConfirm'); + } + return {game,offered:offered.id}; +} + +for (const emperor of [false,true]) for (const phase of ['market','reply','confirm'] as const) + void test(`Advanced Richese purchase preserves ${phase} with Emperor ${emperor ? 'present' : 'absent'}`, () => { + const f = fixture(emperor); + let game = f.game; + const returned = player(game,'r').hand.find(card => card.id !== f.karama && card.id !== f.spare); assert.ok(returned); + const offered = phase === 'market' ? undefined : trade(game,phase === 'confirm' ? returned.id : undefined); + if (offered) game = offered.game; + const parent = structuredClone(game.decision), market = structuredClone(game.choamMarket); + const beforeSpice = player(game,'r').spice, income = emperor ? player(game,'e').spice : 0; + assert.ok(viewGame(game,'r').richeseSpecialKarama?.cards.some(card => card.id === f.acquire)); + game = act(game,'r',purchase(f.karama,f.acquire)); + assert.equal(player(game,'r').spice,beforeSpice - 3); + assert.equal(player(game,'r').specialKaramaUsed,true); + assert.ok(player(game,'r').hand.some(card => card.id === f.acquire)); + assert.equal(game.discard.filter(card => card.id === f.karama).length,1); + if (emperor) { + assert.equal(game.response?.kind,'richesePurchaseIncome'); + game = advance(game,state => !state.response && !!state.decision); + assert.equal(player(game,'e').spice,income + 3); + } + assert.deepEqual(game.decision,parent); + assert.deepEqual(game.choamMarket,market); + assert.deepEqual(truthMovementInventory(game),f.inventory); + if (phase === 'reply') game = act(game,'r',{type:'decision',card:returned.id}); + if (phase !== 'market') { + game = act(game,'c',{type:'decision',accept:true}); + assert.ok(player(game,'r').hand.some(card => card.id === offered!.offered)); + assert.ok(player(game,'c').hand.some(card => card.id === returned.id)); + } + assert.equal(game.decision?.kind,'choamMarket'); + game = act(game,'c',{type:'decision',done:true}); + assert.equal(game.choamMarket,null); + assert.equal(game.discard.filter(card => card.id === f.karama).length,1); + assert.deepEqual(truthMovementInventory(game),f.inventory); + }); + +void test('an agreed return Karama remains reserved while another Karama can fund the purchase', () => { + const f = fixture(true); + const extra = player(f.game,'a').hand.findIndex(card => card.id === f.spare); assert.ok(extra >= 0); + player(f.game,'r').hand.push(...player(f.game,'a').hand.splice(extra,1)); + const result = trade(f.game,f.karama); + const game = result.game, before = structuredClone(game); + assert.throws(() => act(game,'r',purchase(f.karama,f.acquire))); + assert.deepEqual(game,before); + let next = act(game,'r',purchase(f.spare,f.acquire)); + next = advance(next,state => !state.response && state.decision?.kind === 'choamTradeConfirm'); + next = act(next,'c',{type:'decision',accept:true}); + assert.ok(player(next,'c').hand.some(card => card.id === f.karama)); + assert.equal(next.discard.filter(card => card.id === f.spare).length,1); + assert.deepEqual(truthMovementInventory(next),f.inventory); +}); + +void test('preventing Emperor income keeps the completed purchase and original market decision', () => { + const f = fixture(true); assert.ok(f.cancel); + const parent = structuredClone(f.game.decision), market = structuredClone(f.game.choamMarket); + const income = player(f.game,'e').spice; + let game = act(f.game,'r',purchase(f.karama,f.acquire)); + assert.equal(game.response?.kind,'richesePurchaseIncome'); + game = act(game,'a',{type:'card',mode:'cancel',card:f.cancel}); + game = advance(game,state => !state.response && !!state.decision); + assert.equal(player(game,'e').spice,income); + assert.equal(player(game,'r').specialKaramaUsed,true); + assert.ok(player(game,'r').hand.some(card => card.id === f.acquire)); + assert.deepEqual(game.decision,parent); assert.deepEqual(game.choamMarket,market); + assert.deepEqual(truthMovementInventory(game),f.inventory); +}); diff --git a/tests/richese-special-market-semuta.test.ts b/tests/richese-special-market-semuta.test.ts new file mode 100644 index 00000000..52363407 --- /dev/null +++ b/tests/richese-special-market-semuta.test.ts @@ -0,0 +1,133 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createGame, initializeSemutaGameForAudit, joinGame, newPlayer, viewGame, type Game } from '../game/engine'; +import { SEMUTA_DRUG_ID } from '../game/semuta-drug'; +import { nextStrongholdFactionsNativeStep } from './fixture-stronghold-factions'; +import { actTruthMovementNativeEarly as act, nextTruthMovementNativeEarlyStep } from './fixture-truth-movement-native-early'; +import { truthMovementInventory as inventory } from './fixture-truth-movement'; +import { moveSemutaEmperorCard, semutaEmperorCardId } from './fixture-semuta-emperor-share'; +import { reactSemutaSpecial } from './fixture-semuta-special-karama'; + +const player = (game:Game,id:string) => { + const seat = game.players.find(row => row.id === id); assert.ok(seat); return seat; +}; +function advance(game:Game, until:(state:Game) => boolean):Game { + for (let count = 0; count < 1000; count++) { + if (until(game)) return game; + const step = nextTruthMovementNativeEarlyStep(game); assert.ok(step, 'The native game needs its next action'); + game = act(game,step.actor,step.action); + } + throw Error('The original native market did not resume.'); +} +/** Real Advanced Richese/CHOAM/Atreides/Emperor Semuta setup reaches its + * original market. Original hands are moved back into the deck, and existing + * printed cards are redistributed without duplication to isolate a private + * activation and its optional Semuta response. For trade cases, a reciprocal + * CHOAM/Richese alliance is staged; actual offer/reply/confirm actions follow. */ +function source(holder:'a'|'c' = 'a') { + let game = createGame('RICHSEMUTAMARKET',newPlayer('r','Richese','richese'),true,['choam']); + for (const [id,faction] of [['c','choam'],['a','atreides'],['e','emperor']] as const) + joinGame(game,newPlayer(id,id,faction)); + for (const seat of game.players) game = act(game,seat.id,{type:'ready'}); + game = initializeSemutaGameForAudit(game); + for (let n = 0; game.status === 'setup' && n < 200; n++) { + const step = nextStrongholdFactionsNativeStep(game); assert.ok(step); + game = act(game,step.actor,step.action); + } + assert.equal(game.status,'playing'); + for (const seat of game.players) game.deck.push(...seat.hand.splice(0)); + const karama = semutaEmperorCardId(game,card => card.effect === 'karama'); + moveSemutaEmperorCard(game,karama,'r'); + const second = game.deck.find(card => card.effect === 'karama'); assert.ok(second); + moveSemutaEmperorCard(game,second.id,'r'); + const returned = game.deck.find(card => card.kind === 'projectile' && !card.effect); assert.ok(returned); + moveSemutaEmperorCard(game,returned.id,'r'); + const offered = game.deck.find(card => card.kind === 'shield' && !card.effect); assert.ok(offered); + moveSemutaEmperorCard(game,offered.id,'c'); + moveSemutaEmperorCard(game,SEMUTA_DRUG_ID,holder); + const original = inventory(game); + game = advance(game,state => state.decision?.kind === 'choamMarket' && !state.response && !state.phaseOpening); + assert.equal(game.decision?.player,'c'); + const acquire = game.richeseCache?.find(card => card.id !== SEMUTA_DRUG_ID); assert.ok(acquire); + return {game,karama,second:second.id,returned:returned.id,offered:offered.id,acquire:acquire.id,original}; +} +const purchase = (karama:string,acquire:string) => ({type:'card',mode:'special',card:karama,acquire}); +const cash = (game:Game) => game.players.map(seat => ({id:seat.id,spice:seat.spice})); +function settleIncome(game:Game) { + assert.equal(game.response?.kind,'richesePurchaseIncome'); + return advance(game,state => !state.response && !state.pendingTreacheryDiscard); +} +function trade(game:Game, offered:string, returned:string) { + player(game,'r').ally = 'c'; player(game,'c').ally = 'r'; + game = act(game,'c',{type:'decision',mode:'trade',card:offered}); + assert.equal(game.decision?.kind,'choamTradeReply'); + game = act(game,'r',{type:'decision',card:returned}); + assert.equal(game.decision?.kind,'choamTradeConfirm'); + return game; +} + +for (const claim of [false,true]) void test(`Semuta ${claim ? 'claims' : 'passes'} the Richese special cost without losing the original CHOAM market`, () => { + const f = source(), market = structuredClone(f.game.choamMarket), decision = structuredClone(f.game.decision); + const before = cash(f.game); + assert.equal(viewGame(f.game,'r').richeseSpecialKarama?.blocked,null); + let game = act(f.game,'r',purchase(f.karama,f.acquire)); + assert.equal(game.pendingTreacheryDiscard?.batch.cause,'specialKarama:richese'); + assert.deepEqual(game.choamMarket,market); + assert.equal(player(game,'r').spice,player(f.game,'r').spice); + assert.ok(game.richeseCache?.some(card => card.id === f.acquire)); + game = reactSemutaSpecial(game,'a',claim); + assert.equal(player(game,'r').specialKaramaUsed,true); + assert.equal(player(game,'r').spice,player(f.game,'r').spice - 3); + assert.ok(player(game,'r').hand.some(card => card.id === f.acquire)); + assert.equal(player(game,'a').hand.some(card => card.id === f.karama),claim); + game = settleIncome(game); + assert.deepEqual(game.decision,decision); assert.deepEqual(game.choamMarket,market); + assert.equal(player(game,'e').spice,before.find(row => row.id === 'e')!.spice + 3); + assert.deepEqual(inventory(game),f.original); + game = act(game,'c',{type:'decision',done:true}); + assert.equal(game.choamMarket,null); +}); + +void test('a different holder may claim the special cost while the exact confirmed trade remains intact', () => { + const f = source(); + let game = trade(f.game,f.offered,f.returned); + const market = structuredClone(game.choamMarket), decision = structuredClone(game.decision); + game = act(game,'r',purchase(f.karama,f.acquire)); + assert.equal(game.pendingTreacheryDiscard?.batch.cause,'specialKarama:richese'); + game = reactSemutaSpecial(game,'a',true); + game = settleIncome(game); + assert.deepEqual(game.choamMarket,market); assert.deepEqual(game.decision,decision); + game = act(game,'c',{type:'decision',accept:true}); + assert.ok(player(game,'c').hand.some(card => card.id === f.returned)); + assert.ok(player(game,'r').hand.some(card => card.id === f.offered)); + assert.deepEqual(inventory(game),f.original); +}); + +void test('Semuta offered in a pending trade cannot be spent to claim the special cost', () => { + const f = source('c'); + let game = trade(f.game,SEMUTA_DRUG_ID,f.returned); + const market = structuredClone(game.choamMarket), decision = structuredClone(game.decision); + game = act(game,'r',purchase(f.karama,f.acquire)); + const pending = game.pendingTreacheryDiscard; assert.ok(pending?.reaction); + assert.equal(viewGame(game,'c').semutaReaction?.canCommit,false); + const before = structuredClone(game); + assert.throws(() => act(game,'c',{type:'semutaCommit',event:pending.batch.event})); + assert.deepEqual(game,before); + game = reactSemutaSpecial(game,'c',false); + game = settleIncome(game); + assert.deepEqual(game.choamMarket,market); assert.deepEqual(game.decision,decision); + game = act(game,'c',{type:'decision',accept:true}); + assert.ok(player(game,'r').hand.some(card => card.id === SEMUTA_DRUG_ID)); + assert.ok(player(game,'c').hand.some(card => card.id === f.returned)); + assert.deepEqual(inventory(game),f.original); +}); + +void test('a Karama already selected as a return cannot be spent while its trade awaits confirmation', () => { + const f = source(); + const game = trade(f.game,f.offered,f.karama); + const before = structuredClone(game); + assert.throws(() => act(game,'r',purchase(f.karama,f.acquire))); + assert.deepEqual(game,before); + assert.ok(!viewGame(game,'r').richeseSpecialKarama?.karamas.some(card => card.id === f.karama)); + assert.ok(viewGame(game,'r').richeseSpecialKarama?.karamas.some(card => card.id === f.second)); +});