Time sequential Richese auctions
Verify and publish checkpoint container / container (push) Canceled after 0s
Verify and publish checkpoint container / container (push) Canceled after 0s
This commit is contained in:
1 parent
e7520e8679
commit
7fc6f1cd43
15 files changed
+692
-38
No files matched your search
@@ -0,0 +1,109 @@
|
||||
// @dune-suite integration
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { botActions } from '../game/bots';
|
||||
import type { Action, GameView } from '../game/engine';
|
||||
|
||||
const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000';
|
||||
async function request(path: string, cookie?: string, body?: unknown) {
|
||||
const response = await fetch(base + path, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
headers: {
|
||||
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
...(cookie ? { cookie } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
return {
|
||||
status: response.status,
|
||||
cookie: response.headers.get('set-cookie')?.split(';')[0],
|
||||
data: await response.json() as GameView & { error?: string },
|
||||
};
|
||||
}
|
||||
|
||||
/** Only this new QA room is used. Both factions are real human seats; the
|
||||
* existing bot adapter proposes setup/phase choices from each seat's private
|
||||
* view without changing the server's seat control or staging game state. */
|
||||
void test('authenticated Once Around cache clock expires to the native pass and rejects a late bid', async () => {
|
||||
const host = await request('/api/rooms', undefined, {
|
||||
name: 'Richese clock QA', faction: 'richese', advanced: false, expansions: ['choam'],
|
||||
});
|
||||
assert.equal(host.status, 201, JSON.stringify(host.data)); assert.ok(host.cookie);
|
||||
const path = `/api/rooms/${host.data.code}`;
|
||||
const peer = await request(path, undefined, {type:'join', name:'Clock QA opponent', faction:'atreides'});
|
||||
assert.equal(peer.status, 200, JSON.stringify(peer.data)); assert.ok(peer.cookie);
|
||||
const seats = [{id:host.data.me, cookie:host.cookie}, {id:peer.data.me, cookie:peer.cookie}];
|
||||
let view = peer.data;
|
||||
async function read(cookie: string) {
|
||||
const result = await request(path, cookie);
|
||||
assert.equal(result.status, 200, JSON.stringify(result.data));
|
||||
view = result.data;
|
||||
return view;
|
||||
}
|
||||
async function act(cookie: string, action: Action) {
|
||||
const result = await request(path, cookie, {version:view.version, action});
|
||||
assert.equal(result.status, 200, `Rejected ${action.type}: ${JSON.stringify(result.data)}`);
|
||||
view = result.data;
|
||||
return view;
|
||||
}
|
||||
for (const seat of seats) await act(seat.cookie, {type:'ready'});
|
||||
await act(host.cookie, {type:'start'});
|
||||
|
||||
// Stop at the native response before the first cache, then choose its
|
||||
// printed sequential method. Every other action comes from real views.
|
||||
let clocked: GameView | null = null;
|
||||
for (let count = 0; count < 400; count++) {
|
||||
const owner = await read(host.cookie);
|
||||
assert.notEqual(owner.status, 'finished', 'The QA game ended before its first cache lot.');
|
||||
if (owner.richeseAuction?.source === 'cache' && owner.richeseAuction.method === 'onceAround' &&
|
||||
owner.richeseAuction.active && owner.auctionClock?.event && owner.auctionClock.running &&
|
||||
!owner.response && !owner.decision && !owner.phaseOpening) {
|
||||
clocked = owner;
|
||||
break;
|
||||
}
|
||||
if (owner.decision?.kind === 'richeseDeclaration' && owner.decision.player === owner.me && owner.richeseBidding) {
|
||||
await act(host.cookie, {type:'decision', event:owner.richeseBidding.event, position:'first'});
|
||||
continue;
|
||||
}
|
||||
if (owner.decision?.kind === 'richeseCache' && owner.decision.player === owner.me && owner.richeseBidding) {
|
||||
const card = owner.richeseBidding.cache?.[0]; assert.ok(card);
|
||||
await act(host.cookie, {type:'decision', event:owner.richeseBidding.event,
|
||||
card:card.id, method:'onceAround', direction:'clockwise'});
|
||||
continue;
|
||||
}
|
||||
let choice: {cookie:string; action:Action} | null = null;
|
||||
for (const seat of seats) {
|
||||
const current = await read(seat.cookie);
|
||||
const local = structuredClone(current);
|
||||
const self = local.players.find(player => player.id === seat.id); assert.ok(self);
|
||||
self.bot = 'Easy';
|
||||
const action = botActions(local)[0];
|
||||
if (action) { choice = {cookie:seat.cookie, action}; break; }
|
||||
}
|
||||
assert.ok(choice, `No native continuation at ${owner.status}/${owner.phase}/${owner.decision?.kind ?? 'no decision'}.`);
|
||||
if (view.response && !view.response.passed.includes(view.me)) choice.action = {type:'passResponse'};
|
||||
await act(choice.cookie, choice.action);
|
||||
}
|
||||
assert.ok(clocked, 'The dedicated room did not reach an active Once Around clock.');
|
||||
const lot = clocked.richeseAuction; assert.ok(lot?.active);
|
||||
const clock = clocked.auctionClock; assert.ok(clock?.event);
|
||||
assert.equal(clock.player, lot.active);
|
||||
const bidder = seats.find(seat => seat.id === lot.active); assert.ok(bidder);
|
||||
const oldVersion = clocked.version;
|
||||
const lotEvent = lot.event;
|
||||
|
||||
// The HTTP boundary uses the real server clock. The room worker or the
|
||||
// authenticated late-action preflight must expire the original bid once.
|
||||
await new Promise(resolve => setTimeout(resolve, 11_500));
|
||||
const late = await request(path, bidder.cookie, {version:oldVersion,
|
||||
action:{type:'richeseBid', event:lotEvent, amount:1, allyPayment:0}});
|
||||
assert.ok(late.status >= 400, 'A bid from the expired version must not be accepted.');
|
||||
const after = await read(host.cookie);
|
||||
assert.ok(after.version > oldVersion);
|
||||
assert.equal(after.richeseAuction?.event, lotEvent);
|
||||
assert.ok(after.richeseAuction?.passed.includes(bidder.id));
|
||||
assert.equal(after.richeseAuction?.bid, 0);
|
||||
assert.equal(after.richeseAuction?.outcome?.kind, 'unbid');
|
||||
assert.equal(after.decision?.kind, 'richeseUnbid');
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { advanceAuctionClock, hasAuctionClockOpportunity, synchronizeAuctionClock,
|
||||
viewGame, type Game } from '../game/engine';
|
||||
import {
|
||||
actSemutaRicheseCacheKarama as act,
|
||||
advanceSemutaRicheseCacheKarama as advance,
|
||||
createSemutaRicheseCacheKaramaFixture as fixture,
|
||||
semutaRicheseCacheKaramaInventory as inventory,
|
||||
} from './fixture-semuta-richese-cache-karama';
|
||||
import { createTruthRicheseBidFixture, bindTruthRicheseBid, declareTruthRicheseBid,
|
||||
passTruthRicheseFreshDiscard } from './fixture-truth-richese-bid';
|
||||
import { createSaphoCyclicAuctionFixture, actSaphoCyclic, saphoCyclicAction,
|
||||
saphoCyclicBid } from './fixture-sapho-cyclic-auction';
|
||||
|
||||
const epoch = '0:0';
|
||||
type Method = 'normal' | 'onceAround' | 'silent';
|
||||
|
||||
/** Genuine Basic cache: Richese previously sold Semuta and now declares its
|
||||
* second-turn first cache lot. The fixture selects only unopened card/spice
|
||||
* positions; this helper takes the original response and owner decisions. */
|
||||
function cache(method: 'onceAround' | 'silent'): Game {
|
||||
const f = fixture({position:'first'});
|
||||
let game = advance(f.game, state => !state.response && !state.phaseOpening &&
|
||||
state.decision?.kind === 'richeseCache');
|
||||
const card = game.richeseCache?.[0]; assert.ok(card && game.richeseBidding);
|
||||
game = act(game, 'richese', {type:'decision', event:game.richeseBidding.event,
|
||||
card:card.id, method, direction:'clockwise'});
|
||||
assert.equal(game.richeseAuction?.source, 'cache');
|
||||
assert.equal(game.richeseAuction?.method, method);
|
||||
assert.ok(!game.response && !game.decision && !game.phaseOpening);
|
||||
return game;
|
||||
}
|
||||
|
||||
/** An actual original Advanced game reaches its first Black Market decision.
|
||||
* The original owner offers a real held card and all response/inspection
|
||||
* windows are resolved through the existing native action driver. */
|
||||
function blackMarket(method: Method): Game {
|
||||
const f = fixture({advanced:true});
|
||||
let game = structuredClone(f.afterSetup);
|
||||
const front: Game['spiceDeck'] = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const index = game.spiceDeck.findIndex(card => 'territory' in card && !card.discovery);
|
||||
assert.ok(index >= 0); front.push(game.spiceDeck.splice(index,1)[0]);
|
||||
}
|
||||
game.spiceDeck.unshift(...front);
|
||||
game = advance(game, state => !state.response && !state.phaseOpening &&
|
||||
state.decision?.kind === 'richeseBlackMarket');
|
||||
const owner = game.players.find(player => player.id === 'richese');
|
||||
assert.ok(owner && owner.hand.length && game.richeseBidding);
|
||||
game = act(game, 'richese', {type:'decision', event:game.richeseBidding.event,
|
||||
card:owner.hand[0].id, method, ...(method === 'onceAround' ? {direction:'clockwise'} : {})});
|
||||
game = advance(game, state => state.richeseAuction?.source === 'blackMarket' &&
|
||||
state.richeseAuction.method === method && !state.response && !state.phaseOpening && !state.decision);
|
||||
assert.equal(game.richeseAuction?.source, 'blackMarket');
|
||||
return game;
|
||||
}
|
||||
|
||||
for (const source of ['cache', 'blackMarket'] as const)
|
||||
for (const method of (source === 'cache' ? ['onceAround'] : ['normal','onceAround']) as Exclude<Method,'silent'>[])
|
||||
void test(`${source} ${method} expires at the deadline through its native pass`,()=>{
|
||||
const initial = source === 'cache' ? cache('onceAround') : blackMarket(method);
|
||||
const lot = initial.richeseAuction; assert.ok(lot && lot.active);
|
||||
const original = structuredClone(initial), originalCards = inventory(initial);
|
||||
assert.equal(hasAuctionClockOpportunity(initial),true);
|
||||
const armed = synchronizeAuctionClock(initial,1_000,epoch);
|
||||
assert.equal(armed.auctionClock?.player,lot.active);
|
||||
assert.equal(armed.auctionClock?.remainingMs,10_000);
|
||||
assert.equal(armed.auctionClock?.startedAt,1_000);
|
||||
assert.equal(advanceAuctionClock(armed,10_999,epoch),armed);
|
||||
const expected = act(initial,lot.active,{type:'richeseBid',event:lot.event,amount:null});
|
||||
const expired = advanceAuctionClock(armed,11_000,epoch);
|
||||
assert.deepEqual(expired.richeseAuction,expected.richeseAuction);
|
||||
assert.equal(expired.active,expected.active);
|
||||
assert.ok(expired.richeseAuction?.passed.includes(lot.active));
|
||||
assert.notEqual(expired.auctionClock?.event,armed.auctionClock?.event);
|
||||
assert.equal(expired.auctionClock?.remainingMs,10_000);
|
||||
assert.equal(expired.auctionClock?.startedAt,11_000);
|
||||
assert.deepEqual(inventory(expired),originalCards);
|
||||
assert.deepEqual(initial,original);
|
||||
});
|
||||
|
||||
void test('a native special-lot bid resets the next bidder and an administrative pause preserves the remainder',()=>{
|
||||
const initial=blackMarket('normal'), lot=initial.richeseAuction; assert.ok(lot?.active);
|
||||
let game=synchronizeAuctionClock(initial,1_000,epoch);
|
||||
const original=game.auctionClock!.event;
|
||||
game=act(game,lot.active,{type:'richeseBid',event:lot.event,amount:1,allyPayment:0});
|
||||
game=synchronizeAuctionClock(game,2_000,epoch);
|
||||
assert.notEqual(game.auctionClock!.event,original);
|
||||
assert.equal(game.auctionClock!.player,game.richeseAuction!.active);
|
||||
game=synchronizeAuctionClock(game,5_000,epoch,true);
|
||||
assert.equal(game.auctionClock!.remainingMs,7_000); assert.equal(game.auctionClock!.startedAt,null);
|
||||
const held=advanceAuctionClock(game,50_000,epoch,true); assert.deepEqual(held,game);
|
||||
game=synchronizeAuctionClock(held,50_000,epoch);
|
||||
assert.equal(game.auctionClock!.remainingMs,7_000); assert.equal(game.auctionClock!.startedAt,50_000);
|
||||
assert.equal(advanceAuctionClock(game,56_999,epoch),game);
|
||||
const actor=game.richeseAuction!.active!;
|
||||
const expected=act(game,actor,{type:'richeseBid',event:game.richeseAuction!.event,amount:null});
|
||||
const expired=advanceAuctionClock(game,57_000,epoch);
|
||||
assert.deepEqual(expired.richeseAuction,expected.richeseAuction);
|
||||
});
|
||||
|
||||
for (const source of ['cache','blackMarket'] as const)
|
||||
void test(`${source} Silent auction is simultaneous and has no sequential bidding clock`,()=>{
|
||||
const game=source==='cache'?cache('silent'):blackMarket('silent');
|
||||
const lot=game.richeseAuction; assert.ok(lot && lot.active===null);
|
||||
assert.equal(hasAuctionClockOpportunity(game),false);
|
||||
assert.equal(synchronizeAuctionClock(game,1_000,epoch),game);
|
||||
assert.equal(advanceAuctionClock(game,1_000_000,epoch),game);
|
||||
for (const seat of game.players) assert.equal(viewGame(game,seat.id,10_000).auctionClock,null);
|
||||
});
|
||||
|
||||
void test('the special-lot clock exposes only public countdown fields, never a Black Market card identity',()=>{
|
||||
const source=blackMarket('onceAround'), lot=source.richeseAuction; assert.ok(lot && lot.active);
|
||||
const game=synchronizeAuctionClock(source,1_000,epoch);
|
||||
for (const seat of game.players) {
|
||||
const view=viewGame(game,seat.id,3_250);
|
||||
assert.deepEqual(Object.keys(view.auctionClock!).sort(),['event','player','remainingMs','running']);
|
||||
assert.equal(view.auctionClock!.remainingMs,7_750);
|
||||
assert.equal(view.auctionClock!.player,lot.active);
|
||||
assert.ok(!JSON.stringify(view.auctionClock).includes(lot.cardId));
|
||||
}
|
||||
});
|
||||
|
||||
void test('a previously opened unstamped special lot is not retroactively timed',()=>{
|
||||
const game=blackMarket('onceAround');
|
||||
assert.ok(game.richeseAuction);
|
||||
const old=structuredClone(game);
|
||||
delete old.richeseAuction!.clockVersion;
|
||||
assert.equal(hasAuctionClockOpportunity(old),false);
|
||||
assert.equal(synchronizeAuctionClock(old,1_000,epoch),old);
|
||||
assert.equal(advanceAuctionClock(old,1_000_000,epoch),old);
|
||||
assert.equal(viewGame(old,'richese',1_000_000).auctionClock,null);
|
||||
});
|
||||
|
||||
void test('a Once Around timeout honors the original binding Truthtrance Yes with the legal required bid',()=>{
|
||||
const f=createTruthRicheseBidFixture();
|
||||
const source=act(f.game,f.asker,{type:'richeseBid',event:f.lot,amount:null});
|
||||
assert.equal(source.richeseAuction?.active,f.target);
|
||||
const game=bindTruthRicheseBid(f,'yes',4,source).game;
|
||||
const guide=viewGame(game,f.target).richeseBidPromiseGuide; assert.ok(guide);
|
||||
assert.equal(guide.action.type,'richeseBid'); assert.equal(guide.action.amount,4);
|
||||
const armed=synchronizeAuctionClock(game,1_000,epoch);
|
||||
const expired=advanceAuctionClock(armed,11_000,epoch);
|
||||
assert.equal(expired.richeseAuction?.bid,4);
|
||||
assert.equal(expired.richeseAuction?.bidder,f.target);
|
||||
assert.ok(expired.richeseBidPromises?.some(row=>row.player===f.target && row.fulfilled));
|
||||
assert.deepEqual(inventory(expired),f.originalCards);
|
||||
});
|
||||
|
||||
void test('a Once Around timeout may pass when a binding Truthtrance No forbids the qualifying bid',()=>{
|
||||
const f=createTruthRicheseBidFixture();
|
||||
const source=act(f.game,f.asker,{type:'richeseBid',event:f.lot,amount:null});
|
||||
assert.equal(source.richeseAuction?.active,f.target);
|
||||
const game=bindTruthRicheseBid(f,'no',4,source).game;
|
||||
const expected=act(game,f.target,{type:'richeseBid',event:f.lot,amount:null});
|
||||
const armed=synchronizeAuctionClock(game,1_000,epoch);
|
||||
const expired=advanceAuctionClock(armed,11_000,epoch);
|
||||
assert.deepEqual(expired.richeseAuction,expected.richeseAuction);
|
||||
assert.ok(expired.richeseAuction?.passed.includes(f.target));
|
||||
assert.notEqual(expired.richeseAuction?.bidder,f.target);
|
||||
assert.deepEqual(inventory(expired),f.originalCards);
|
||||
});
|
||||
|
||||
void test('Sapho moving another Black Market bidder last does not refresh the unchanged current bidder',()=>{
|
||||
const f=createSaphoCyclicAuctionFixture({advanced:true,blackMarket:true});
|
||||
const first=saphoCyclicBid(f.game,1);
|
||||
let game=actSaphoCyclic(f.game,first.actor,first.action);
|
||||
const lot=game.richeseAuction; assert.ok(lot?.active);
|
||||
assert.notEqual(lot.active,f.owner,'The Sapho owner is not the current bidder');
|
||||
const action=saphoCyclicAction(game,'last');
|
||||
game=synchronizeAuctionClock(game,1_000,epoch);
|
||||
const original=game.auctionClock!;
|
||||
const next=actSaphoCyclic(game,f.owner,action);
|
||||
assert.equal(next.richeseAuction?.active,lot.active);
|
||||
game=synchronizeAuctionClock(next,3_000,epoch);
|
||||
assert.equal(game.auctionClock?.event,original.event);
|
||||
assert.equal(game.auctionClock?.player,original.player);
|
||||
assert.equal(viewGame(game,f.owner,3_000).auctionClock?.remainingMs,8_000);
|
||||
assert.equal(game.auctionClock?.startedAt,1_000);
|
||||
});
|
||||
|
||||
void test('the native Truthtrance interruption holds and resumes the same Once Around clock',()=>{
|
||||
const f=createTruthRicheseBidFixture(), armed=synchronizeAuctionClock(f.game,1_000,epoch);
|
||||
const declared=declareTruthRicheseBid(f,armed), held=synchronizeAuctionClock(declared,3_000,epoch);
|
||||
assert.equal(held.auctionClock!.event,armed.auctionClock!.event);
|
||||
assert.equal(held.auctionClock!.remainingMs,8_000); assert.equal(held.auctionClock!.startedAt,null);
|
||||
assert.deepEqual(advanceAuctionClock(held,50_000,epoch),held);
|
||||
let game=act(held,f.asker,{type:'truthAsk',question:{kind:'richeseBid',target:f.target,
|
||||
turn:held.turn,event:f.lot,minimum:4}});
|
||||
game=act(game,f.target,{type:'truthAnswer',answer:'no'});
|
||||
game=passTruthRicheseFreshDiscard(game);
|
||||
game=synchronizeAuctionClock(game,50_000,epoch);
|
||||
assert.equal(game.auctionClock!.event,armed.auctionClock!.event);
|
||||
assert.equal(game.auctionClock!.remainingMs,8_000); assert.equal(game.auctionClock!.startedAt,50_000);
|
||||
assert.equal(advanceAuctionClock(game,57_999,epoch),game);
|
||||
const expired=advanceAuctionClock(game,58_000,epoch);
|
||||
assert.ok(expired.richeseAuction?.passed.includes(f.asker));
|
||||
assert.deepEqual(inventory(expired),f.originalCards);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { createElement, type ReactNode } from 'react';
|
||||
import * as jsxRuntime from 'react/jsx-runtime';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
import { RicheseAuctionCountdown } from '../components/richese-auction-countdown';
|
||||
import type { AuctionClockView } from '../game/auction-clock';
|
||||
|
||||
const frame = (remainingMs = 10_000, running = true, event: string | null = 'bid-event'): AuctionClockView =>
|
||||
({ event, player: 'p', remainingMs, running });
|
||||
const html = (clock: AuctionClockView | null, method: 'onceAround' | 'normal', paused = false) =>
|
||||
renderToStaticMarkup(createElement(RicheseAuctionCountdown, { clock, playerName: 'Respondent', method, paused }));
|
||||
|
||||
void test('sequential Richese countdown presents the live bidder, method and server-controlled expiry', () => {
|
||||
for (const [method, label] of [['onceAround', 'Once Around'], ['normal', 'Black Market']] as const) {
|
||||
const clock = frame(1001), before = structuredClone(clock), markup = html(clock, method);
|
||||
assert.match(markup, new RegExp(`${label} auction countdown`));
|
||||
assert.match(markup, /Respondent may bid or pass/);
|
||||
assert.match(markup, /2 seconds remaining/);
|
||||
assert.match(markup, /role="timer" aria-live="off"/);
|
||||
assert.match(markup, /server controls the deadline/);
|
||||
if (method === 'onceAround') {
|
||||
assert.match(markup, /provisional online interpretation/);
|
||||
assert.match(markup, /binding Truthtrance answer/);
|
||||
}
|
||||
assert.doesNotMatch(markup, /<button|<form|Continue/);
|
||||
assert.deepEqual(clock, before);
|
||||
}
|
||||
assert.equal(html(null, 'onceAround'), '');
|
||||
});
|
||||
|
||||
void test('Richese countdown keeps unarmed, held, paused and expired states distinct', () => {
|
||||
assert.match(html(frame(10_000, false, null), 'onceAround'), /Clock starts when bidding is ready/);
|
||||
assert.match(html(frame(6_200, false), 'normal'), /held while the current game decision finishes/);
|
||||
assert.match(html(frame(6_200), 'onceAround', true), /Auction paused/);
|
||||
assert.match(html(frame(0, false), 'onceAround'), /Awaiting server resolution/);
|
||||
assert.match(html(frame(0, false), 'onceAround'), /0 seconds remaining/);
|
||||
});
|
||||
|
||||
/** Exercise the real effect with a controlled monotonic browser clock. */
|
||||
function browserDisplay(initial: Parameters<typeof RicheseAuctionCountdown>[0]) {
|
||||
type Effect = { dependencies: readonly unknown[]; cleanup?: () => void };
|
||||
const states: unknown[] = [], effects: Effect[] = [], pending: (() => void)[] = [];
|
||||
const intervals = new Map<number, () => void>();
|
||||
let stateIndex = 0, effectIndex = 0, now = 0, nextTimer = 0, props = initial;
|
||||
const exports: { RicheseAuctionCountdown?: typeof RicheseAuctionCountdown } = {};
|
||||
runInNewContext(ts.transpileModule(readFileSync(new URL('../components/richese-auction-countdown.tsx', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
|
||||
}).outputText, {
|
||||
exports,
|
||||
performance: { now: () => now },
|
||||
setInterval(callback: () => void, ms: number) { assert.equal(ms, 200); const timer = ++nextTimer; intervals.set(timer, callback); return timer; },
|
||||
clearInterval(timer: number) { intervals.delete(timer); },
|
||||
require(name: string) {
|
||||
if (name === 'react/jsx-runtime') return jsxRuntime;
|
||||
assert.equal(name, 'react');
|
||||
return {
|
||||
useState(initialValue: unknown) {
|
||||
const index = stateIndex++;
|
||||
if (!(index in states)) states[index] = initialValue;
|
||||
return [states[index], (next: unknown) => { states[index] = next; }];
|
||||
},
|
||||
useEffect(callback: () => (() => void) | undefined, dependencies: readonly unknown[]) {
|
||||
const index = effectIndex++, previous = effects[index];
|
||||
if (previous && dependencies.every((dependency, i) => Object.is(dependency, previous.dependencies[i]))) return;
|
||||
pending.push(() => { previous?.cleanup?.(); effects[index] = { dependencies, cleanup: callback() }; });
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.ok(exports.RicheseAuctionCountdown);
|
||||
const render = () => {
|
||||
stateIndex = 0; effectIndex = 0;
|
||||
const node: ReactNode = exports.RicheseAuctionCountdown!(props);
|
||||
const markup = renderToStaticMarkup(node);
|
||||
while (pending.length) pending.shift()!();
|
||||
return markup;
|
||||
};
|
||||
return {
|
||||
render,
|
||||
update(next: typeof initial) { props = next; return render(); },
|
||||
advance(ms: number) { now += ms; for (const callback of intervals.values()) callback(); return render(); },
|
||||
get ticking() { return intervals.size; },
|
||||
};
|
||||
}
|
||||
|
||||
void test('local countdown follows elapsed time and stops while paused or awaiting the server', () => {
|
||||
const display = browserDisplay({ clock: frame(), playerName: 'Respondent', method: 'onceAround' });
|
||||
assert.match(display.render(), /10 seconds remaining/); assert.equal(display.ticking, 1);
|
||||
assert.match(display.advance(5401), /5 seconds remaining/);
|
||||
assert.match(display.update({ clock: frame(2000, false), playerName: 'Respondent', method: 'onceAround' }), /2 seconds remaining/);
|
||||
assert.equal(display.ticking, 0);
|
||||
assert.match(display.update({ clock: frame(1000), playerName: 'Respondent', method: 'normal' }), /Black Market/);
|
||||
assert.match(display.advance(1000), /Awaiting server resolution/); assert.equal(display.ticking, 0);
|
||||
assert.equal(display.update({ clock: null, playerName: 'Respondent', method: 'normal' }), '');
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import test from 'node:test';
|
||||
import { applyAction, type Action } from '../game/engine';
|
||||
import type * as Rooms from '../db/rooms';
|
||||
import { unitStore } from './fixture-nexus-room-store';
|
||||
import { createTruthRicheseBidFixture, inventory } from './fixture-truth-richese-bid';
|
||||
|
||||
function fakeClock(start = 10_000) {
|
||||
let time = start;
|
||||
const sleeps: number[] = [];
|
||||
return { now: () => time, advance: (ms: number) => { time += ms; }, sleeps,
|
||||
sleep: async (ms: number) => { sleeps.push(ms); time += ms; } } satisfies Rooms.RoomsClock & {
|
||||
advance(ms: number): void; sleeps: number[];
|
||||
};
|
||||
}
|
||||
|
||||
/** The source is a genuine public Basic game and native Once Around cache
|
||||
* lot. Only the parent fixture's unopened cards and scalar lotteries are
|
||||
* selected; no wallet, force, lot, response or stored deadline is staged. */
|
||||
function fixture() {
|
||||
const native = createTruthRicheseBidFixture(), game = structuredClone(native.game);
|
||||
const lot = game.richeseAuction; assert.ok(lot && lot.method === 'onceAround' && lot.active);
|
||||
assert.equal(lot.clockVersion, 1, 'A newly opened sequential special lot uses trusted timing');
|
||||
const store = unitStore(), clock = fakeClock(), code = game.code;
|
||||
store.sqlite.prepare('INSERT INTO rooms(code,state,version,updated_at) VALUES(?,?,0,?)')
|
||||
.run(code, JSON.stringify(game), clock.now());
|
||||
const auth = Object.fromEntries(game.players.map(player => {
|
||||
const tokenHash = createHash('sha256').update(`richese-auction-clock-test:${player.id}`).digest('hex');
|
||||
store.sqlite.prepare('INSERT INTO seats(token_hash,room_code,player_id) VALUES(?,?,?)').run(tokenHash, code, player.id);
|
||||
return [player.id, { playerId: player.id, tokenHash }];
|
||||
})) as Record<string, Rooms.SeatAuth>;
|
||||
return { ...store, clock, code, native, auth, actor: lot.active, event: lot.event };
|
||||
}
|
||||
|
||||
void test('a trusted room clock arms and expires a genuine Once Around bid through its native pass', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
const view = await f.rooms.readSeatView(f.code, f.auth[f.actor], f.clock);
|
||||
assert.equal(view.auctionClock?.player, f.actor);
|
||||
assert.equal(view.auctionClock?.remainingMs, 10_000);
|
||||
assert.equal(view.auctionClock?.running, true);
|
||||
assert.equal(typeof view.auctionClock?.event, 'string');
|
||||
assert.equal(f.rooms.needsAutomaticRoomRecovery(await f.rooms.readRoom(f.code)), true);
|
||||
f.clock.advance(9999);
|
||||
assert.equal(await f.rooms.continueRoomAuctionClock(f.code, f.clock), false);
|
||||
assert.equal((await f.rooms.readRoom(f.code)).richeseAuction?.active, f.actor);
|
||||
const expected = applyAction(f.native.game, f.actor,
|
||||
{ type: 'richeseBid', event: f.event, amount: null, allyPayment: 0 });
|
||||
f.clock.advance(1);
|
||||
assert.equal(await f.rooms.continueRoomAuctionClock(f.code, f.clock), true);
|
||||
const game = await f.rooms.readRoom(f.code);
|
||||
assert.deepEqual(game.richeseAuction, expected.richeseAuction);
|
||||
assert.ok(game.richeseAuction?.acted.includes(f.actor));
|
||||
assert.notEqual(game.richeseAuction?.active, f.actor);
|
||||
assert.equal(game.auctionClock?.remainingMs, 10_000);
|
||||
assert.equal(game.auctionClock?.startedAt, f.clock.now());
|
||||
assert.deepEqual(inventory(game), f.native.originalCards);
|
||||
} finally { f.sqlite.close(); }
|
||||
});
|
||||
|
||||
void test('a timely special bid advances the source and a late bid cannot beat its committed timeout', async () => {
|
||||
for (const timely of [true, false]) {
|
||||
const f = fixture();
|
||||
try {
|
||||
const view = await f.rooms.readSeatView(f.code, f.auth[f.actor], f.clock);
|
||||
f.clock.advance(timely ? 9999 : 10_000);
|
||||
const bid: Action = { type: 'richeseBid', event: f.event, amount: 1, allyPayment: 0 };
|
||||
if (timely) {
|
||||
const result = await f.rooms.act(f.code, f.auth[f.actor], view.version, bid, f.clock);
|
||||
assert.equal(result.richeseAuction?.bid, 1);
|
||||
assert.equal(result.richeseAuction?.bidder, f.actor);
|
||||
assert.notEqual(result.auctionClock?.event, view.auctionClock?.event);
|
||||
assert.equal(result.auctionClock?.remainingMs, 10_000);
|
||||
await assert.rejects(f.rooms.act(f.code, f.auth[f.actor], view.version, bid, f.clock), /table changed/i);
|
||||
} else {
|
||||
await assert.rejects(f.rooms.act(f.code, f.auth[f.actor], view.version, bid, f.clock), /table changed/i);
|
||||
const game = await f.rooms.readRoom(f.code);
|
||||
assert.equal(game.richeseAuction?.bid, 0);
|
||||
assert.ok(game.richeseAuction?.acted.includes(f.actor));
|
||||
assert.notEqual(game.richeseAuction?.active, f.actor);
|
||||
}
|
||||
} finally { f.sqlite.close(); }
|
||||
}
|
||||
});
|
||||
|
||||
void test('a paused room cannot expire a special bid and reopening re-arms its trusted budget', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
await f.rooms.continueRoomAuctionClock(f.code, f.clock);
|
||||
f.clock.advance(4000);
|
||||
f.sqlite.prepare('INSERT INTO room_controls(room_code,paused,join_locked,revision,updated_at) VALUES(?,1,0,1,?)')
|
||||
.run(f.code, f.clock.now());
|
||||
const before = await f.rooms.readRoom(f.code);
|
||||
f.clock.advance(60_000);
|
||||
assert.equal(await f.rooms.continueRoomAuctionClock(f.code, f.clock, true), false);
|
||||
assert.deepEqual(await f.rooms.readRoom(f.code), before);
|
||||
assert.deepEqual(f.clock.sleeps, []);
|
||||
const blocked = await f.rooms.readSeatView(f.code, f.auth[f.actor], f.clock);
|
||||
assert.equal(blocked.auctionClock?.running, false);
|
||||
f.sqlite.prepare('UPDATE room_controls SET paused=0,revision=2,updated_at=? WHERE room_code=?')
|
||||
.run(f.clock.now(), f.code);
|
||||
await f.rooms.continueRoomAuctionClock(f.code, f.clock);
|
||||
let game = await f.rooms.readRoom(f.code);
|
||||
assert.equal(game.auctionClock?.controlEpoch, '2:0');
|
||||
assert.equal(game.auctionClock?.remainingMs, 10_000);
|
||||
assert.equal(game.auctionClock?.startedAt, f.clock.now());
|
||||
f.clock.advance(10_000);
|
||||
await f.rooms.continueRoomAuctionClock(f.code, f.clock);
|
||||
game = await f.rooms.readRoom(f.code);
|
||||
assert.ok(game.richeseAuction?.acted.includes(f.actor));
|
||||
} finally { f.sqlite.close(); }
|
||||
});
|
||||
Reference in new issue
Block a user