Allow Richese reveals with unrelated public deals
Verify and publish checkpoint container / container (push) Successful in 11m19s

This commit is contained in:
Quintine committed 2026-11-16 15:24:41 +11:00
1 parent d7d0f89625
commit d169740adf
7 files changed
+275 -3

No files matched your search

@@ -0,0 +1,134 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as jsxRuntime from 'react/jsx-runtime';
import ts from 'typescript';
import { RicheseNoFieldControls } from '../components/richese-no-field';
import { createGame, joinGame, newPlayer, applyAction, viewGame, type Action, type Game, type GameView } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import * as catalog from '../game/catalog';
import * as board from '../game/board';
import * as advisors from '../game/advisors';
import * as shipmentPrice from '../game/shipment-price';
import * as noField from '../game/richese-no-field';
import * as homeworldCards from '../game/homeworld-cards';
import * as smuggler from '../game/smuggler-no-field';
import * as homeworldShipment from '../game/richese-homeworld-shipment';
import { actTruthMovementNativeEarly as act, nextTruthMovementNativeEarlyStep } from './fixture-truth-movement-native-early';
const owner = 'richese', observer = 'emperor', other = 'choam';
const seat = (game: Game, id: string) => { const p = game.players.find(row => row.id === id); assert.ok(p); return p; };
const quiet = (game: Game) => !game.response && !game.decision && !game.phaseOpening &&
!game.truthtrance && !game.pendingTreacheryDiscard;
function reach(game: Game, until: (state: Game) => boolean) {
for (let count = 0; count < 1800; count++) {
if (until(game)) return game;
assert.notEqual(game.status, 'finished');
const step = game.phase === 5 && game.active === observer && quiet(game)
? {actor:observer, action:{type:'endMovement'} satisfies Action}
: nextTruthMovementNativeEarlyStep(game, {position:'first', method:'onceAround', direction:'clockwise', keepUnbid:false});
assert.ok(step, `Native continuation at ${game.turn}/${game.phase}/${game.decision?.kind}`);
game = act(game, step.actor, step.action);
}
throw Error('Native game did not reach the requested window');
}
/** Original Basic three-human setup and actual paid marker shipment. Only
* unopened starting cards and Spice order are selected; the unrelated deal is
* offered and accepted through real actions before the shipment. */
function fixture() {
let game = createGame('REVEALDEAL', newPlayer(owner, 'Richese', 'richese'), false, ['choam','ix']);
joinGame(game, newPlayer(other, 'CHOAM', 'choam'));
joinGame(game, newPlayer(observer, 'Emperor', 'emperor'));
for (const p of game.players) game = act(game, p.id, {type:'ready'});
game = act(game, game.host, {type:'start'});
const cards = game.deck.filter(card => ['projectile','poison','shield','snooper'].includes(card.kind)).slice(0,3);
assert.equal(cards.length,3);
for (const [index,card] of cards.entries()) {
const from = game.deck.findIndex(candidate => candidate.id === card.id); assert.ok(from >= index);
[game.deck[index],game.deck[from]] = [game.deck[from],game.deck[index]];
}
game = reach(game, state => state.status === 'playing');
for (const index of [0,1]) {
const from = game.spiceDeck.findIndex((card,i) => i >= index && 'territory' in card && !card.discovery);
assert.ok(from >= index); [game.spiceDeck[index],game.spiceDeck[from]] = [game.spiceDeck[from],game.spiceDeck[index]];
}
game = reach(game, state => state.turn === 1 && state.phase === 5 && state.active === owner && quiet(state));
game = act(game, other, {type:'dealOffer',target:observer,terms:'Our public agreement.'});
const deal = game.deals?.at(-1); assert.ok(deal);
game = act(game, observer, {type:'dealRespond',deal:deal.id,accept:true});
assert.equal(game.deals?.at(-1)?.status,'active');
const marker = seat(game,owner).noField!.tokens.find(row => row.value === 3); assert.ok(marker);
const event = seat(game,owner).noFieldEvent; assert.ok(event);
game = act(game,owner,{type:'ship',noField:marker.id,event,territory:'polar_sink',sector:0,allyPayment:0});
game = reach(game,quiet);
game = act(game,owner,{type:'endMovement'});
game = reach(game,state => state.turn === 2 && state.decision?.kind === 'richeseDeclaration' && !state.response && !state.phaseOpening);
const revealEvent = seat(game,owner).noFieldEvent; assert.ok(revealEvent);
assert.equal(seat(game,owner).noField?.deployed?.tokenId,marker.id);
assert.equal(game.deals?.find(row => row.id === deal.id)?.status,'active');
return {game,token:marker.id,event:revealEvent,deal:deal.id};
}
let saved: ReturnType<typeof fixture> | undefined;
const source = () => saved ??= fixture();
const props = (game: GameView, act: (action: Action) => void) =>
({game,busy:false,act,destination:'arrakeen',sector:10,allyPayment:''});
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)];
}
function control(game: GameView, sent: Action[]) {
const exports: {RicheseNoFieldControls?:typeof RicheseNoFieldControls} = {};
runInNewContext(ts.transpileModule(readFileSync(new URL('../components/richese-no-field.tsx',import.meta.url),'utf8'), {
compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX},
}).outputText,{exports,require(name:string) {
const modules:Record<string,unknown> = {'react/jsx-runtime':jsxRuntime,
react:{useId:() => 'fixture',useState:(initial:unknown) => [initial,() => {}]},
'@/game/catalog':catalog,'@/game/board':board,'@/game/advisors':advisors,
'@/game/shipment-price':shipmentPrice,'@/game/richese-no-field':noField,
'@/game/homeworld-cards':homeworldCards,'@/game/smuggler-no-field':smuggler,
'@/game/richese-homeworld-shipment':homeworldShipment,
'./richese-homeworld-forces':{},'./shipment-quote':{},'./ui/button':{Button:'button'}};
if (!(name in modules)) throw Error(`Unexpected import ${name}`);
return modules[name];
}});
assert.ok(exports.RicheseNoFieldControls);
return elements(exports.RicheseNoFieldControls(props(game,action => sent.push(action))));
}
void test('real owner view and control reveal without changing an unrelated accepted deal or the native parent', () => {
const {game,token,event,deal} = source(), view = viewGame(game,owner), sent:Action[] = [];
assert.equal(view.richeseNoField?.canReveal,true);
assert.match(renderToStaticMarkup(createElement(RicheseNoFieldControls,props(view,() => {}))),/Reveal your No-Field/);
const button = control(view,sent).find(element => element.type === 'button' && element.props.children === 'Reveal your No-Field');
assert.ok(button); assert.equal(button.props.disabled,false);
(button.props.onClick as () => void)();
assert.deepEqual(JSON.parse(JSON.stringify(sent)),[{type:'revealNoField',token,event}]);
const parent = structuredClone(game.decision), agreement = structuredClone(game.deals?.find(row => row.id === deal));
const after = act(game,owner,sent[0]);
assert.deepEqual(after.decision,parent); assert.deepEqual(after.deals?.find(row => row.id === deal),agreement);
assert.equal(seat(after,owner).noField?.deployed,null);
assert.equal(seat(after,owner).forces['polar_sink:0'],3);
});
void test('foreign player cannot reveal, while all bot levels can continue the original decision', () => {
const {game,token,event,deal} = source(), foreign = viewGame(game,observer);
assert.equal(foreign.richeseNoField?.private,null);
assert.equal(renderToStaticMarkup(createElement(RicheseNoFieldControls,props(foreign,() => {}))),'');
assert.throws(() => act(game,observer,{type:'revealNoField',token,event}));
const after = act(game,owner,{type:'revealNoField',token,event});
for (const level of DIFFICULTIES) {
const view = viewGame(after,owner); view.players.find(p => p.id === owner)!.bot = level;
const choice = botActions(view).find(action => action.type === 'decision');
assert.ok(choice,`${level} must continue the original decision`);
const continued = applyAction(structuredClone(after),owner,choice);
assert.notDeepEqual(continued.decision,after.decision);
assert.equal(continued.deals?.find(row => row.id === deal)?.status,'active');
}
});
@@ -0,0 +1,90 @@
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 as inventory } from './fixture-truth-movement';
const player = (game: Game, id: string) => {
const seat = game.players.find(row => row.id === id); assert.ok(seat); return seat;
};
const quiet = (game: Game) => !game.response && !game.decision && !game.phaseOpening &&
!game.truthtrance && !game.pendingTreacheryDiscard;
function advance(game: Game, until: (state: Game) => boolean): Game {
for (let count = 0; count < 1800; count++) {
if (until(game)) return game;
assert.notEqual(game.status, 'finished');
const step = game.phase === 5 && game.active === 'emperor' && quiet(game)
? {actor:'emperor', action:{type:'endMovement'} satisfies Action}
: nextTruthMovementNativeEarlyStep(game, {position:'first', method:'onceAround', direction:'clockwise', keepUnbid:false});
assert.ok(step, `A native continuation is needed at ${game.turn}/${game.phase}/${game.decision?.kind}`);
game = act(game,step.actor,step.action);
}
throw Error('The native game did not reach the requested boundary.');
}
/** Real selected-deck Basic setup, paid No-Field shipment, and two separately
* consented deals. Only original unopened starting cards and Spice positions
* are selected; no marker, offer, payment, balance or response is staged. */
function source() {
let game = createGame('REVEALDEAL',newPlayer('richese','Richese','richese'),false,['choam','ix']);
for (const id of ['choam','emperor'] as const) joinGame(game,newPlayer(id,id,id));
for (const seat of game.players) game = act(game,seat.id,{type:'ready'});
game = act(game,game.host,{type:'start'});
const ordinary = game.deck.filter(card => ['projectile','poison','shield','snooper'].includes(card.kind)).slice(0,2);
const karama = game.deck.find(card => card.effect === 'karama');
assert.equal(ordinary.length,2); assert.ok(karama);
for (const [position,card] of [...ordinary,karama].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');
for (const position of [0,1]) {
const from = game.spiceDeck.findIndex((card,index) => index >= position && 'territory' in card && !card.discovery);
assert.ok(from >= position); [game.spiceDeck[position],game.spiceDeck[from]] = [game.spiceDeck[from],game.spiceDeck[position]];
}
game = advance(game,state => state.turn === 1 && state.phase === 5 && state.active === 'richese' && quiet(state));
const token = player(game,'richese').noField!.tokens.find(row => row.value === 3); assert.ok(token);
const event = player(game,'richese').noFieldEvent; assert.ok(event);
game = act(game,'richese',{type:'ship',noField:token.id,event,territory:'polar_sink',sector:0,allyPayment:0});
game = advance(game,quiet);
game = act(game,'richese',{type:'dealOffer',target:'choam',terms:'Public agreement.'});
const written = game.deals?.at(-1); assert.ok(written);
game = act(game,'choam',{type:'dealRespond',deal:written.id,accept:true});
const payment = {kind:'deferredBribe',payer:'richese',recipient:'choam',amount:1,dueTurn:2};
game = act(game,'richese',{type:'dealOffer',target:'choam',terms:'One spice on turn two.',payment});
const offer = game.deals?.at(-1); assert.ok(offer);
game = act(game,'choam',{type:'dealRespond',deal:offer.id,accept:true});
assert.equal(game.deals?.find(row => row.id === offer.id)?.paymentStatus,'pending');
game = act(game,'richese',{type:'endMovement'});
game = advance(game,state => state.turn === 2 && state.phase === 2 && state.response?.kind === 'choamCharity');
const revealEvent = player(game,'richese').noFieldEvent; assert.ok(revealEvent);
return {game,token:token.id,event:revealEvent,written:written.id,payment:offer.id};
}
let cached: ReturnType<typeof source> | undefined;
const fixture = () => cached ??= source();
void test('a revealed No-Field preserves both active public deals and the original Charity response', () => {
const {token,event,written,payment} = fixture();
let before = structuredClone(fixture().game);
before = act(before,'richese',{type:'passResponse'});
const response = structuredClone(before.response), deals = structuredClone(before.deals), cards = inventory(before);
const reserves = player(before,'richese').reserves, forces = player(before,'richese').forces['polar_sink:0'] ?? 0;
assert.equal(viewGame(before,'richese').richeseNoField?.canReveal,true);
const after = act(before,'richese',{type:'revealNoField',token,event});
assert.deepEqual(after.response,response);
assert.deepEqual(after.deals,deals);
assert.equal(player(after,'richese').noField?.deployed,null);
assert.equal(player(after,'richese').reserves,reserves - 3);
assert.equal(player(after,'richese').forces['polar_sink:0'],forces + 3);
assert.deepEqual(inventory(after),cards);
const continued = advance(after,state => quiet(state) && state.response?.kind !== 'choamCharity');
assert.equal(continued.deals?.find(row => row.id === written)?.status,'active');
assert.equal(continued.deals?.find(row => row.id === payment)?.paymentStatus,'pending');
const payer = player(continued,'richese').spice, recipientBribes = player(continued,'choam').bribes;
const paid = act(continued,'richese',{type:'dealPay',deal:payment});
assert.equal(paid.deals?.find(row => row.id === payment)?.paymentStatus,'paid');
assert.equal(player(paid,'richese').spice,payer - 1);
assert.equal(player(paid,'choam').bribes,recipientBribes + 1);
assert.equal(player(paid,'richese').forces['polar_sink:0'],forces + 3);
assert.deepEqual(inventory(paid),cards);
});
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createGame, newPlayer, type Decision, type Game } from '../game/engine';
import { createPublicDeal, respondPublicDeal } from '../game/public-deals';
import { richeseRevealInterruptSupported as supported } from '../game/richese-reveal-interruption';
/** Staged parent records test only the admission quote; native parent and
@@ -185,5 +186,21 @@ void test('live current-turn commitments block the interruption; settled and pre
game.futureBattleLeaderPromises = [{turn:game.turn, asker:'r', player:'e', leader:'leader', answer:true, status:'waiting'}];
assert.equal(supported(game), false);
game.futureBattleLeaderPromises[0].status = 'settled'; assert.equal(supported(game), true);
game.deals = [{status:'active'}] as unknown as Game['deals']; assert.equal(supported(game), false);
game.travelPromises = [{turn:game.turn, player:'r', asker:'e', answer:true, fulfilled:false, released:false}] as unknown as Game['travelPromises'];
assert.equal(supported(game), false);
game.travelPromises![0].turn++; assert.equal(supported(game), true);
});
void test('active text and deferred-payment deals do not independently block a clean reveal opportunity', () => {
const game = parent('auctionPayment');
const text = createPublicDeal(game.players, 'r', 'c', 'A public agreement.', game.turn, 'text');
const current = createPublicDeal(game.players, 'c', 'e', 'Pay this turn.', game.turn, 'current',
{kind:'deferredBribe', payer:'c', recipient:'e', amount:1, dueTurn:game.turn});
const future = createPublicDeal(game.players, 'r', 'e', 'Pay later.', game.turn, 'future',
{kind:'deferredBribe', payer:'r', recipient:'e', amount:2, dueTurn:game.turn + 1});
game.deals = [respondPublicDeal(text, game.players, 'c', true),
respondPublicDeal(current, game.players, 'e', true), respondPublicDeal(future, game.players, 'e', true)];
const before = structuredClone(game);
assert.equal(supported(game), true);
assert.deepEqual(game, before, 'The admission quote must not mutate the deals or parent.');
});