Show cultural influence outcomes and targets in recap

This commit is contained in:
coyotte508 2026-10-18 14:53:42 +02:00
commit 279636dd18
8 changed files with 308 additions and 47 deletions

View file

@ -401,3 +401,5 @@ Viewer 0.1.142 / engine 0.4.99 removes claimed Great People from the Event disca
Viewer 0.1.143 uses printed card names in waiting-status labels, matching event popups (for example Major Earthquake).
Viewer 0.1.144 / engine 0.4.100 adds combat estimates to attack confirmation and selected tactics, Siegecraft and Steel Weapons choices. An isolated worker runs 2,048 battles with the real engine, an independent random stream, public information only, and explicit no-retreat / no-additional-tactics and casualty assumptions. Attack previews compare affordable Siegecraft options and declining Steel Weapons. Unsupported decisions show no estimate. Results are cached, selection changes cancel old workers, and simulations stop before capture rewards.
Viewer 0.1.145 enriches cultural-influence recap captions with success/failure, target civilization and building (or unit), without coordinates. Pending rolls stay pending until the boost response resolves; existing public recordings are supported. No engine or saved-data changes.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.144",
"version": "0.1.145",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.144",
"version": "0.1.145",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.144",
"version": "0.1.145",
"private": true,
"type": "module",
"scripts": {

View file

@ -0,0 +1,90 @@
import type { BoardFrame, LoggedAction } from './types.ts';
export function influenceResult(text: string): 'succeeded' | 'failed' | null {
if (/Cultural influence succeeded|pays to increase the dice roll/.test(text)) return 'succeeded';
if (
/Cultural influence failed|Declined to pay to increase the dice roll|does not have enough resources to increase the roll/.test(
text,
)
)
return 'failed';
return null;
}
/** Use only public actions up to this frame; a later boost must not rewrite the original roll. */
export function influenceRecap(
history: LoggedAction[],
start: number,
before: BoardFrame,
frame: BoardFrame,
) {
const attemptIn = (action: LoggedAction) => {
const entry = action.items?.find((i) => i.InfluenceCultureAttempt);
if (entry?.InfluenceCultureAttempt) return { player: entry.player, ...entry.InfluenceCultureAttempt };
const playing = typeof action.action === 'object' ? action.action?.Playing : undefined;
const attempt =
playing && typeof playing === 'object' && 'InfluenceCultureAttempt' in playing
? (playing.InfluenceCultureAttempt as {
selected_structure: { position: string; structure: unknown };
target_unit?: { player: number; unit: number };
starting_position?: string;
})
: undefined;
return attempt?.selected_structure
? {
player: action.player ?? frame.actor,
...attempt.selected_structure,
starting_city_position: attempt.starting_position,
target_unit: attempt.target_unit,
target_player: attempt.target_unit?.player,
}
: undefined;
};
const attempts = history.map(attemptIn);
const backwards = [...attempts].reverse().findIndex(Boolean);
if (backwards < 0) return null;
const index = attempts.length - 1 - backwards;
const attempt = attempts[index]!;
const current = history.slice(Math.max(start, index));
const messages = current.flatMap((a) => [
...(a.items ?? []).flatMap((i) => (i.Text ? [i.Text] : [])),
...(a.log ?? []),
]);
const success = messages.some((t) => influenceResult(t) === 'succeeded');
const failure = messages.some((t) => influenceResult(t) === 'failed');
const pending = messages.some((t) => /now has the option to pay .*increase the dice roll/.test(t));
if (!success && !failure && !pending && index < start) return null;
const cityOwner = before.players.find((p) => p.cities?.some((c) => c.position === attempt.position));
const city = cityOwner?.cities?.find((c) => c.position === attempt.position);
const structure = attempt.structure;
const building =
structure &&
typeof structure === 'object' &&
'Building' in structure &&
typeof structure.Building === 'string'
? structure.Building
: undefined;
const unit = attempt.target_unit;
const unitType =
unit &&
before.players.find((p) => p.id === unit.player)?.units?.find((u) => u.id === unit.unit)?.unit_type;
const name = unit
? typeof unitType === 'string'
? unitType
: 'army unit'
: (building ?? (structure === 'CityCenter' ? 'Settlement' : 'building'));
const owner =
unit?.player ??
(building
? city?.city_pieces?.[
building.toLowerCase() as keyof NonNullable<NonNullable<typeof city>['city_pieces']>
]
: cityOwner?.id) ??
attempt.target_player;
const target = before.players.find((p) => p.id === owner)?.civilization;
return {
actor: before.players.find((p) => p.id === attempt.player)?.civilization,
description: `Cultural influence${success ? ' succeeded' : failure ? ' failed' : ''} against ${target ? `${target}’s ` : ''}${name}${!success && !failure ? (pending ? ' · Awaiting boost' : ' · Awaiting result') : ''}`,
positions: [attempt.position, attempt.starting_city_position].filter((p): p is string => !!p),
};
}

View file

@ -1,3 +1,4 @@
import { frameHasContent } from './replay-actions.ts';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { recapStart, sinceLastTurn, frameAt, frameEffects, frameDetails } from './playback.ts';
@ -455,30 +456,141 @@ test('choice recaps use public decisions and happiness outcomes', () => {
});
test('recap names a publicly played action card, never a drawn card', () => {
const before = { cursor: 0, actor: 0, title: 'End turn', tiles: [], players: [{id:0,civilization:'Greece',units:[],cities:[]}] } as unknown as BoardFrame;
const after = {...before,cursor:1,title:'Play action card'};
const action = {player:0,action:{Playing:{ActionCard:2}},items:[]} as LoggedAction;
const history = {log_index:1,log:[{age:1,rounds:[{round:1,turns:[{actions:[action]}]}]}]} as Game;
const catalog = [{id:2,name:'Great Ideas',description:'Gain ideas.',free:true,tactics:null}];
assert.equal(frameDetails(before,after,history,[],catalog).caption,'Greece · Played Good Ideas');
action.action = {Response:{Bool:true}};
action.items = [{player:0,HandCard:{card:{ActionCard:2},to:{Hand:0}}}];
assert.ok(!frameDetails(before,after,history,[],catalog).caption.includes('Good Ideas'));
const before = {
cursor: 0,
actor: 0,
title: 'End turn',
tiles: [],
players: [{ id: 0, civilization: 'Greece', units: [], cities: [] }],
} as unknown as BoardFrame;
const after = { ...before, cursor: 1, title: 'Play action card' };
const action = { player: 0, action: { Playing: { ActionCard: 2 } }, items: [] } as LoggedAction;
const history = {
log_index: 1,
log: [{ age: 1, rounds: [{ round: 1, turns: [{ actions: [action] }] }] }],
} as Game;
const catalog = [{ id: 2, name: 'Great Ideas', description: 'Gain ideas.', free: true, tactics: null }];
assert.equal(frameDetails(before, after, history, [], catalog).caption, 'Greece · Played Good Ideas');
action.action = { Response: { Bool: true } };
action.items = [{ player: 0, HandCard: { card: { ActionCard: 2 }, to: { Hand: 0 } } }];
assert.ok(!frameDetails(before, after, history, [], catalog).caption.includes('Good Ideas'));
});
test('objective completion recaps name the completed side, without repeating its effect', () => {
const { before, after, game } = choiceRecap([
{ player: 0, HandCard: { card: { ObjectiveCard: 1 }, to: { CompleteObjective: 'Bold' } } },
], [{ player: 0, kind: 'completed', label: 'Bold' }]);
const { before, after, game } = choiceRecap(
[{ player: 0, HandCard: { card: { ObjectiveCard: 1 }, to: { CompleteObjective: 'Bold' } } }],
[{ player: 0, kind: 'completed', label: 'Bold' }],
);
before.players[0].civilization = 'Maya';
for (const title of ['Select Objective Cards to Complete', 'Complete Objectives', 'Resolve choice']) {
after.title = title;
assert.equal(frameDetails(before, after, game).caption, 'Maya · Completed Daring');
}
// A second public completion in the same frame is retained.
game.log![0].rounds[0].turns[0].actions![0].items!.push(
{ player: 0, HandCard: { to: { CompleteObjective: 'Conqueror' } } },
);
game.log![0].rounds[0].turns[0].actions![0].items!.push({
player: 0,
HandCard: { to: { CompleteObjective: 'Conqueror' } },
});
assert.equal(frameDetails(before, after, game).caption, 'Maya · Completed Daring, Conqueror');
});
function influenceFrames(messages: string[][]) {
const before: BoardFrame = {
cursor: 0,
actor: 0,
ended_turn: false,
title: 'Earlier position',
age: 1,
round: 1,
tiles: [],
players: [
{ id: 0, civilization: 'Greece', cities: [] },
{ id: 1, civilization: 'Rome', cities: [] },
{
id: 2,
civilization: 'Babylonia',
cities: [{ position: 'C2', mood_state: 'Happy', city_pieces: { fortress: 1 } }],
},
],
};
const actions: LoggedAction[] = messages.map((lines) => ({
player: 0,
action: { Response: { Payment: [] } },
items: lines.map((Text) => ({ player: 0, Text })),
}));
actions[0].items!.unshift({
player: 0,
InfluenceCultureAttempt: {
position: 'C2',
starting_city_position: 'B1',
structure: { Building: 'Fortress' },
target_player: 2,
},
});
const game = {
log_index: actions.length,
log: [{ age: 1, rounds: [{ round: 1, turns: [{ actions }] }] }],
} as Game;
const after = { ...structuredClone(before), cursor: 1, title: 'Cultural influence' };
after.players[2].cities![0].city_pieces!.fortress = 0;
return { before, after, game };
}
test('influence recap names the building owner and result, not the coordinates or current owner', () => {
for (const result of ['succeeded', 'failed']) {
const { before, after, game } = influenceFrames([['Cultural influence ' + result + ' (rolls 5)']]);
const details = frameDetails(before, after, game);
assert.equal(details.caption, `Greece · Cultural influence ${result} against Rome’s Fortress`);
assert.deepEqual(new Set(details.positions), new Set(['C2', 'B1']));
assert.doesNotMatch(details.caption, /C2|B1|Babylonia/);
}
});
test('influence recap waits for the boost decision and resolves later payment frames', () => {
for (const [message, result] of [
['pays to increase the dice roll', 'succeeded'],
['Declined to pay to increase the dice roll', 'failed'],
]) {
const { before, after, game } = influenceFrames([
[
'rolls a 2 and now has the option to pay 3 culture tokens to increase the dice roll and proceed with the cultural influence',
],
[message],
]);
const waiting = { ...before, cursor: 1, title: 'Cultural influence' };
assert.equal(
frameDetails(before, waiting, game).caption,
'Greece · Cultural influence against Rome’s Fortress · Awaiting boost',
);
after.cursor = 2;
after.title = 'Resolve choice';
assert.equal(
frameDetails(waiting, after, game).caption,
`Greece · Cultural influence ${result} against Rome’s Fortress`,
);
}
});
test('influence recap describes insufficient boost resources as failure and ignores unrelated later choices', () => {
const { before, after, game } = influenceFrames([
['rolls a 2 and does not have enough resources to increase the roll'],
['Decided to keep the current government'],
]);
assert.equal(
frameDetails(before, after, game).caption,
'Greece · Cultural influence failed against Rome’s Fortress',
);
const next = { ...after, cursor: 2, title: 'Resolve choice' };
assert.doesNotMatch(frameDetails(after, next, game).caption, /Cultural influence/);
});
test('recap keeps a declined influence boost even when the board does not change', () => {
const { before, game } = influenceFrames([
['rolls a 2 and now has the option to pay 3 culture tokens to increase the dice roll'],
['Declined to pay to increase the dice roll'],
]);
const pending = { ...before, cursor: 1, title: 'Cultural influence' };
const failed = { ...before, cursor: 2, title: 'Resolve choice' };
assert.equal(frameHasContent(game, pending, failed), true);
assert.match(frameDetails(pending, failed, game).caption, /failed against Rome’s Fortress/);
});

View file

@ -1,6 +1,7 @@
import type { BoardFrame, Game, View, Pile } from './types.ts';
import { frameResources, describeResources } from './resource-playback.ts';
import { frameHasContent } from './replay-actions.ts';
import { influenceRecap } from './influence-recap.ts';
import { activeHistory } from './active-history.ts';
import { officialWonderText, wonderName } from './wonder-names.ts';
import { printedCardName, printedCardText } from './card-names.ts';
@ -78,7 +79,7 @@ export function frameDetails(
cards: NonNullable<View['cardCatalog']> = [],
) {
if (!frame) return { caption: 'No recorded positions yet.', positions: [] as string[] };
const actor = frame.players.find((p) => p.id === frame.actor)?.civilization;
let actor = frame.players.find((p) => p.id === frame.actor)?.civilization;
const positions = new Set<string>();
const units = (f: BoardFrame | undefined) =>
new Map(
@ -119,9 +120,13 @@ export function frameDetails(
let description = ['Explore Resolution', 'Finish ship exploration'].includes(frame.title)
? 'Explore'
: frame.title;
const generic = ['Resolve choice', 'Pay for action', 'Action', 'Select Objective Cards to Complete', 'Complete Objectives'].includes(
frame.title,
);
let generic = [
'Resolve choice',
'Pay for action',
'Action',
'Select Objective Cards to Complete',
'Complete Objectives',
].includes(frame.title);
const outcomes: string[] = [];
if (before && generic) {
for (const player of frame.players) {
@ -163,20 +168,34 @@ export function frameDetails(
// Read only the public log interval for this frame, never the current player's hand
// or later turns. This also enriches recordings made before detailed captions existed.
if (before && game) {
const actions = activeHistory(game)
const history = activeHistory(game)
.flatMap((age) => age.rounds.flatMap((round) => round.turns.flatMap((turn) => turn.actions ?? [])))
.slice(before.cursor, frame.cursor);
.slice(0, frame.cursor);
const actions = history.slice(before.cursor);
const influence = influenceRecap(history, before.cursor, before, frame);
if (influence) {
description = influence.description;
actor = influence.actor ?? actor;
generic = false;
influence.positions.forEach((position) => positions.add(position));
}
const items = actions.flatMap((action) => action.items ?? []);
if (frame.title === 'Play action card') {
const played = actions.flatMap(action => {
if (frame.title === 'Play action card' && !influence) {
const played = actions.flatMap((action) => {
const playing = typeof action.action === 'object' && action.action?.Playing;
return playing && typeof playing === 'object' && 'ActionCard' in playing && typeof playing.ActionCard === 'number'
? [playing.ActionCard] : [];
return playing &&
typeof playing === 'object' &&
'ActionCard' in playing &&
typeof playing.ActionCard === 'number'
? [playing.ActionCard]
: [];
});
const names = [...new Set(played.map(id => cards.find(card => card.id === id)?.name).filter(Boolean))];
const names = [
...new Set(played.map((id) => cards.find((card) => card.id === id)?.name).filter(Boolean)),
];
if (names.length) description = `Played ${names.join(' · ')}`;
}
if (frame.title === 'Civilization ability') {
if (frame.title === 'Civilization ability' && !influence) {
// Older frames kept a generic title. The public start entry already names
// the advance or leader ability, including free actions with no cost item.
for (const action of actions) {
@ -204,17 +223,27 @@ export function frameDetails(
}
}
}
const details: string[] = [...outcomes];
const details: string[] = influence ? [] : [...outcomes];
const readable = wonderName;
for (const player of frame.players) {
const own = items.filter((item) => item.player === player.id);
const completed = [...new Set(own.flatMap((item) => {
const to = item.HandCard?.to;
return to && typeof to === 'object' && 'CompleteObjective' in to && typeof to.CompleteObjective === 'string'
? [to.CompleteObjective] : [];
}))];
const completed = [
...new Set(
own.flatMap((item) => {
const to = item.HandCard?.to;
return to &&
typeof to === 'object' &&
'CompleteObjective' in to &&
typeof to.CompleteObjective === 'string'
? [to.CompleteObjective]
: [];
}),
),
];
if (completed.length)
details.push(`${player.id === frame.actor ? '' : player.civilization + ': '}Completed ${completed.join(', ')}`);
details.push(
`${player.id === frame.actor ? '' : player.civilization + ': '}Completed ${completed.join(', ')}`,
);
const gained = [
...new Set(
own.filter((item) => item.Advance?.balance === 'Gain').map((item) => item.Advance!.advance),
@ -259,11 +288,20 @@ export function frameDetails(
}
// Public effect labels identify card types without exposing private cards.
for (const effect of frame.effects ?? []) {
if (effect.kind === 'completed' && items.some(item => {
const to = item.HandCard?.to;
return item.player === effect.player && to && typeof to === 'object' &&
'CompleteObjective' in to && to.CompleteObjective === effect.label;
})) continue;
if (
effect.kind === 'completed' &&
items.some((item) => {
const to = item.HandCard?.to;
return (
item.player === effect.player &&
to &&
typeof to === 'object' &&
'CompleteObjective' in to &&
to.CompleteObjective === effect.label
);
})
)
continue;
const player = frame.players.find((p) => p.id === effect.player);
const label = `${effect.player === frame.actor ? '' : (player?.civilization ?? 'Player') + ': '}${effect.label}`;
if (!details.includes(label)) details.push(label);

View file

@ -1,3 +1,4 @@
import { influenceResult } from './influence-recap.ts';
import { activeHistory } from './active-history.ts';
import type { BoardFrame, Game, LoggedAction } from './types.ts';
@ -43,7 +44,15 @@ export function frameHasContent(game: Game, before: BoardFrame | undefined, fram
)
)
return true;
if (actions.some((action) => action.combat_stats)) return true;
if (
actions.some(
(action) =>
action.combat_stats ||
action.items?.some((item) => influenceResult(item.Text ?? '') !== null) ||
action.log?.some((line) => influenceResult(line) !== null),
)
)
return true;
if (frame.ended_turn || frame.title === 'End turn') return false;
if (
before &&

View file

@ -123,7 +123,13 @@ export interface LoggedAction {
hits: number;
combat_modifiers?: string[];
};
InfluenceCultureAttempt?: { position: string; starting_city_position: string; structure: unknown };
InfluenceCultureAttempt?: {
position: string;
starting_city_position: string;
structure: unknown;
target_player?: number;
target_unit?: { player: number; unit: number };
};
Action?: { balance: string; amount?: number };
Structure?: { structure: unknown; balance: string; position: string };
HandCard?: { card?: unknown; from?: unknown; to: unknown };
@ -330,7 +336,11 @@ export interface View {
units?: UnitView[];
movementLeft?: number;
nomadCities?: string[];
tradeRoutes?: { player: number; enabled: boolean; routes: { from: string; to: string; unit: number | null }[] }[];
tradeRoutes?: {
player: number;
enabled: boolean;
routes: { from: string; to: string; unit: number | null }[];
}[];
regions?: { id: number; homePlayer: number | null; tiles: string[] }[];
seaRoutes?: string[][];
barbarianGuide?: {
@ -531,7 +541,7 @@ export interface EventInfo {
}
export interface Session {
eventNotices?: import('./event-notices').EventNotice[];
portPlacement?: {city: string; payment: Pile; choices: {position: string; action: Move}[]};
portPlacement?: { city: string; payment: Pile; choices: { position: string; action: Move }[] };
landingTargets?: string[];
disembarkCarriers?: number[];
analysis?: boolean;