Guide cultural influence through destination source and payment

This commit is contained in:
coyotte508 2026-10-13 01:33:29 +02:00
commit 39694d112f
11 changed files with 231 additions and 25 deletions

View file

@ -293,3 +293,5 @@ Verified sea/land routing, reverse travel and Navigation perimeter regressions (
Viewer 0.1.87 / engine 0.4.72 ends a game immediately when dropping leaves only one active human player, clears pending decisions, and ranks withdrawn players below remaining players regardless of points. Full admin replay also repairs existing unfinished saves with only one remaining player; replaying to an earlier move does not prematurely end it. Multiplayer pending-choice/turn-skipping handling remains separate from this last-player victory fix.
Viewer 0.1.88 / engine 0.4.73 restores ship exploration beside any reachable sea space, including the destination sea area after Navigation. Unrevealed tiles remain endpoints, and enemy ships still block traversal. Verified against a local copy of ClashoftheTitans; no live move was submitted.
Viewer 0.1.89 adds Influence to the main action bar. Its map flow chooses a destination and specific building first, preselects the cheapest eligible source, then explicitly presents Arts/Influence Culture and their upfront costs before rolling. A single available method still requires confirmation. Desktop, mobile and Strategy browser checks cover building selection, method changes, and no submission before confirmation. Engine remains 0.4.73.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.88",
"version": "0.1.89",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.88",
"version": "0.1.89",
"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.88",
"version": "0.1.89",
"private": true,
"type": "module",
"scripts": {

View file

@ -0,0 +1,135 @@
// Influence: destination/building, source, then explicit method/payment confirmation.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'map-targets', {})).players.slice(2);
async function fixture(name) {
const game = JSON.parse(
await readFile(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'),
);
for (const npc of npcs)
if (!game.players.some((p) => p.civilization === npc.civilization))
game.players.push({ ...npc, id: game.players.length });
return game;
}
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
const frame = (page) =>
page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function open(width, height, state, strategy = false) {
const page = await browser.newPage({ viewport: { width, height } }),
errors = [],
sent = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.exposeFunction('captureMove', (move) => sent.push(JSON.parse(move)));
await page.route('**/*', async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
});
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({
contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + path, import.meta.url)),
});
});
await page.goto('http://clash.test/');
await page.evaluate(
({ state, strategy }) => {
window.host = clash3d.launch('#app');
host.on('move', (m) => window.captureMove(m));
host.emit('player', { index: 0 });
host.emit('preferences', { sound: false, mapView: strategy ? 'strategy' : '3d' });
host.emit('state', state);
},
{ state: engine.stripSecret(JSON.stringify(state), 0), strategy },
);
return { page, errors, sent };
}
async function center(page, position) {
const target = page.locator(`.map-hit-target[data-position="${position}"]`);
await target.waitFor({ state: 'attached' });
await page.waitForTimeout(250);
await frame(page);
const box = await target.boundingBox();
assert.ok(box, `${position} is highlighted on the board`);
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
}
/** Click around a hex until a click resolves to an exact building model. */
async function clickBuilding(page, position, done) {
const { x, y } = await center(page, position);
for (let r = 0; r <= 40; r += 5)
for (let a = 0; a < 360; a += r ? 30 : 360) {
await page.mouse.click(x + r * Math.cos((a * Math.PI) / 180), y + r * Math.sin((a * Math.PI) / 180));
await frame(page);
if (await done()) return;
}
assert.fail(`no building model at ${position} could be clicked`);
}
try {
for (const [width, height, strategy] of [
[1400, 900, false],
[390, 844, false],
[1400, 900, true],
]) {
const label = `${width}px ${strategy ? 'strategy' : '3D'}`;
// Cultural influence: the ability opens a map mode with highlighted target cities.
const influence = await fixture('base/cultural_influence_instant');
influence.current_player_index = 0;
influence.players[1].cities[0].city_pieces = { temple: 1, academy: 1 };
influence.players[0].cities = [{ position: 'A1', mood_state: 'Happy' }];
influence.players[0].resources.culture_tokens = 7;
if (!strategy) influence.players[0].advances.push('Arts');
const { page, errors, sent } = await open(width, height, influence, strategy);
await page.getByRole('button', { name: 'Cultural influence', exact: true }).click();
const panel = page.getByRole('region', { name: 'Abilities and influence', exact: true });
await panel.locator('.influence-picker').waitFor();
assert.equal(await page.locator('.map-hit-target[data-position="C1"]').count(), 1);
await page.locator('.map-hit-target[data-position="C1"]').press('Enter');
await frame(page);
assert.equal(
await panel.locator('.influence-target-group').count(),
1,
`${label}: C1 opens its buildings`,
);
if (!strategy)
await clickBuilding(page, 'C1', async () => (await panel.locator('.influence-preview').count()) > 0);
else await panel.getByRole('button', { name: /Temple/ }).click();
const route = await panel.locator('.influence-route').innerText();
assert.match(route, /A1/);
assert.match(route, /(Temple|Academy) at C1/);
assert.equal(
await page.locator('.map-hit-target[data-position="A1"]').getAttribute('aria-pressed'),
'true',
);
await page.screenshot({ path: `/tmp/clash-influence-map-${width}-${strategy ? 'strategy' : '3d'}.png` });
assert.deepEqual(sent, []);
assert.equal(await panel.getByRole('button', { name: /Pay & roll|Roll for influence/ }).count(), 0);
await panel.getByRole('button', { name: 'Choose payment' }).click();
const methods = panel.getByLabel('Influence payment method');
await methods.waitFor();
assert.equal(await methods.getByRole('button').count(), strategy ? 1 : 2);
if (!strategy) {
await methods.getByRole('button', { name: /Arts/ }).click();
assert.equal(await methods.getByRole('button', { name: /Arts/ }).getAttribute('aria-pressed'), 'true');
}
await page.screenshot({ path: `/tmp/clash-influence-payment-${width}-${strategy ? 'strategy' : '3d'}.png` });
assert.deepEqual(sent, [], 'source confirmation does not spend or roll');
await panel.getByRole('button', { name: /Pay & roll|Roll for influence/ }).click();
await page.waitForTimeout(100);
assert.ok(sent.length >= 1);
assert.equal(sent[0].Playing.InfluenceCultureAttempt.selected_structure.position, 'C1');
assert.deepEqual(errors, []);
console.log(`${label}: influence target ${route.replace(/\s+/g, ' ')} chosen on the map, then rolled.`);
await page.close();
}
} finally {
await browser.close();
}

View file

@ -148,11 +148,11 @@ try {
influence.players[1].cities[0].city_pieces = { temple: 1, academy: 1 };
influence.players[0].cities = [{ position: 'A1', mood_state: 'Happy' }];
influence.players[0].resources.culture_tokens = 7;
influence.players[0].advances.push('Arts');
({ page, errors, sent } = await open(width, height, influence, strategy));
await page.getByRole('button', { name: 'Abilities and cultural influence', exact: true }).click();
await page.getByRole('button', { name: 'Cultural influence', exact: true }).click();
const panel = page.getByRole('region', { name: 'Abilities and influence', exact: true });
assert.equal(await panel.locator('.influence-targets').count(), 0, 'the menu no longer lists targets');
await panel.getByRole('button', { name: /Choose target/ }).click();
await panel.locator('.influence-picker').waitFor();
assert.equal(await page.locator('.map-hit-target[data-position="C1"]').count(), 1);
await page.locator('.map-hit-target[data-position="C1"]').press('Enter');
@ -174,6 +174,14 @@ try {
);
await page.screenshot({ path: `/tmp/clash-influence-map-${width}-${strategy ? 'strategy' : '3d'}.png` });
assert.deepEqual(sent, []);
assert.equal(await panel.getByRole('button', { name: /Pay & roll|Roll for influence/ }).count(), 0);
await panel.getByRole('button', { name: 'Choose payment' }).click();
const methods = panel.getByLabel('Influence payment method');
await methods.waitFor();
assert.equal(await methods.getByRole('button').count(), 2);
await methods.getByRole('button', { name: /Arts/ }).click();
assert.equal(await methods.getByRole('button', { name: /Arts/ }).getAttribute('aria-pressed'), 'true');
assert.deepEqual(sent, [], 'source confirmation does not spend or roll');
await panel.getByRole('button', { name: /Pay & roll|Roll for influence/ }).click();
await page.waitForTimeout(100);
assert.ok(sent.length >= 1);

View file

@ -1358,13 +1358,21 @@
/>{/if}</button
>
<button
aria-label="Cultural influence"
title="Cultural influence · Choose a destination"
class:active={$session.abilitiesOpen && $session.influenceMode}
disabled={replaying || pending || !view?.canPlay || !view?.influence?.length}
onclick={() => { confirmEnd = false; controller.chooseInfluence(); }}
><Drama size={21} /><span>Influence</span></button>
<button
title={abilitiesAvailable
? 'Abilities and cultural influence'
: 'No abilities or influence targets available'}
data-tutorial="influence"
aria-label="Abilities and cultural influence"
class:active={$session.abilitiesOpen}
class:active={$session.abilitiesOpen && !$session.influenceMode}
class:inspect-only={!abilitiesAvailable}
disabled={!$session.view}
onclick={() => {

View file

@ -11,7 +11,7 @@
TriangleAlert,
} from 'lucide-svelte';
import type { Controller } from './controller';
import { activeInfluence, influenceKey, influenceUpfrontCost, cheaperInfluenceOrigin } from './influence';
import { activeInfluence, influenceKey, influenceUpfrontCost, cheaperInfluenceOrigin, influenceDestinations, influenceDestinationKey } from './influence';
import ResourceAmount from './ResourceAmount.svelte';
let {
controller,
@ -22,6 +22,10 @@
const offers = $derived(influence?.offers ?? []);
const target = $derived(influence?.target ?? null);
const origin = $derived(influence?.origin ?? null);
const methods = $derived(target ? offers.filter(o => influenceDestinationKey(o) === influenceDestinationKey(target) && (!origin || o.origins?.some(from => from.position === origin.position))) : []);
let paymentStep = $state(false);
const selectionKey = $derived(`${target ? influenceDestinationKey(target) : ''}:${origin?.position}`);
$effect(() => { selectionKey; paymentStep = false; });
const cheaper = $derived(cheaperInfluenceOrigin(target, origin));
const attemptKey = $derived(`${target ? influenceKey(target) : ''}:${origin?.position}`);
let confirmedSource = $state<string | null>(null);
@ -61,9 +65,9 @@
</header>
<div class="influence-picker">
<ol class="influence-steps" aria-label="Influence progress">
<li class="current" aria-current="step">Target</li>
<li>Roll</li>
<li>Resolve</li>
{#each ['Destination', 'Source', 'Payment'] as label, i}
<li class:current={i === (!target ? 0 : paymentStep ? 2 : 1)} aria-current={i === (!target ? 0 : paymentStep ? 2 : 1) ? 'step' : undefined}>{label}</li>
{/each}
</ol>
{#if !target}
<p class="movement-hint">Click a highlighted city or building on the map, or choose below.</p>
@ -71,7 +75,7 @@
{#each groups as position}<div class="influence-target-group">
<strong>At {position}</strong>
<div class="decision-options">
{#each offers.filter((o) => o.position === position) as offer}<button
{#each influenceDestinations(offers.filter((o) => o.position === position)) as offer}<button
onmouseenter={() => onHighlight(offer.position)}
onmouseleave={() => onHighlight(null)}
onfocus={() => onHighlight(offer.position)}
@ -79,7 +83,7 @@
onclick={() => {
controller.selectInfluenceTarget(influenceKey(offer));
onHighlight(null);
}}>{offer.name}<small>{offer.variant}</small></button
}}>{offer.name}</button
>{/each}
</div>
</div>{:else}<p class="settler-empty">No eligible targets.</p>{/each}
@ -99,7 +103,7 @@
>{target.name} at <b>{target.position}</b></span
>
</div>
{#if (target.origins?.length ?? 0) > 1}<div class="influence-origins" aria-label="Influence from">
{#if !paymentStep && (target.origins?.length ?? 0) > 0}<div class="influence-origins" aria-label="Influence from">
<span>From</span>{#each target.origins ?? [] as from}<button
class:selected={origin === from}
aria-pressed={origin === from}
@ -118,6 +122,25 @@
{#if from.reroll}<RotateCcw size={14} />{/if}
</button>{/each}
</div>{/if}
{#if !paymentStep}
<p class="movement-hint">Choose the source on the map or above. The lowest-cost source is preselected.</p>
<button class="primary wide" onclick={() => paymentStep = true}>Choose payment<ArrowRight size={16} /></button>
{:else}
<button class="secondary compact" onclick={() => paymentStep = false}>Change source</button>
<div class="decision-options" aria-label="Influence payment method">
{#each methods as method}
{@const from = method.origins?.find(o => o.position === origin?.position)}
<button class:selected={method === target} aria-pressed={method === target} onclick={() => {
const position = origin?.position;
controller.selectInfluenceTarget(influenceKey(method));
if (position) controller.selectInfluenceOrigin(position);
}}>
{method.variant}
<small>{(from?.free ?? method.free) ? 'Free action' : '1 action'}</small>
<ResourceAmount pile={influenceUpfrontCost(from?.actionPayment ?? method.actionPayment, from?.payment ?? method.payment)} compact />
</button>
{/each}
</div>
<div class="influence-cost-line">
<span>Action</span><span
>{#if origin?.free ?? target.free}Free action{:else}<Zap size={14} />1 action{/if}{#if Object.values(actionPayment).some(Boolean)}<ResourceAmount
@ -175,6 +198,7 @@
compact
/>{/if}<ArrowRight size={16} />
</button>
{/if}
</div>
{/if}
</div>

View file

@ -368,11 +368,11 @@
color: var(--muted);
}
.play-layout .board-toolbar {
width: 490px;
width: 540px;
}
.board-toolbar .board-actions {
display: grid;
grid-template-columns: repeat(9, minmax(0, 1fr));
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.board-toolbar .board-actions button {
min-width: 0;
@ -383,11 +383,11 @@
}
@media (max-width: 760px), (max-width: 1000px) and (max-height: 500px) {
.play-layout .board-toolbar {
width: 208px;
width: 236px;
max-width: calc(100% - 150px);
}
.board-toolbar .board-actions {
grid-template-columns: repeat(7, minmax(0, 1fr));
grid-template-columns: repeat(8, minmax(0, 1fr));
padding: 4px;
gap: 0;
}

View file

@ -312,17 +312,17 @@
}
}
.board-toolbar.has-redo .board-actions {
grid-template-columns: repeat(10, minmax(0, 1fr));
grid-template-columns: repeat(11, minmax(0, 1fr));
}
.play-layout .board-toolbar.has-redo {
width: 540px;
width: 590px;
}
@media (max-width: 760px), (max-width: 1000px) and (max-height: 500px) {
.play-layout .board-toolbar.has-redo {
width: 236px;
width: 264px;
}
.board-toolbar.has-redo .board-actions {
grid-template-columns: repeat(8, minmax(0, 1fr));
grid-template-columns: repeat(9, minmax(0, 1fr));
}
.play-layout .live-battle {
top: 100px;

View file

@ -4,6 +4,8 @@ import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import {
activeInfluence,
bestInfluenceOrigin,
influenceDestinations,
cheaperInfluenceOrigin,
influenceKey,
influenceMapPick,
@ -148,3 +150,20 @@ test('influence warns about a cheaper eligible city for the same target', () =>
'equal range costs need no warning',
);
});
test('destination selection defers Arts versus regular influence and defaults to the cheapest source', () => {
const g = influenceFixture();
g.players[0].advances.push('Arts');
g.players[0].cities.push({ position: 'B1', mood_state: 'Happy' });
const v = view(g);
const offers = v.influence!.filter(o => o.name === 'Temple' && o.position === 'C1');
assert(offers.length >= 2);
assert.equal(influenceDestinations(offers).length, 1);
const target = influenceMapPick(offers, 'C1', { kind: 'tile' })!;
assert(target);
assert.equal(bestInfluenceOrigin(target)?.position, 'B1');
const state = { view: v, mode: 'overview', abilitiesOpen: true, influenceMode: true, influenceTarget: influenceKey(target) } as Session;
assert.equal(activeInfluence(state)?.source, 'B1');
assert.equal(activeInfluence({ ...state, influenceOrigin: 'A1' })?.source, 'A1');
});

View file

@ -35,6 +35,16 @@ type Attempt = {
};
export const influenceKey = (offer: InfluenceOffer) => `${offer.position}/${offer.name}/${offer.variant}`;
export const influenceDestinationKey = (offer: InfluenceOffer) => `${offer.position}/${offer.name}`;
export function bestInfluenceOrigin(offer: InfluenceOffer) {
const cost = (o: NonNullable<InfluenceOffer['origins']>[number]) =>
Object.values(influenceUpfrontCost(o.actionPayment, o.payment)).reduce((sum, n) => sum + (n ?? 0), 0);
return [...(offer.origins ?? [])].sort((a, b) => cost(a) - cost(b) || Number(!!b.free) - Number(!!a.free))[0] ?? null;
}
export function influenceDestinations(offers: InfluenceOffer[]) {
return offers.filter((o, i) => offers.findIndex(other => influenceDestinationKey(other) === influenceDestinationKey(o)) === i);
}
/** The board model an offer targets: a structure key or an army unit. */
export function influenceTarget(offer: InfluenceOffer) {
const action = offer.action as { Playing?: { InfluenceCultureAttempt?: Attempt } } | null;
@ -46,7 +56,7 @@ export function influenceTarget(offer: InfluenceOffer) {
/** Resolve a map click to one offer, or null when the hex has several candidates. */
export function influenceMapPick(offers: InfluenceOffer[], position: string, pick: MapPick) {
const here = offers.filter((offer) => offer.position === position);
const here = influenceDestinations(offers.filter((offer) => offer.position === position));
if (pick.kind === 'unit' || pick.structure) {
const exact = here.filter((offer) => {
const target = influenceTarget(offer);
@ -73,8 +83,8 @@ export function activeInfluence(s: Session) {
const offers = s.view.influence;
const target = offers.find((offer) => influenceKey(offer) === s.influenceTarget) ?? null;
const origin =
target?.origins?.find((o) => o.position === (s.influenceOrigin ?? target.origin)) ??
target?.origins?.[0] ??
target?.origins?.find((o) => o.position === s.influenceOrigin) ??
(target ? bestInfluenceOrigin(target) : null) ??
null;
const targets = [...new Set(offers.map((offer) => offer.position))];
const position =