Show public Raiders trade warnings and keep spectator map controls visible; prepare viewer 0.1.237 and engine 0.4.168

This commit is contained in:
coyotte508 2026-11-22 22:04:31 +00:00
commit 4e2471b08c
41 changed files with 526 additions and 34 deletions

View file

@ -30,6 +30,8 @@ jobs:
working-directory: web-client
- run: node scripts/horse-master-smoke.mjs && node scripts/carthage-recruit-smoke.mjs && node scripts/payment-defaults-smoke.mjs && node scripts/wonder-payment-perf.mjs
working-directory: web-client
- run: node scripts/map-guide-smoke.mjs && node scripts/trade-routes-smoke.mjs && node scripts/raiders-smoke.mjs
working-directory: web-client
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: clash-viewer

View file

@ -208,7 +208,13 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
} else {
vec![]
};
json!({"player":p.index,"enabled":enabled,"routes":routes})
// Use the rules predicate on expanded engine units, including passengers.
// This is public board information, independent of whose turn it is.
let raided_settlers = p.units.iter()
.filter(|unit| crate::content::civilizations::huns::raided_settler(game, unit))
.map(|unit| json!({"position":unit.position,"unit":unit.id}))
.collect::<Vec<_>>();
json!({"player":p.index,"enabled":enabled,"routes":routes,"raidedSettlers":raided_settlers})
})
.collect::<Vec<_>>();
let pirate_spawns = game

View file

@ -0,0 +1,85 @@
# Raiders in the Trade Routes guide
The Trade Routes guide uses optional `raidedSettlers` metadata from the engine's
existing `huns::raided_settler` predicate. Engine units are expanded, so carried
Settlers are included. This public board information is calculated for every
selectable civilization, including off-turn inspection. Saved game data and rules
are unchanged; older views without the field remain supported.
Affected source hexes have one solid orange contour. The trade guide shows only a
Settler icon and “Settlers blocked by Huns’ Raiders”; clicking a hex keeps that same
short warning in the normal tile panel. There is no warning paragraph, unit-ID list,
or eligible-pairings heading/count. Valid coordinate route rows remain.
The orange contour previously floated at a fixed world Y of 0.67 with depth testing
disabled, so it appeared above the water slab (Y 0.01) and over unit silhouettes.
It now uses the same slab-surface calculation as the board, with a 0.04 centerline
offset and a 0.025 tube radius, inset inside the hex perimeter. Depth testing lets
pieces and terrain occlude it. Gold endpoint contours use the same slab-relative
height; route arcs are unchanged. Strategy uses the same ground geometry underneath
its DOM/SVG unit markers, not an elevated warning layer. All valid gold route lines remain visible,
including the Ship's route from a hex shared with affected Settlers. Only the gold
endpoint contour is replaced with orange. Engine pairing and income are unchanged;
protection restores the normal gold endpoint. Selection contours do not stack on
the orange contour.
## Local verification
From `web-client`:
```sh
npm run build:bridge
npm run build
node --test scripts/raiders.test.mjs
node --experimental-strip-types --test src/trade-overlay.test.ts
node scripts/raiders-smoke.mjs
node scripts/raiders-preview.mjs
```
The final command serves the normal built viewer at `http://localhost:8645/`.
It now defaults to a **real spectator**: the host emits no player index and uses
`stripSecret(raw, undefined)`, not Greece's participant-filtered state. Use
`http://localhost:8645/?seat=spectator` explicitly, or `?seat=1` to compare the
original off-turn Greek participant. There is no simulated seat or game mutation.
Open **Show trade routes** (the route icon in the bottom map toolbar), then choose
**Greece** in its **Civilization** selector. The initial inspection follows the
active civilization, Huns; selecting Greece changes only the overlay, never the
seat, turn owner, camera home, or secret filtering. Explicit trade inspection is
retained when reopening the guide. The synthetic board has Greek Ship #8 and passenger
Settlers #6/#7 at D7, a Huns army at D9, and two Happy trade destinations. The
engine assigns only the Ship a route; the tests also verify its route to D9 when
the other destination is Angry. The fixture is derived from a checked-in rules
test, not a live game or private history. The preview records attempted moves in
memory but never executes or saves them.
The smoke test exercises genuine spectator and off-turn participant hosts,
physical 3D/Strategy tile clicks, keyboard/touch, civilization switching, dark/light, and 3D/Strategy at
1400×900, 1047×827 (the reported screenshot size), and 390×740. It checks the map
controls are enabled and inside the viewport, private hand buttons are absent for
spectators, and no moves are submitted. Screenshots are written to
`/tmp/clash-raiders-{spectator,player}-{1400,1047,390}-{3d,strategy}-{dark,light}.png`.
## Spectator controls audit
Regions and its civilization selector, sea routes, Trade Routes (including
Raiders), pirate/barbarian guides and their incident-player selectors, zoom,
Strategy and its key, and fullscreen (when the host supports it) were already
available without a seat. Pirate blockade marks are automatic; tile inspection
already exposes public terrain, coordinates, city buildings, and units. There
are no separate terrain-label, coordinate, city-range, or unit-model toggles in
the existing in-viewer toolbar to unlock. Account-host preferences are not game
actions and are not being replaced with a spectator seat.
The three-shapes button is **Color-blind mode**, not a menu or collapsed table
controls. The map toolbar is a separate row beneath Journal/Chat/Sound. In the IDE's
embedded browser, the map's percentage height could resolve to the full viewport
instead of the remaining flex height below the header. This put the toolbar below
the screen; focusing a guide scrolled player cards under the header. The map now
fills its positioned board container with explicit insets, verified in the actual
IDE browser as well as the Chromium smoke tests. No global
"always expanded" preference was added. Spectators now omit the participant action
button row rather than displaying disabled actions (or an empty Abilities menu);
public civilization inspection remains available by clicking each player card.
Private hands, own-city management, queues, payment, and participant settings
remain unavailable. No authorization or engine legality checks were changed.

View file

@ -1787,3 +1787,15 @@ can recommend 2 culture + 1 mood; no extra token-conservation policy is introduc
See `docs/mercenaries-payment-recommendation.md`. Publish matching viewer and engine
only after both exact-commit Check and Web viewer workflows succeed. No saved-game
migration, backfill, or live-game writes are required. Catalog and art are unchanged.
# Viewer 0.1.237 / engine 0.4.168 — Raiders and spectator map controls
Public per-civilization `raidedSettlers` view metadata reuses the existing Huns
predicate, including passengers; no rules, save schema, replay or private hands
change. The trade guide and tile inspection show one concise Settler-icon line,
with grounded orange contours and valid Ship route lines preserved. Spectators
retain public civilization inspection and an on-screen map toolbar without a
participant action row or seat mutation. All 17 locales include the label.
See [Raiders verification](raiders-trade-guide.md). Publish the matching viewer and
engine together; achievement catalog 8 (46 entries), art 4, all 60 named assets,
gallery, Standard variant and existing settings/preferences/options remain intact.

View file

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

View file

@ -1,13 +1,13 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.236",
"version": "0.1.237",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 8643",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs",
"test:boarding": "npm run build:bridge && npm run build && node --test scripts/boarding.test.mjs && node scripts/boarding-smoke.mjs",
"test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs",
"build:achievement-assets": "node scripts/build-achievement-assets.mjs",

View file

@ -13,7 +13,7 @@
"web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0",
"web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b",
"server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332",
"web-client/package-lock.json": "fc9a2cf3b38935a23842fc66c3e29f17700436258ed9a7e6bfbfa3b837ddfa31",
"web-client/package-lock.json": "2c2de2c40d022c6eef85578ee7949cc0dc0de9f5fc64f860d1b7581dcb1796fc",
"web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be",
"web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a",
"web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db"

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-server",
"version": "0.4.167",
"version": "0.4.168",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -0,0 +1,26 @@
import { readFileSync } from 'node:fs';
/** Synthetic public board built from a checked-in rules fixture, never a live game. */
export async function raidersFixture(engine) {
const game = JSON.parse(readFileSync(new URL('../../server/tests/test_games/advances/trade_routes.json', import.meta.url), 'utf8'));
const npcs = JSON.parse(await engine.init(2, [], {}, 'raiders-guide', {})).players.slice(2);
for (const npc of npcs) if (!game.players.some(p => p.civilization === npc.civilization)) game.players.push({ ...npc, id: game.players.length });
game.current_player_index = 0; // Inspect Greece off-turn.
game.players[0].civilization = 'Huns';
game.players[0].advances.push('Tactics');
game.players[0].special_advances = ['Raiders'];
game.players[0].units = [{ position: 'D9', unit_type: 'Infantry', id: 18 }];
game.players[0].cities = [
{ position: 'D9', mood_state: 'Happy' },
{ position: 'B7', mood_state: 'Happy' },
];
game.players[0].next_unit_id = 19;
game.players[1].units = [{ position: 'D7', unit_type: 'Ship', id: 8, carried_units: [
{ unit_type: 'Settler', id: 6 }, { unit_type: 'Settler', id: 7 },
] }];
game.players[1].next_unit_id = 9;
const tiles = new Map(game.map.tiles);
for (const [position, terrain] of [['D7', 'Water'], ['D8', 'Fertile'], ['D9', 'Fertile'], ['B7', 'Fertile'], ['C7', 'Fertile']]) tiles.set(position, terrain);
game.map.tiles = [...tiles];
return game;
}

View file

@ -0,0 +1,38 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
import { raidersFixture } from './raiders-fixture.mjs';
export async function startPreview(port = 8645) {
const engine = createRequire(import.meta.url)('../.engine/server.js');
const raw = JSON.stringify(await raidersFixture(engine));
// Never use a participant's secret-filtered state for the spectator preview.
const publicState = engine.stripSecret(raw, undefined);
const playerState = engine.stripSecret(raw, 1);
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const path = url.pathname;
if (path === '/') {
const spectator = url.searchParams.get('seat') !== '1';
const state = spectator ? publicState : playerState;
res.setHeader('Content-Type', 'text/html');
return res.end(`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Clash · synthetic Raiders preview</title><div id="app"></div><script src="/viewer.js"></script><script>
window.host=clash3d.launch('#app');window.sent=[];window.prefs={sound:false};
host.on('move',a=>sent.push(a));
host.on('update:preference',({name,value})=>{prefs[name]=value;host.emit('preferences',prefs)});
host.emit('player',${spectator ? '{}' : '{index:1}'});host.emit('theme',{dark:true});host.emit('preferences',prefs);
host.emit('state',${JSON.stringify(state)});
</script>`);
}
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) { res.statusCode = 404; return res.end(); }
res.setHeader('Content-Type', path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript');
res.end(await readFile(new URL('../dist' + path, import.meta.url)));
});
await new Promise(resolve => server.listen(port, '127.0.0.1', resolve));
return server;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await startPreview();
console.log('Synthetic Raiders preview: http://localhost:8645/ (normal viewer, no saved moves)');
}

View file

@ -0,0 +1,109 @@
import assert from 'node:assert/strict';
import { chromium } from 'playwright';
import { startPreview } from './raiders-preview.mjs';
const server = await startPreview(0);
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const spectator of [true, false]) for (const width of [1400, 1047, 390]) {
const height = width === 390 ? 740 : width === 1047 ? 827 : 900;
const page = await browser.newPage({ viewport: { width, height }, hasTouch: width === 390 });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}/?seat=${spectator ? 'spectator' : '1'}`);
await page.locator('.player-card').first().waitFor();
if (spectator) {
await page.locator('.game-shell.spectating').waitFor();
assert.equal(await page.locator('.board-actions').count(), 0);
assert.equal(await page.locator('.cards-button, .wonders-button, .objectives-button').count(), 0);
assert.doesNotMatch(await page.locator('.player-list').textContent(), /You/);
}
for (const name of ['Show regions', 'Show all sea routes', 'Show trade routes', 'Show pirate spawn positions', 'Show barbarian spawn and movement', 'Strategy map', 'Zoom in', 'Zoom out']) {
const button = page.getByRole('button', { name, exact: true });
assert(await button.isVisible(), `${name} is visible`);
assert(await button.isEnabled(), `${name} is enabled`);
const box = await button.boundingBox();
assert(box.x >= 0 && box.y >= 0 && box.x + box.width <= width + 1 && box.y + box.height <= height + 1, `${name} fits viewport`);
}
await page.getByRole('button', { name: 'Show regions', exact: true }).click();
await page.getByRole('combobox', { name: 'Region player' }).selectOption('1');
await page.getByRole('button', { name: 'Show regions', exact: true }).click();
for (const name of ['Show all sea routes', 'Show pirate spawn positions', 'Show barbarian spawn and movement', 'Zoom in', 'Zoom out']) {
await page.getByRole('button', { name, exact: true }).click();
}
const toggle = page.getByRole('button', { name: 'Show trade routes', exact: true });
if (width === 390) await toggle.tap();
else { await toggle.focus(); await page.keyboard.press('Enter'); }
await page.getByRole('combobox', { name: 'Trade route player' }).selectOption('1');
const warning = page.locator('.raided-settlers-note');
const guideWarning = page.locator('.raided-settlers-guide');
assert.equal(await guideWarning.textContent(), 'Settlers blocked by Huns’ Raiders');
assert.equal(await guideWarning.locator('svg').count(), 1);
assert((await guideWarning.boundingBox()).height < 24, 'warning stays one compact line');
assert.equal(await guideWarning.evaluate(node => getComputedStyle(node).borderLeftWidth), '0px');
assert.equal(await page.locator('.collapsible-map-guide .coordinate-link').count(), 2, 'valid ship pairing remains');
assert.doesNotMatch(await page.locator('.collapsible-map-guide').textContent(), /Current eligible pairings|unit #|warning only|does not change/i);
assert.equal(await warning.count(), 0, 'no warning before tile inspection');
// Use the normal coordinate link to locate the source, then physically hit
// its rendered 3D hex (no event interception or controller test hooks).
await page.locator('.collapsible-map-guide .coordinate-link').filter({ hasText: /^D7$/ }).click();
await page.locator('.collapsible-map-guide summary').click();
await page.waitForTimeout(300);
const reference = await page.getByRole('status', { name: 'Map location D7' }).boundingBox();
assert(reference, 'D7 has a visible projected map reference');
const point = { x: reference.x + reference.width / 2, y: reference.y - 8 };
if (width === 390) await page.touchscreen.tap(point.x, point.y);
else await page.mouse.click(point.x, point.y);
await warning.waitFor();
assert.equal(await warning.textContent(), 'Settlers blocked by Huns’ Raiders');
await page.getByRole('button', { name: spectator ? 'Close tile details' : 'Close tile actions', exact: true }).click();
for (const strategy of [false, true]) {
if (strategy) await page.getByRole('button', { name: 'Strategy map', exact: true }).click();
if (strategy) {
// Strategy changes camera orientation; re-center through the real guide
// before tapping a tile so the collapsed guide cannot cover the target.
await page.locator('.collapsible-map-guide summary').click();
await page.locator('.collapsible-map-guide .coordinate-link').filter({ hasText: /^D7$/ }).click();
await page.locator('.collapsible-map-guide summary').click();
const tile = page.locator('.strategy-map-tile[data-position="D7"]');
if (width === 390) await tile.tap(); else await tile.click();
await warning.waitFor();
assert.equal(await warning.textContent(), 'Settlers blocked by Huns’ Raiders');
await page.getByRole('button', { name: spectator ? 'Close tile details' : 'Close tile actions', exact: true }).click();
await tile.focus();
await page.keyboard.press('Enter');
await warning.waitFor();
assert.match(await warning.textContent(), /Settlers blocked by Huns’ Raiders/);
await page.screenshot({ path: `/tmp/clash-raiders-click-${spectator}-${width}-${strategy}.png` });
await page.getByRole('button', { name: spectator ? 'Close tile details' : 'Close tile actions', exact: true }).click();
assert.equal(await warning.count(), 0);
}
for (const dark of [true, false]) {
await page.evaluate(dark => host.emit('theme', { dark }), dark);
await page.waitForTimeout(700);
await page.screenshot({ path: `/tmp/clash-raiders-${spectator ? 'spectator' : 'player'}-${width}-${strategy ? 'strategy' : '3d'}-${dark ? 'dark' : 'light'}.png` });
}
}
await page.locator('.collapsible-map-guide summary').click();
await page.getByRole('combobox', { name: 'Trade route player' }).selectOption('0');
assert.equal(await warning.count(), 0);
assert.equal(await guideWarning.count(), 0);
await page.getByRole('combobox', { name: 'Trade route player' }).selectOption('1');
assert.equal(await warning.count(), 0);
assert.equal(await guideWarning.textContent(), 'Settlers blocked by Huns’ Raiders');
const layout = await page.evaluate(() => {
const board = document.querySelector('.play-layout');
const map = document.querySelector('.map-section');
const firstPlayer = document.querySelector('.player-card');
return { scroll: board.scrollTop, board: board.getBoundingClientRect().toJSON(), map: map.getBoundingClientRect().toJSON(), player: firstPlayer.getBoundingClientRect().toJSON() };
});
assert.equal(layout.scroll, 0, 'focusing guides must not scroll the board under the header');
assert(Math.abs(layout.map.bottom - layout.board.bottom) < 1, 'map fills the board, not the whole viewport');
assert(layout.player.top >= layout.board.top, 'player cards stay below the header');
await toggle.click();
assert.equal(await warning.count(), 0);
assert.deepEqual(await page.evaluate(() => sent), []);
assert.deepEqual(errors, []);
await page.close();
}
console.log('Raiders: physical 3D/Strategy clicks, desktop keyboard/mobile touch; dark/light; spectator/off-turn civilization switch; visible map toolbar; no moves submitted.');
} finally { await browser.close(); await new Promise(resolve => server.close(resolve)); }

View file

@ -0,0 +1,43 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { raidersFixture } from './raiders-fixture.mjs';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const guide = (game, seat = 1) => JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(game), seat), seat)).tradeRoutes.find(p => p.player === 1);
test('Raiders metadata distinguishes two passengers from their trading ship, off-turn and public', async () => {
const game = await raidersFixture(engine), before = JSON.stringify(game);
const g = guide(game);
assert.deepEqual(g.raidedSettlers, [{ position: 'D7', unit: 6 }, { position: 'D7', unit: 7 }]);
assert.equal(g.routes.length, 1);
assert.equal(g.routes[0].unit, 8);
assert.deepEqual(guide(game, 0), g);
assert.deepEqual(JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(game)))).tradeRoutes.find(p => p.player === 1), g);
assert.equal(JSON.stringify(game), before);
game.players[0].cities[1].mood_state = 'Angry';
assert.equal(guide(game).routes[0].to, 'D9');
game.players[0].cities[0].mood_state = 'Angry';
assert.equal(guide(game).routes.length, 0);
assert.deepEqual(guide(game).raidedSettlers, g.raidedSettlers, 'angry destinations are not reported as extra raided sources');
});
test('own army aboard or outside, own city, and absent Raiders suppress the warning', async () => {
const game = await raidersFixture(engine), player = game.players[1];
player.units[0].carried_units.push({ unit_type: 'Infantry', id: 9 });
assert.deepEqual(guide(game).raidedSettlers, []);
player.units[0].carried_units = [];
player.units.push({ position: 'C8', unit_type: 'Settler', id: 6 });
assert.equal(guide(game).raidedSettlers.length, 1);
player.units.push({ position: 'C8', unit_type: 'Infantry', id: 9 });
assert.deepEqual(guide(game).raidedSettlers, []);
player.units.pop();
player.units.pop();
// Disembark onto friendly land/city rather than creating a city on water.
player.units.push({ position: 'D8', unit_type: 'Settler', id: 6 });
assert.deepEqual(guide(game).raidedSettlers, []);
player.units.pop();
player.units[0].carried_units = [{ unit_type: 'Settler', id: 6 }];
game.players[0].special_advances = [];
game.players[0].advances = game.players[0].advances.filter(a => a !== 'Tactics');
assert.deepEqual(guide(game).raidedSettlers, []);
});

View file

@ -33,7 +33,9 @@ try {
await page.evaluate(state=>{window.host=clash3d.launch('#app');window.sent=[];host.on('move',a=>sent.push(a));host.emit('player',{index:1});host.emit('theme',{dark:true});host.emit('preferences',{sound:false});host.emit('state',state)},engine.stripSecret(JSON.stringify(state),1));
await page.getByRole('button',{name:'Show trade routes',exact:true}).click();
const guide=page.locator('.pirate-spawn-key').filter({has:page.getByRole('combobox',{name:'Trade route player'})});
await guide.getByText('Current eligible pairings · 2',{exact:true}).waitFor();
await guide.locator('.coordinate-link').first().waitFor();
assert.equal(await guide.locator('.coordinate-link').count(),4,'both valid route pairings remain');
assert.doesNotMatch(await guide.textContent(),/Current eligible pairings/);
const box=await guide.boundingBox();assert(box.x>=0 && box.x+box.width<=width+1);
await page.screenshot({path:`/tmp/clash-trade-guide-${width}.png`});
await guide.getByRole('combobox').selectOption('0');

View file

@ -7,6 +7,7 @@
import CollectionBonusHints from './CollectionBonusHints.svelte';
import BarbarianIcon from './BarbarianIcon.svelte';
import MapGuide from './MapGuide.svelte';
import UnitIcon from './UnitIcon.svelte';
import CitySiteIcon from './CitySiteIcon.svelte';
import PlaybackPanel from './PlaybackPanel.svelte';
import CardReferenceDialog from './CardReferenceDialog.svelte';
@ -1101,13 +1102,15 @@
{#if !guide?.enabled}<p>Requires Trade Routes.</p>
{:else if !guide.routes.length}<p>No eligible trade routes.</p>
{:else}
<p>Current eligible pairings · {guide.routes.length}</p>
{#each guide.routes as route}
<div><button class="coordinate-link" onclick={() => world?.locateCoordinate(route.from)}>{route.from}</button>
→ <button class="coordinate-link" onclick={() => world?.locateCoordinate(route.to)}>{route.to}</button></div>
{/each}
<p>Routes are recalculated at the start of your turn.</p>
{/if}
{#if guide?.enabled && guide.raidedSettlers?.length}
<p class="raided-settlers-guide"><UnitIcon type="Settler" size={16} />Settlers blocked by Huns’ Raiders</p>
{/if}
</MapGuide>
{/if}
</div>
@ -1312,6 +1315,7 @@
>
{/if}
</div>
{#if $session.seat !== undefined}
<nav class="board-actions" aria-label="Actions">
<button
class:active={$session.mode === 'collect'}
@ -1473,6 +1477,7 @@
}}><Flag size={19} /><span>End turn</span></button
>
</nav>
{/if}
{#if queueControls?.pending && !queueControls.waiting && queueControls.seat === 0}
<div class="concurrent-choice-row">
<span class="concurrent-choice-copy"><span><strong>{queueControls.other}</strong> · <span>{queueControls.label ?? 'Placing a settler'}</span></span>{#if queueControls.queued}<strong>{queueControls.queued} queued{queueControls.ended ? ' · End turn queued' : ''}</strong>{/if}</span>

View file

@ -5,10 +5,14 @@
import TerrainRules from './TerrainRules.svelte';
import CityBuildings from './CityBuildings.svelte';
import TileUnits from './TileUnits.svelte';
import UnitIcon from './UnitIcon.svelte';
import { terrainInfo } from './terrain';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
const position = $derived($session.focus!);
const raided = $derived(!$session.playback && $session.tradeRoutes && $session.mode === 'overview' &&
$session.view?.tradeRoutes?.find(p => p.player === ($session.tradeRoutePlayer ?? $session.seat ?? $session.view?.activePlayer))
?.raidedSettlers?.some(source => source.position === position));
const frame = $derived($session.playback?.frame);
const players = $derived(frame?.players ?? $session.game?.players ?? []);
const terrain = $derived(
@ -36,6 +40,7 @@
<CityBuildings {city} owner={owner.id} {players} />
{/if}
<TileUnits {players} {position} />
{#if raided}<p class="city-rule raided-settlers-note"><UnitIcon type="Settler" size={16} />Settlers blocked by Huns’ Raiders</p>{/if}
{/if}
<TerrainRules {terrain} />
</section>

View file

@ -42,6 +42,9 @@
const cityMountainStop = $derived(ownCity?.size === 1 && !!publicCity?.nomad_mountain);
const ownUnits = $derived($session.view?.units?.filter((u) => u.position === position) ?? []);
const settler = $derived($session.view?.settlers.find((u) => u.position === position));
const raided = $derived($session.tradeRoutes && $session.mode === 'overview' &&
$session.view?.tradeRoutes?.find(p => p.player === ($session.tradeRoutePlayer ?? $session.seat ?? $session.view?.activePlayer))
?.raidedSettlers?.some(source => source.position === position));
const canMove = $derived(canMoveOnMap($session.view, $session.game));
const origins = $derived.by(() => {
// Recompute when the filtered game state changes, never from hidden state.
@ -135,6 +138,7 @@
</button>{/each}
</div>
{:else}<TileUnits players={$session.game?.players ?? []} {position} />{/if}
{#if raided}<p class="city-rule raided-settlers-note"><UnitIcon type="Settler" size={16} />Settlers blocked by Huns’ Raiders</p>{/if}
{#if settler && !publicCity}<FoundCityAction {controller} {settler} />{/if}
{#each $session.view?.players ?? [] as player}
{#each player.leaders?.filter((l) => l.position === position) ?? [] as leader}

View file

@ -27,7 +27,7 @@ import { playerColor, playerSymbol } from './types';
import { buildingCivilization } from './building-owner';
import { positionXY } from './model';
import { terrainInfo } from './terrain';
import { terrainDisplay } from './terrain-display';
import { terrainDisplay, tileSurfaceHeight } from './terrain-display';
import { PieceModels, type BuildingKind } from './piece-models';
import { MapGesture } from './map-gesture';
import { SeaOverlay } from './sea-overlay';
@ -1139,8 +1139,11 @@ export class World {
const tradePlayer = s.tradeRoutePlayer ?? s.seat ?? s.view?.activePlayer;
this.tradeOverlay.group.visible = !!s.tradeRoutes && s.mode === 'overview' && !s.playback &&
!s.view?.decision && !s.view?.choiceDecision && !s.view?.objectiveDecision && !s.view?.explorationDecision;
const tradeGuide = s.view?.tradeRoutes?.find(p => p.player === tradePlayer);
this.tradeOverlay.update(this.tradeOverlay.group.visible
? s.view?.tradeRoutes?.find(p => p.player === tradePlayer)?.routes ?? [] : [], '#f4c86b');
? tradeGuide?.routes ?? [] : [], '#f4c86b',
this.tradeOverlay.group.visible && tradeGuide?.enabled
? (tradeGuide.raidedSettlers ?? []).map(source => source.position) : [], s.game.map.tiles);
this.combatOverlay.update(combat);
if (s.reducedMotion || !battle) this.combatOverlay.stopAnimation();
@ -1228,7 +1231,7 @@ export class World {
for (const [position, terrain] of mapTiles) {
const { kind, exhausted } = terrainDisplay(terrain);
const [x, z] = positionXY(position);
const height = kind === 'Water' ? 0.13 : kind === 'Unexplored' ? 0.27 : 0.43;
const height = tileSurfaceHeight(terrain) + 0.12;
const group = new THREE.Group();
group.position.set(x, height / 2 - 0.12, z);
const top = this.material(
@ -1771,7 +1774,10 @@ export class World {
const barbarianMoves = barb?.moves ?? [];
const pirateFirst = s.threatGuide !== 'barbarians' ? (pirateSpawns?.first ?? []) : [];
const pirateSecond = s.threatGuide !== 'barbarians' ? (pirateSpawns?.second ?? []) : [];
const raidedPositions = this.tradeOverlay.group.visible && tradeGuide?.enabled
? (tradeGuide.raidedSettlers ?? []).map(source => source.position) : [];
const selectionSig = JSON.stringify([
raidedPositions,
selected,
available,
pirateFirst,
@ -1798,6 +1804,7 @@ export class World {
...barbarianSpawn,
...barbarianReinforce,
])) {
if (raidedPositions.includes(pos)) continue;
const [x, z] = positionXY(pos);
if (barbarianSpawn.includes(pos)) {
// Draw over terrain decorations; a dark outer edge stays visible without colour cues.

View file

@ -2613,6 +2613,56 @@ test('exploration previews four tiles before a second destination click submits'
}
});
test('spectator map guides keep inspection separate from seats, moves and private hands', async () => {
const app = paymentController(), c = app.controller;
try {
c.setPlayer(undefined);
const raw = JSON.parse(fixture('advances/trade_routes'));
const dealt = JSON.parse(await engine.init(2, [], {}, 'spectator-private', {}));
for (const index of [0, 1]) {
raw.players[index].action_cards = dealt.players[index].action_cards;
raw.players[index].objective_cards = dealt.players[index].objective_cards;
assert(raw.players[index].objective_cards.length > 0);
}
const publicState = engine.stripSecret(JSON.stringify(raw), undefined);
await c.load(publicState);
const game = app.session().game;
const active = app.session().view!.activePlayer;
const assertPublic = () => {
const s = app.session();
assert.equal(s.seat, undefined);
assert.equal(s.view!.activePlayer, active);
assert.equal(s.view!.canPlay, false);
assert.deepEqual(s.view!.cities, []);
assert.deepEqual(s.view!.objectiveCards, []);
assert.deepEqual(s.view!.wonderCards, []);
assert.equal(s.view!.actionCards?.length ?? 0, 0);
assert.equal(s.game, game, 'inspection does not reload as the selected player');
for (const player of s.game!.players.slice(0, 2)) {
assert(player.objective_cards?.every(id => id === 0), 'private objective identities stay stripped');
}
};
for (const player of app.session().view!.players) {
c.showTradeRoutes();
c.patch({ tradeRoutePlayer: player.index, showRegions: true, regionPlayer: player.index });
assertPublic();
c.showTradeRoutes(false);
c.showTradeRoutes();
assert.equal(app.session().tradeRoutePlayer, player.index, 'explicit inspection survives reopening');
c.showSeaRoutes();
c.showPirateSpawns();
c.setPirateSpawnPlayer(player.index);
c.showPirateSpawns(true, 'barbarians');
c.toggleMapView();
c.selectTile('C2');
c.submit({ Playing: 'EndTurn' });
assertPublic();
}
assert.deepEqual(app.sent, []);
assert.deepEqual(app.settings, []);
} finally { app.close(); }
});
test('trade-route toggle is read-only and exclusive with other map guides', async () => {
const app = paymentController(),
c = app.controller;

View file

@ -1427,7 +1427,11 @@ export class Controller {
showTradeRoutes(show = true) {
this.closeActivity();
const s = get(this.session);
this.patch({ tradeRoutes: show, tradeRoutePlayer: s.seat ?? s.view?.activePlayer,
// Inspection civilization is independent of the viewer seat and turn owner.
// Keep an explicit selection when reopening the guide (including spectators).
const tradeRoutePlayer = s.view?.players.some(p => p.index === s.tradeRoutePlayer)
? s.tradeRoutePlayer : s.seat ?? s.view?.activePlayer;
this.patch({ tradeRoutes: show, tradeRoutePlayer,
seaRoutes: false, pirateSpawns: false, tilePanel: false, mode: 'overview',
abilitiesOpen: false, selection: [], preview: null, focus: null, error: '' });
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Byg, rekruttér og øg lykken",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Hver civilisation har sine egne fremskridt. Rom får Akvædukt, når den forsker i Ingeniørkunst. Åbn Fremskridt, og forsk i Ingeniørkunst; Akvædukt låses automatisk op uden et separat køb.",
"Invalid fleet boarding assignment": "Ugyldig fordeling ved ombordstigning",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Nybyggere blokeret af hunnernes plyndrere"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Bauen, rekrutieren und Stimmung verbessern",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Jede Zivilisation hat eigene Fortschritte. Rom erhält Aquädukt, wenn es Ingenieurwesen erforscht. Öffne Fortschritte und erforsche Ingenieurwesen; Aquädukt wird automatisch freigeschaltet, ohne einen gesonderten Kauf.",
"Invalid fleet boarding assignment": "Ungültige Zuordnung beim Einschiffen",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Siedler durch die Plünderer der Hunnen blockiert"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Κατασκευή, στρατολόγηση και αύξηση ευτυχίας",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Κάθε πολιτισμός έχει τις δικές του προόδους. Η Ρώμη αποκτά το Υδραγωγείο όταν ερευνά τη Μηχανική. Άνοιξε τις Προόδους και ερεύνησε τη Μηχανική· το Υδραγωγείο ξεκλειδώνει αυτόματα, χωρίς ξεχωριστή αγορά.",
"Invalid fleet boarding assignment": "Μη έγκυρη ανάθεση επιβίβασης στον στόλο",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Άποικοι μπλοκαρισμένοι από τους Επιδρομείς των Ούννων"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Construct, recruit and improve happiness",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.",
"Invalid fleet boarding assignment": "Invalid fleet boarding assignment",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Settlers blocked by Huns’ Raiders"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "ساخت، جذب نیرو و افزایش شادی",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "هر تمدن پیشرفت‌های مخصوص خود را دارد. روم با پژوهش مهندسی، آب‌گذر را به دست می‌آورد. پیشرفت‌ها را باز کنید و مهندسی را پژوهش کنید؛ آب‌گذر خودکار و بدون خرید جداگانه باز می‌شود.",
"Invalid fleet boarding assignment": "تخصیص نامعتبر برای سوار شدن به ناوگان",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "مهاجران توسط غارتگران هون‌ها مسدود شده‌اند"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Construire, recruter et améliorer le bonheur",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Chaque civilisation possède ses propres avancées. Rome obtient Aqueduc en recherchant Ingénierie. Ouvrez Progrès et recherchez Ingénierie ; Aqueduc se débloque automatiquement, sans achat séparé.",
"Invalid fleet boarding assignment": "Affectation d’embarquement invalide",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Colons bloqués par les Pillards des Huns"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "निर्माण करें, भर्ती करें और खुशहाली बढ़ाएँ",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "हर सभ्यता की अपनी उन्नतियाँ होती हैं। रोम अभियांत्रिकी पर शोध करने पर जलसेतु पाता है। उन्नतियाँ खोलें और अभियांत्रिकी पर शोध करें; जलसेतु अलग खरीद के बिना अपने-आप खुल जाता है।",
"Invalid fleet boarding assignment": "बेड़े पर चढ़ने का अमान्य आवंटन",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "हूणों के हमलावरों द्वारा अवरुद्ध बसने वाले"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Costruisci, recluta e aumenta la felicità",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Ogni civiltà ha i propri progressi. Roma ottiene Acquedotto quando ricerca Ingegneria. Apri Progressi e ricerca Ingegneria; Acquedotto si sblocca automaticamente, senza un acquisto separato.",
"Invalid fleet boarding assignment": "Assegnazione di imbarco sulla flotta non valida",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Coloni bloccati dai Razziatori degli Unni"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "건설·모집·행복 개선",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "문명마다 고유 발전이 있습니다. 로마는 공학을 연구하면 수로를 얻습니다. 발전을 열고 공학을 연구하세요. 수로는 따로 구매하지 않아도 자동으로 해금됩니다.",
"Invalid fleet boarding assignment": "함대 승선 배정이 유효하지 않습니다",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "훈족의 약탈자에 의해 개척자 차단됨"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Bouwen, rekruteren en tevredenheid verhogen",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Elke beschaving heeft eigen ontwikkelingen. Rome krijgt Aquaduct wanneer het Bouwkunde onderzoekt. Open Ontwikkelingen en onderzoek Bouwkunde; Aquaduct wordt automatisch ontgrendeld, zonder aparte aankoop.",
"Invalid fleet boarding assignment": "Ongeldige indeling voor inscheping op de vloot",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Kolonisten geblokkeerd door de plunderaars van de Hunnen"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Buduj, rekrutuj i poprawiaj nastrój",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Każda cywilizacja ma własne postępy. Rzym otrzymuje Akwedukt po zbadaniu Inżynierii. Otwórz Postępy i zbadaj Inżynierię; Akwedukt odblokowuje się automatycznie, bez osobnego zakupu.",
"Invalid fleet boarding assignment": "Nieprawidłowy przydział jednostek do statków",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Osadnicy zablokowani przez najeźdźców Hunów"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Construir, recrutar e melhorar felicidade",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Cada civilização tem seus próprios avanços. Roma ganha Aqueduto ao pesquisar Engenharia. Abra Avanços e pesquise Engenharia; Aqueduto desbloqueia automaticamente, sem uma compra separada.",
"Invalid fleet boarding assignment": "Distribuição inválida para embarque na frota",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Colonos bloqueados pelos Saqueadores dos Hunos"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Construiește, recrutează și îmbunătățește fericirea",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Fiecare civilizație are propriile progrese. Roma primește Apeduct când cercetează Inginerie. Deschide Progrese și cercetează Inginerie; Apeduct se deblochează automat, fără o achiziție separată.",
"Invalid fleet boarding assignment": "Repartizare nevalidă pentru îmbarcare",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Coloniști blocați de Jefuitorii hunilor"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Строительство, найм и повышение счастья",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "У каждой цивилизации свои достижения. Рим получает Акведук, когда исследует Инженерию. Откройте «Достижения» и исследуйте Инженерию; Акведук откроется автоматически, без отдельной покупки.",
"Invalid fleet boarding assignment": "Недопустимое распределение при посадке на корабли",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Поселенцы заблокированы налётчиками гуннов"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "Xây dựng, tuyển quân và tăng hạnh phúc",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "Mỗi nền văn minh có tiến bộ riêng. La Mã nhận Cầu dẫn nước khi nghiên cứu Kỹ thuật. Mở Các tiến bộ và nghiên cứu Kỹ thuật; Cầu dẫn nước tự mở khóa, không cần mua riêng.",
"Invalid fleet boarding assignment": "Phân bổ lên hạm đội không hợp lệ",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "Người định cư bị chặn bởi quân đột kích Hung Nô"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "建造、招募并提升幸福度",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "各文明都有专属进步。罗马研究工程学时获得引水渠。打开进步并研究工程学,引水渠自动解锁,无需单独购买。",
"Invalid fleet boarding assignment": "舰队登船分配无效",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠夺者阻止"
}

View file

@ -5308,5 +5308,6 @@
"Construct, recruit and improve happiness": "建造、招募與提升幸福",
"Each civilization has its own advances. Rome gains Aqueduct when it researches Engineering. Open Advances and research Engineering; Aqueduct unlocks automatically, without a separate purchase.": "每個文明都有專屬科技。羅馬研究工程學時獲得水道橋。開啟科技並研究工程學;水道橋會自動解鎖,不需要另行購買。",
"Invalid fleet boarding assignment": "艦隊登船分配無效",
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})"
"{p0} #{p1} ({p2} + {p3} / {p4})": "{p0} #{p1} ({p2} + {p3} / {p4})",
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠奪者阻止"
}

View file

@ -2189,7 +2189,12 @@ small {
overflow: hidden;
}
.map-section {
height: 100%;
/* Fill the flex-sized board explicitly. Percentage height can resolve against
the viewport in embedded WebKit, placing the map toolbar below the screen
and scrolling the player cards behind the header when a guide is focused. */
position: absolute;
inset: 0;
height: auto;
min-height: 0;
}
.map-world,
@ -3181,6 +3186,12 @@ small {
.map-tooltip p {
margin-top: 7px;
}
.map-tooltip .raided-settlers-guide {
display: flex;
align-items: center;
gap: 5px;
}
.raided-settlers-guide > svg { flex-shrink: 0; }
.map-tooltip .route-line {
width: 22px;
flex-shrink: 0;

View file

@ -1,5 +1,11 @@
import type { Terrain } from './types.ts';
/** Top of the hex slab, excluding trees, mountains, cities and pieces. */
export function tileSurfaceHeight(terrain: Terrain) {
const { kind } = terrainDisplay(terrain);
return (kind === 'Water' ? 0.13 : kind === 'Unexplored' ? 0.27 : 0.43) - 0.12;
}
/** Visual identity only: never use the unwrapped kind for action legality. */
export function terrainDisplay(terrain: Terrain) {
const exhausted = typeof terrain !== 'string';

View file

@ -1,6 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TradeOverlay } from './trade-overlay.ts';
import * as THREE from 'three';
import { tileSurfaceHeight } from './terrain-display.ts';
import type { Terrain } from './types.ts';
test('trade overlay draws pairings and replaces or clears old geometry', () => {
const overlay = new TradeOverlay();
@ -16,3 +19,37 @@ test('trade overlay draws pairings and replaces or clears old geometry', () => {
assert.equal(overlay.group.children.length, 0);
overlay.dispose();
});
test('Raiders source contours deduplicate a shared tile without hiding its valid ship route', () => {
const overlay = new TradeOverlay();
overlay.update([{ from: 'D7', to: 'D9' }], '#f4c86b', ['D7', 'D7']);
assert.equal(overlay.group.children.length, 3, 'valid route, destination endpoint, and one solid orange source contour');
assert.equal((overlay.group.children[0] as any).geometry.type, 'TubeGeometry', 'ship route line remains visible');
assert.equal((overlay.group.children[2] as any).material.color.getHexString(), 'ed8a23');
overlay.update([{ from: 'D7', to: 'D9' }, { from: 'C2', to: 'A1' }], '#f4c86b', ['D7']);
assert.equal(overlay.group.children.length, 6, 'both valid routes remain visible');
overlay.update([{ from: 'D7', to: 'D9' }], '#f4c86b', []);
assert.equal(overlay.group.children.length, 3, 'protection restores the normal route');
overlay.update([], '#f4c86b');
assert.equal(overlay.group.children.length, 0);
});
for (const terrain of ['Water', 'Fertile', 'Mountain', 'Unexplored', { Exhausted: 'Mountain' }] satisfies Terrain[]) {
test(`Raiders contour hugs the slab below pieces: ${JSON.stringify(terrain)}`, () => {
const overlay = new TradeOverlay();
overlay.update([{ from: 'D7', to: 'D9' }], '#f4c86b', ['D7'], [['D7', terrain], ['D9', terrain]]);
const ring = overlay.group.children[2] as THREE.Mesh<THREE.TorusGeometry, THREE.MeshBasicMaterial>;
const surface = tileSurfaceHeight(terrain);
assert(Math.abs(ring.position.y - surface - 0.04) < 1e-8);
assert(ring.position.y - ring.geometry.parameters.tube > surface, 'tube clears slab without z-fighting');
assert(ring.position.y + ring.geometry.parameters.tube < surface + 0.07, 'contour remains at ground level, not above unit bodies');
assert(ring.geometry.parameters.radius + ring.geometry.parameters.tube < 0.976, 'contour stays inside tile perimeter');
assert.equal(ring.material.depthTest, true, 'terrain and unit silhouettes occlude the contour');
assert.equal(ring.material.depthWrite, false);
assert.equal(overlay.group.children[1].position.y, ring.position.y, 'gold and orange endpoints share slab-relative height');
assert.equal((overlay.group.children[0] as THREE.Mesh).geometry.type, 'TubeGeometry', 'valid ship route survives');
overlay.update([], '#f4c86b', ['D7'], [['D7', 'Water']]);
assert(Math.abs(overlay.group.children[0].position.y - 0.05) < 1e-8, 'terrain changes invalidate cached elevation');
overlay.dispose();
});
}

View file

@ -1,16 +1,21 @@
import * as THREE from 'three';
import { positionXY } from './model.ts';
import { tileSurfaceHeight } from './terrain-display.ts';
import type { Terrain } from './types.ts';
/** Public trade pairings, not movement paths or submitted actions. */
export class TradeOverlay {
readonly group = new THREE.Group();
private signature = '';
update(routes: { from: string; to: string }[], color: string) {
const signature = JSON.stringify([routes, color]);
update(routes: { from: string; to: string }[], color: string, raidedPositions: string[] = [], tiles: [string, Terrain][] = []) {
const surfaces = new Map(tiles.map(([position, terrain]) => [position, tileSurfaceHeight(terrain)]));
const contourHeight = (position: string) => (surfaces.get(position) ?? tileSurfaceHeight('Fertile')) + 0.04;
const signature = JSON.stringify([routes, color, raidedPositions, tiles]);
if (signature === this.signature) return;
this.dispose();
this.signature = signature;
const material = new THREE.MeshBasicMaterial({ color, depthTest: false, depthWrite: false, transparent: true, opacity: 0.9 });
const raided = new Set(raidedPositions);
const endpoints = new Set<string>();
for (const { from, to } of routes) {
endpoints.add(from); endpoints.add(to);
@ -22,13 +27,30 @@ export class TradeOverlay {
line.renderOrder = 5; this.group.add(line);
}
for (const position of endpoints) {
if (raided.has(position)) continue;
const [x, z] = positionXY(position);
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.83, 0.035, 5, 6), material);
ring.rotation.x = -Math.PI / 2; ring.position.set(x, 0.65, z); ring.renderOrder = 5;
ring.rotation.x = -Math.PI / 2; ring.position.set(x, contourHeight(position), z); ring.renderOrder = 5;
this.group.add(ring);
}
if (!routes.length) material.dispose();
// Keep valid route lines, including ships sharing a raided Settler hex.
// Only the endpoint contour is replaced with orange, avoiding stacked rings.
if (raided.size) {
// Depth-test against terrain and pieces instead of painting over their silhouettes.
const warning = new THREE.MeshBasicMaterial({ color: '#ed8a23', depthTest: true, depthWrite: false, toneMapped: false });
for (const position of raided) {
const [x, z] = positionXY(position);
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.94, 0.025, 6, 6), warning);
ring.rotation.x = -Math.PI / 2;
// The tube sits just above the slab, not at the old fixed unit-height 0.67.
ring.position.set(x, contourHeight(position), z);
ring.renderOrder = 6;
this.group.add(ring);
}
}
}
dispose() {
const materials = new Set<THREE.Material>();
this.group.traverse(object => {

View file

@ -364,6 +364,7 @@ export interface View {
player: number;
enabled: boolean;
routes: { from: string; to: string; unit: number | null }[];
raidedSettlers?: { position: string; unit: number }[];
}[];
regions?: { id: number; homePlayer: number | null; tiles: string[] }[];
seaRoutes?: string[][];