Explain blocked combat dice and preselect exact-capacity collection

This commit is contained in:
coyotte508 2026-10-12 23:40:47 +02:00
commit 4190fe7148
11 changed files with 194 additions and 10 deletions

View file

@ -273,3 +273,9 @@ All 737 tests, locale validation, type checks and production build pass. Desktop
# Viewer 0.1.83 / engine 0.4.71
Caesar's Proconsul grants infantry only when its one-gold payment is made. Previously the callback checked the payment list instead of its resource amount, granting an infantry even on decline. The latest D2 capture in a read-only copy of Willful-vertex-9913 confirms that exact sequence; the existing live unit was not removed. Paid/declined regression tests and all 739 tests, locale validation, type checks and production build pass.
# Viewer 0.1.84 / engine unchanged (0.4.71)
Combat dice whose matching unit ability was prevented by High Ground or Mighty Army show a red border and crossed-circle marker in the journal and battle recap. A visible explanation and tooltip name the blocking effect. Matching respects available unit counts and does not flag unrelated or excess faces; historical rolls lacking a recorded roster are not guessed. Combat values and outcomes are unchanged.
Collect preselects one resource choice per eligible tile when the number of distinct tiles exactly equals city capacity, on opening or switching cities. The engine validates the full selection before it appears, and resource choices remain editable. Opening Collect from one of those tiles does not immediately deselect it. Collection is never submitted automatically. Verified blocked-dice desktop/mobile browser checks, selection/payment regression tests, type checks and production build.

View file

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

View file

@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
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, [], {}, 'combat-smoke', {})).players.slice(2);
async function fixture(name) {
const game = JSON.parse(
await readFile(new URL(`../../server/tests/test_games/combat/${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 engine.stripSecret(JSON.stringify(game), 0);
}
const blocked = JSON.parse(await fixture('remove_casualties_attacker.outcome'));
for (const age of blocked.log) for (const round of age.rounds) for (const turn of round.turns) for (const action of turn.actions) for (const item of action.items ?? []) {
if (item.CombatRoll && item.player === 0) {
item.CombatRoll.rolls.forEach(die => die.bonus = false);
item.CombatRoll.combat_modifiers = ['High Ground prevents opponent from using dice-symbol abilities'];
}
}
const pending = JSON.stringify(blocked);
const server = createServer(async (req, res) => {
if (req.url === '/')
return res.end(
'<!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(req.url)) return res.writeHead(404).end();
res.setHeader('Content-Type', req.url.endsWith('.wasm') ? 'application/wasm' : 'text/javascript');
res.end(await readFile(new URL('../dist' + req.url, import.meta.url)));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const [width, height, dark] of [
[1400, 900, false],
[390, 844, true],
[320, 640, false],
]) {
if (process.env.SMOKE_WIDTH && width !== Number(process.env.SMOKE_WIDTH)) continue;
const page = await browser.newPage({ viewport: { width, height } }),
errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto('http://127.0.0.1:' + server.address().port);
await page.evaluate(
({ state, dark }) => {
window.host = clash3d.launch('#app');
host.emit('player', { index: 0 });
host.emit('theme', { dark });
host.emit('preferences', { sound: false });
host.emit('state', state);
},
{ state: pending, dark },
);
await page.getByRole('button', { name: 'Open journal', exact: true }).click();
const table = page.getByRole('table', { name: 'Combat round 1', exact: true });
await table.getByText('Dice-symbol abilities blocked by High Ground', {exact:true}).waitFor();
assert.equal(await table.locator('.ability-blocked').count(), 2);
assert.equal(await table.locator('.ability-blocked.activated').count(), 0);
await page.screenshot({path:`/tmp/clash-combat-blocked-${width}.png`});
assert.deepEqual(errors, []);
console.log(
`${width}px: blocked dice marker and explanation verified.`,
);
await page.close();
}
} finally {
await browser.close();
server.close();
}

View file

@ -1,5 +1,5 @@
<script lang="ts">
import { Swords, Shield, X } from 'lucide-svelte';
import { Swords, Shield, X, CircleSlash } from 'lucide-svelte';
import type { Controller } from './controller';
import CivilizationEmblem from './CivilizationEmblem.svelte';
import UnitIcon from './UnitIcon.svelte';
@ -44,15 +44,17 @@
{#each side.dice as die, i}<span
class="battle-die"
class:activated={!!die.effect}
class:ability-blocked={!!die.blockedBy}
style={`--die-delay:${i * 45}ms`}
title={`${die.value}${die.symbol ? ` · ${die.symbol}` : ''}${die.effect ? ` · ${die.effect}` : ''}`}
title={`${die.value}${die.symbol ? ` · ${die.symbol}` : ''}${die.blockedBy ? ` · Ability blocked by ${die.blockedBy}` : die.effect ? ` · ${die.effect}` : ''}`}
>
<b>{die.value}</b>{#if die.symbol}<UnitIcon
type={die.symbol === 'Leader' ? { Leader: 'Leader' } : die.symbol}
size={12}
/>{/if}
/>{/if}{#if die.blockedBy}<CircleSlash size={10} />{/if}
</span>{:else}<small>No dice</small>{/each}
</div>
{#if side.dice.some(d => d.blockedBy)}<small class="combat-blocked-note">Abilities blocked by {side.diceBlockedBy}</small>{/if}
<div class="battle-hit-count">
<span>{side.value} value</span><strong
>{#if side.cancelledHits}<s title={side.cancelledHits.reasons.join(' · ')}

View file

@ -1,6 +1,6 @@
<script lang="ts">
import { printedCardName } from './card-names';
import { RotateCcw } from 'lucide-svelte';
import { RotateCcw, CircleSlash } from 'lucide-svelte';
import type { CombatDie, CombatRound } from './combat-journal';
import CivilizationEmblem from './CivilizationEmblem.svelte';
import UnitIcon from './UnitIcon.svelte';
@ -18,7 +18,7 @@
} = $props();
const sides = $derived([combat.attacker, combat.defender]);
const dieLabel = (die: CombatDie) =>
`${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : (die.effect ?? 'No ability activated')}` : 'Face not recorded'}`;
`${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : (die.blockedBy ? `Ability blocked by ${die.blockedBy}` : die.effect ?? 'No ability activated')}` : 'Face not recorded'}`;
</script>
<table class="combat-table" aria-label={`Combat round ${combat.round ?? ''}`}>
@ -67,6 +67,7 @@
{#each side.dice ?? [] as die}<span
class="combat-die"
class:activated={!!die.effect}
class:ability-blocked={!!die.blockedBy}
class:rerolled={die.effect === 're-roll'}
role="img"
aria-label={dieLabel(die)}
@ -75,9 +76,10 @@
<b>{die.value}</b>{#if die.symbol}<UnitIcon
type={die.symbol === 'Leader' ? { Leader: 'Leader' } : die.symbol}
size={14}
/>{/if}{#if die.effect === 're-roll'}<RotateCcw size={10} />{/if}
/>{/if}{#if die.blockedBy}<CircleSlash size={10} />{/if}{#if die.effect === 're-roll'}<RotateCcw size={10} />{/if}
</span>{:else}{side.dice ? 'None' : '—'}{/each}
</div>
{#if side.dice?.some(d => d.blockedBy)}<span class="combat-blocked-note">Dice-symbol abilities blocked by {side.diceBlockedBy}</span>{/if}
{#each side.dice?.filter((d) => d.effect && d.effect !== 're-roll') ?? [] as die}
<span class="combat-die-effect"
><UnitIcon type={die.symbol === 'Leader' ? { Leader: 'Leader' } : die.symbol!} size={12} />

View file

@ -275,3 +275,21 @@ test('blocked tactics name the ability, preserving new army counts and legacy ex
assert.equal(JSON.stringify(entries), original);
}
});
for (const source of ['High Ground', 'Mighty Army']) test(`${source} marks only dice with an eligible unused unit`, () => {
const game = fixture('remove_casualties_attacker.outcome');
game.log![0].rounds[0].turns[0].actions = [{ log: [
'Combat round 1',
'Player1: Combat: Attacking with 1 infantry and Caesar',
'Player2: Combat: Defending with 1 infantry',
'Player1: Combat: Roll 6 (infantry, no bonus), 6 (infantry, no bonus), 5 (cavalry, no bonus), 1 (leader, no bonus) for combined combat value of 18 and gets 1 hits against defending units',
`Player1: Combat: Combat modifiers: ${source === 'High Ground' ? 'High Ground prevents opponent from using dice-symbol abilities' : 'Mighty Army: five units, no tactics or dice-symbol abilities'}`,
] }];
game.log_index = 1;
const [combat] = rounds(journal(game));
assert.equal(combat.attacker.diceBlockedBy, source);
assert.deepEqual(combat.attacker.dice?.map(d => d.blockedBy), [source, undefined, undefined, source]);
assert(combat.attacker.dice?.every(d => !d.effect));
assert.equal(combat.attacker.value, 18);
assert.equal(combat.defender.diceBlockedBy, undefined);
});

View file

@ -4,6 +4,7 @@ export interface CombatDie {
value: number;
symbol?: 'Infantry' | 'Cavalry' | 'Elephant' | 'Leader';
effect?: string;
blockedBy?: string;
}
export interface CombatSide {
player?: number;
@ -17,6 +18,7 @@ export interface CombatSide {
tactics?: string;
tacticsEffect?: string;
tacticsBlocked?: string;
diceBlockedBy?: string;
}
export interface CombatRound {
round?: number;
@ -205,6 +207,14 @@ export function combatJournal(entries: JournalEntry[]): JournalEntry[] {
// Only move known roll modifiers into the table; keep other effects below.
const remainder: string[] = [];
for (const clause of clauses) {
if (/High Ground.*prevents.*dice-symbol abilities/i.test(clause)) {
target.diceBlockedBy = 'High Ground';
target.modifiers.push(clause);
continue;
}
if (/Mighty Army:.*no tactics or dice-symbol abilities/i.test(clause)) {
target.diceBlockedBy = 'Mighty Army';
}
const blockedBy = /^Sparta (?:denies playing tactics cards|blocks tactics cards:)/i.test(clause)
? 'Sparta'
: /Trojan Horse.*(?:denied|denies).*Tactics Cards/i.test(clause)
@ -236,6 +246,19 @@ export function combatJournal(entries: JournalEntry[]): JournalEntry[] {
}
for (const entry of output) {
if (!entry.combat) continue;
for (const side of [entry.combat.attacker, entry.combat.defender]) {
if (!side.diceBlockedBy || !side.units) continue;
const remaining = new Map<string, number>();
for (const unit of side.units) {
const type = typeof unit.type === 'object' ? 'Leader' : unit.type;
remaining.set(type, (remaining.get(type) ?? 0) + unit.count);
}
for (const die of side.dice ?? []) {
if (!die.symbol || die.effect || !(remaining.get(die.symbol) ?? 0)) continue;
die.blockedBy = side.diceBlockedBy;
remaining.set(die.symbol, remaining.get(die.symbol)! - 1);
}
}
explainCancelledHits(entry.combat.attacker, entry.combat.defender);
explainCancelledHits(entry.combat.defender, entry.combat.attacker);
}

View file

@ -344,3 +344,15 @@
line-height: 1.45;
color: var(--muted);
}
.combat-die.ability-blocked,
.battle-die.ability-blocked {
border: 2px solid #ce5c48;
box-shadow: 0 0 0 1px #ce5c4840;
}
.combat-blocked-note {
display: block;
margin-top: .3rem;
font-size: .75rem;
color: var(--text);
}

View file

@ -1102,6 +1102,7 @@ test('port resource choices replace one another even after selecting another til
c.setPlayer(0);
await c.load(engine.stripSecret(raw, 0));
c.beginCollect('C2');
for (const choice of [...app.session().selection]) c.toggleChoice(choice);
const city = app.session().view!.cities.find((city) => city.position === 'C2')!;
const gold = city.choices.find((choice) => choice.pile.gold)!;
const mood = city.choices.find((choice) => choice.pile.mood_tokens)!;
@ -2688,3 +2689,29 @@ test('Roads offers food/gold choices before an attack and submits the selected p
assert.doesNotThrow(() => engine.tryMove(JSON.stringify(g), app.sent[0], 1));
} finally { app.close(); }
});
test('Collect preselects all tiles only when their count equals capacity', async () => {
const app = paymentController(), c = app.controller;
try {
const raw = await engine.init(2, [], {}, 'collect-all-tiles', {});
const g = JSON.parse(raw), seat = engine.currentPlayer(raw);
c.setPlayer(seat);
await c.load(engine.stripSecret(raw, seat));
const city = app.session().view!.cities[0];
const positions = [...new Set(city.choices.map(choice => choice.position))];
assert(positions.length > city.capacity);
c.beginCollect(city.position);
assert.equal(app.session().selection.length, 0);
const keep = positions.slice(0, city.capacity);
for (const tile of g.map.tiles) if (positions.includes(tile[0]) && !keep.includes(tile[0])) tile[1] = 'Barren';
await c.load(engine.stripSecret(JSON.stringify(g), seat));
c.beginCollect(city.position);
assert.deepEqual(app.session().selection.map(choice => choice.position).sort(), [...keep].sort());
assert(app.session().preview?.action);
assert.deepEqual(app.sent, []);
c.collectFromTile(city.position, keep[0]);
assert.equal(app.session().selection.length, city.capacity, 'opening from a preselected tile must not deselect it');
c.toggleChoice(app.session().selection[0]);
assert.equal(app.session().selection.length, city.capacity - 1, 'manual deselection remains available');
} finally { app.close(); }
});

View file

@ -1309,7 +1309,7 @@ export class Controller {
}
collectFromTile(city: string, tile: string) {
this.beginCollect(city);
this.selectCollectionTile(tile);
if (!get(this.session).selection.some(choice => choice.position === tile)) this.selectCollectionTile(tile);
}
showTradeRoutes(show = true) {
this.closeActivity();
@ -1404,6 +1404,24 @@ export class Controller {
attackPirates: false,
abilitiesOpen: false,
});
this.preselectCollectionTiles();
}
private preselectCollectionTiles() {
const s = get(this.session);
const city = s.view?.cities.find(city => city.position === s.city);
if (!s.view?.canPlay || s.playback || !city || city.reason || !city.capacity) return;
const tiles = new Map<string, Choice>();
for (const choice of city.choices) if (!tiles.has(choice.position)) tiles.set(choice.position, choice);
if (tiles.size !== city.capacity) return;
const selection = [...tiles.values()].map(choice => ({ ...choice, times: 1 }));
try {
const preview = this.query<NonNullable<Session['preview']>>({
kind: 'collect', city: s.city, selections: selection, variant: s.collectVariant, ballcourts: false,
});
if (preview.action) this.patch({ selection, preview });
} catch {
// Range limits or special effects can make collecting every tile illegal.
}
}
switchCollectVariant(variant: Move) {
const s = get(this.session);
@ -1447,6 +1465,7 @@ export class Controller {
collectionTile: null,
error: '',
});
this.preselectCollectionTiles();
}
openCities(position?: string, cityTab: Session['cityTab'] = 'build') {
if (cityTab === 'happiness') {