Add cultural influence thought bubbles, center color-blind symbols, prepare release 0.1.243

This commit is contained in:
coyotte508 2026-11-25 10:11:04 +00:00
commit 5d536a5615
35 changed files with 1102 additions and 57 deletions

View file

@ -30,7 +30,7 @@ jobs:
working-directory: web-client
- run: node scripts/viking-cargo-smoke.mjs && node scripts/withdrawal-smoke.mjs && 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
- run: node scripts/map-guide-smoke.mjs && node scripts/trade-routes-smoke.mjs && node scripts/raiders-smoke.mjs && node scripts/influence-bubble-smoke.mjs
working-directory: web-client
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:

View file

@ -1878,3 +1878,22 @@ green before publishing the frozen viewer and engine together. Preserve catalog
settings and preferences. Only the artwork manifest's lockfile integrity pin
changes; no artwork is republished and no production moves, repairs, backfills
or historical rewrites are performed.
# Viewer 0.1.243 / engine 0.4.173 — Cultural influence thought bubbles and centered color-blind symbols
Cities with foreign buildings now display a compact cultural-influence thought
bubble in both 3D and Strategy views showing each influencing civilization's
color-coded emblem medallion, a count pip when a civilization holds multiple
foreign buildings, and an accessible hover/screen-reader summary without placing
civilization text labels on the board. Color-blind ownership symbols (`●`, `▲`,
`■`, `◆`, `✚`, `✕`) now render via dead-center geometric paths/SVGs across 3D
flag badges, thought-bubble symbol pills, Strategy badges, and player cards
(with bounding-box centering fallback for custom symbols).
Engine 0.4.173 is unchanged since 0.1.242 and publishes alongside viewer
0.1.243. Require exact-commit Check and Web viewer CI green before publishing
the frozen viewer and engine together. Preserve catalog 8 / 46 definitions,
artwork 4, all 60 named assets, gallery, Standard options, settings and
preferences. Only the artwork manifest's lockfile integrity pin changes; no
artwork is republished and no production moves, repairs, backfills or
historical rewrites are performed.

View file

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

View file

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

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": "ef90167f54b1fc2c4386da61388759467180dff77d5bdc2fe7c893a8f3c36d7b",
"web-client/package-lock.json": "991ba032023910ccfb0f0951ddf3a2568f2e9fd80c154d2d55c72ed5a38f3739",
"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

@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import { chromium } from 'playwright';
import { startPreview } from './influence-preview.mjs';
const server = await startPreview(0);
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
function boxesOverlap(a, b) {
return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
}
try {
const baseUrl = `http://127.0.0.1:${server.address().port}`;
// 1. Standard 3D view: uninfluenced, 1-building, multi-building count pip, multi-civ, click-to-select, no overlap.
{
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(`${baseUrl}/`);
await page.locator('.city-influence-bubble').first().waitFor();
await page.waitForTimeout(400);
const bubbles = page.locator('.city-influence-bubble');
assert.equal(await bubbles.count(), 3, 'Uninfluenced C3 has no bubble; F3, F5, C5 each have one');
const bubbleInfo = await page.evaluate(() =>
[...document.querySelectorAll('.city-influence-bubble')].map((el) => ({
title: el.getAttribute('title') ?? '',
ariaLabel: el.getAttribute('aria-label') ?? '',
text: (el.innerText ?? '').trim(),
medallions: el.querySelectorAll('.influence-medallion').length,
counts: [...el.querySelectorAll('.influence-count')].map((n) => n.textContent?.trim()),
symbols: el.querySelectorAll('.influence-symbol').length,
rect: el.getBoundingClientRect().toJSON(),
})),
);
const single = bubbleInfo.find((b) => b.title === 'Influenced by Greece');
const multiCount = bubbleInfo.find((b) => b.title === 'Influenced by Greece (3)');
const multiCiv = bubbleInfo.find((b) => b.title === 'Influenced by Greece, Egypt');
assert.ok(single, 'F3 single-building influence bubble present');
assert.equal(single.medallions, 1);
assert.deepEqual(single.counts, []);
assert.equal(single.symbols, 0);
assert.ok(multiCount, 'F5 multi-building influence bubble present');
assert.equal(multiCount.medallions, 1);
assert.deepEqual(multiCount.counts, ['3']);
assert.ok(multiCiv, 'C5 multi-civ influence bubble present');
assert.equal(multiCiv.medallions, 2);
assert.deepEqual(multiCiv.counts, []);
for (const b of bubbleInfo) {
assert.doesNotMatch(b.text, /Greece|Egypt|Rome/i, 'No visible civilization text on board bubbles');
}
// Verify no overlap between any city mood badge and any influence bubble in 3D view.
const moodRects = await page.evaluate(() =>
[...document.querySelectorAll('.city-map-label')].map((el) => ({
label: el.getAttribute('aria-label') ?? '',
rect: el.getBoundingClientRect().toJSON(),
})),
);
assert.equal(moodRects.length, 4, 'All 4 cities render mood badges');
for (const bubble of bubbleInfo) {
for (const mood of moodRects) {
assert.equal(
boxesOverlap(bubble.rect, mood.rect),
false,
`Bubble "${bubble.title}" must not overlap mood badge "${mood.label}"`,
);
}
}
// Clicking a thought bubble selects its city without submitting any gameplay moves.
await page.locator('.city-influence-bubble[title="Influenced by Greece (3)"]').click();
await page.getByRole('region', { name: /Tile F5/ }).waitFor();
assert.deepEqual(await page.evaluate(() => window.sent), [], 'Clicking influence bubble must not send moves');
assert.deepEqual(errors, []);
await page.close();
}
// 2. Strategy view (normal + color-blind): compact bubbles, zero civ text on board, color-blind symbols centered.
for (const colorBlind of [false, true]) {
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(`${baseUrl}/?strategy=1${colorBlind ? '&colorblind=1' : ''}`);
await page.locator('.strategy-map-tile[data-position="F5"]').waitFor();
assert.equal(
await page.locator('.strategy-map-tile[data-position="C3"] .strategy-influence-bubble').count(),
0,
'Uninfluenced C3 has no Strategy influence bubble',
);
const f3 = page.locator('.strategy-map-tile[data-position="F3"] .strategy-influence-bubble');
const f5 = page.locator('.strategy-map-tile[data-position="F5"] .strategy-influence-bubble');
const c5 = page.locator('.strategy-map-tile[data-position="C5"] .strategy-influence-bubble');
assert.equal(await f3.getAttribute('title'), 'Influenced by Greece');
assert.equal(await f5.getAttribute('title'), 'Influenced by Greece (3)');
assert.equal(await c5.getAttribute('title'), 'Influenced by Greece, Egypt');
assert.equal(await f3.locator('.influence-medallion').count(), 1);
assert.equal(await f3.locator('.influence-count').count(), 0);
assert.equal(await f5.locator('.influence-count').textContent(), '3');
assert.equal(await c5.locator('.influence-medallion').count(), 2);
for (const tilePos of ['C3', 'F3', 'F5', 'C5']) {
const tileText = await page.locator(`.strategy-map-tile[data-position="${tilePos}"]`).innerText();
assert.doesNotMatch(tileText, /Greece|Egypt|Rome/i, `Strategy tile ${tilePos} has no visible civ text`);
}
if (colorBlind) {
assert.equal(await f3.locator('.influence-symbol[data-symbol="▲"] svg.ownership-symbol-svg').count(), 1);
assert.equal(await c5.locator('.influence-symbol[data-symbol="▲"] svg.ownership-symbol-svg').count(), 1);
assert.equal(await c5.locator('.influence-symbol[data-symbol="■"] svg.ownership-symbol-svg').count(), 1);
assert.ok((await page.locator('.strategy-symbol svg.ownership-symbol-svg').count()) >= 4);
assert.equal(await page.locator('.ownership-symbol svg.ownership-symbol-svg').count(), 3);
} else {
assert.equal(await page.locator('.influence-symbol').count(), 0);
}
assert.deepEqual(await page.evaluate(() => window.sent), []);
assert.deepEqual(errors, []);
await page.close();
}
// 3. 3D color-blind mode: centered SVG pills in thought bubbles + player cards, zero errors.
{
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(`${baseUrl}/?colorblind=1`);
await page.locator('.city-influence-bubble').first().waitFor();
await page.waitForTimeout(400);
assert.equal(await page.locator('.city-influence-bubble .influence-symbol svg.ownership-symbol-svg').count(), 4);
assert.equal(await page.locator('.ownership-symbol svg.ownership-symbol-svg').count(), 3);
assert.deepEqual(await page.evaluate(() => window.sent), []);
assert.deepEqual(errors, []);
await page.close();
}
console.log(
'Cultural influence bubbles & centered color-blind symbols: 3D/Strategy, single/counted/multi-civ, click-to-select, zero civ text, no mood overlap, and color-blind mode passed.',
);
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -0,0 +1,115 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
export async function influenceFixture(engine) {
let raw = await engine.init(3, [], { civilization: 'ChooseCivilization' }, 'influence-preview', {});
for (const civ of ['Rome', 'Greece', 'Egypt']) {
raw = engine.tryMove(raw, JSON.stringify({ ChooseCivilization: civ }), engine.currentPlayer(raw));
}
const game = JSON.parse(raw);
const cols = ['C', 'D', 'E', 'F', 'G'];
const terrainAt = (col, row) => {
if (col === 'G') return 'Water';
if (col === 'D' && row === 2) return 'Mountain';
if ((col === 'C' && row === 5) || (col === 'E' && row === 3) || (col === 'D' && row === 6)) return 'Forest';
if (col === 'E' && row === 6) return 'Barren';
return 'Fertile';
};
game.map.tiles = [];
for (const col of cols) {
for (let row = 2; row <= 6; row++) {
game.map.tiles.push([col + row, terrainAt(col, row)]);
}
}
if (game.map.unexplored_blocks) game.map.unexplored_blocks = [];
for (const player of game.players) {
player.cities = [];
player.units = [];
}
game.players[0].civilization = 'Rome';
game.players[1].civilization = 'Greece';
game.players[2].civilization = 'Egypt';
// 4 nearby Roman cities demonstrating control, single-civ, counted single-civ, and multi-civ influence.
game.players[0].cities = [
{
position: 'C3',
mood_state: 'Happy',
city_pieces: { temple: 0, fortress: 0 },
},
{
position: 'F3',
mood_state: 'Happy',
city_pieces: { temple: 1 },
},
{
position: 'F5',
mood_state: 'Neutral',
city_pieces: { academy: 1, port: 1, temple: 1, fortress: 0 },
port_position: 'G5',
},
{
position: 'C5',
mood_state: 'Angry',
city_pieces: { temple: 1, obelisk: 2 },
},
];
return game;
}
const contentType = (path) =>
path.endsWith('.wasm')
? 'application/wasm'
: path.endsWith('.json')
? 'application/json'
: path.endsWith('.woff2')
? 'font/woff2'
: 'text/javascript';
export async function startPreview(port = 8646) {
const engine = createRequire(import.meta.url)('../.engine/server.js');
const game = await influenceFixture(engine);
const raw = JSON.stringify(game);
const state = engine.stripSecret(raw, 0);
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const path = url.pathname;
if (path === '/') {
const dark = url.searchParams.get('dark') === '1';
const colorBlind = url.searchParams.get('colorblind') === '1';
const mapView = url.searchParams.get('strategy') === '1' ? 'strategy' : '3d';
const locale = url.searchParams.get('locale') || 'en';
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 · Cultural influence preview</title><div id="app"></div><script src="/viewer.js"></script><script>
window.host = clash3d.launch('#app');
window.sent = [];
window.prefs = { sound: false, mapView: ${JSON.stringify(mapView)}, colorBlind: ${JSON.stringify(colorBlind)}, locale: ${JSON.stringify(locale)} };
host.on('move', (a) => sent.push(a));
host.on('update:preference', ({ name, value }) => { prefs[name] = value; host.emit('preferences', prefs); });
host.emit('player', { index: 0 });
host.emit('theme', { dark: ${JSON.stringify(dark)} });
host.emit('preferences', prefs);
host.emit('state', ${JSON.stringify(state)});
</script>`);
}
if (!/^\/(viewer\.js|server_bg\.wasm|[a-zA-Z-]+\.json|[a-zA-Z-]+\.woff2)$/.test(path)) {
res.statusCode = 404;
return res.end();
}
try {
res.setHeader('Content-Type', contentType(path));
res.end(await readFile(new URL('../dist' + path, import.meta.url)));
} catch {
res.statusCode = 404;
res.end();
}
});
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('Cultural influence preview: http://localhost:8646/ (normal viewer, 3D + Strategy)');
}

View file

@ -6,6 +6,7 @@
import UndoControl from './UndoControl.svelte';
import CollectionBonusHints from './CollectionBonusHints.svelte';
import BarbarianIcon from './BarbarianIcon.svelte';
import OwnershipSymbol from './OwnershipSymbol.svelte';
import MapGuide from './MapGuide.svelte';
import UnitIcon from './UnitIcon.svelte';
import CitySiteIcon from './CitySiteIcon.svelte';
@ -953,8 +954,10 @@
><CivilizationEmblem civilization={player.civilization} size={64} /></span
>
<span class="player-emblem"
>{#if $session.colorBlind}<span class="ownership-symbol" aria-hidden="true"
>{playerSymbol(player.index, $session.playerSymbols)}</span
>{#if $session.colorBlind}{@const symbol = playerSymbol(player.index, $session.playerSymbols)}<span
class="ownership-symbol"
data-symbol={symbol}
aria-hidden="true"><OwnershipSymbol {symbol} size={18} /></span
>{:else}<CivilizationEmblem
civilization={player.civilization}
size={24}

View file

@ -0,0 +1,39 @@
<script lang="ts">
import CivilizationEmblem from './CivilizationEmblem.svelte';
import OwnershipSymbol from './OwnershipSymbol.svelte';
import { emblemInkColor, type CityInfluencer } from './building-owner';
import { playerColor, playerSymbol } from './types';
let {
influencers,
colorBlind = false,
playerColors = [],
playerSymbols = [],
compact = false,
}: {
influencers: readonly CityInfluencer[];
colorBlind?: boolean;
playerColors?: readonly string[];
playerSymbols?: readonly string[];
compact?: boolean;
} = $props();
</script>
<span class="influence-medallions" class:compact aria-hidden="true">
{#each influencers as influencer (influencer.owner)}
{@const bg = playerColor(influencer.owner, colorBlind, playerColors)}
{@const ink = emblemInkColor(bg)}
<span class="influence-medallion" style={`--medallion-bg:${bg};--medallion-ink:${ink}`}>
<CivilizationEmblem civilization={influencer.civilization} size={compact ? 11 : 13} />
{#if colorBlind && !['Barbarians', 'Pirates'].includes(influencer.civilization)}
{@const symbol = playerSymbol(influencer.owner, playerSymbols)}
<span class="influence-symbol" data-symbol={symbol}>
<OwnershipSymbol {symbol} size={compact ? 7 : 8} />
</span>
{/if}
{#if influencer.count > 1}
<span class="influence-count">{influencer.count}</span>
{/if}
</span>
{/each}
</span>

View file

@ -0,0 +1,37 @@
<script lang="ts">
let { symbol, size = 12 }: { symbol: string; size?: number } = $props();
</script>
{#if symbol === '●'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<circle cx="8" cy="8" r="5.2" fill="currentColor" />
</svg>
{:else if symbol === '▲'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<polygon points="8,2.6 13.4,11.9 2.6,11.9" fill="currentColor" />
</svg>
{:else if symbol === '■'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<rect x="3.4" y="3.4" width="9.2" height="9.2" fill="currentColor" />
</svg>
{:else if symbol === '◆'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<polygon points="8,2.2 13.8,8 8,13.8 2.2,8" fill="currentColor" />
</svg>
{:else if symbol === '✚'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<rect x="2.6" y="6.1" width="10.8" height="3.8" fill="currentColor" />
<rect x="6.1" y="2.6" width="3.8" height="10.8" fill="currentColor" />
</svg>
{:else if symbol === '✕'}
<svg class="ownership-symbol-svg" viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<path
d="M3.8 3.8L12.2 12.2M12.2 3.8L3.8 12.2"
stroke="currentColor"
stroke-width="2.8"
stroke-linecap="round"
/>
</svg>
{:else}
<span class="ownership-symbol-glyph">{symbol}</span>
{/if}

View file

@ -1,7 +1,9 @@
<script lang="ts">
import { Swords, Ship, Footprints, Landmark, Shield, Skull, Smile, Meh, Frown } from 'lucide-svelte';
import { buildingInfo } from './city';
import { cityInfluenceSummary } from './building-owner';
import BarbarianIcon from './BarbarianIcon.svelte';
import CityInfluenceBubble from './CityInfluenceBubble.svelte';
import OwnershipSymbol from './OwnershipSymbol.svelte';
import TerrainIcon from './TerrainIcon.svelte';
import { terrainDisplay } from './terrain-display';
import { playerColor, playerSymbol } from './types';
@ -23,9 +25,10 @@
>
{#each tile.occupants as occupant}
<span class="strategy-owner" style={`--owner:${playerColor(occupant.player.id, colorBlind, playerColors)}`}>
{#if colorBlind && !['Barbarians', 'Pirates'].includes(occupant.player.civilization)}<span
class="strategy-symbol">{playerSymbol(occupant.player.id, playerSymbols)}</span
>{/if}
{#if colorBlind && !['Barbarians', 'Pirates'].includes(occupant.player.civilization)}{@const symbol = playerSymbol(
occupant.player.id,
playerSymbols,
)}<span class="strategy-symbol" data-symbol={symbol}><OwnershipSymbol {symbol} size={13} /></span>{/if}
{#if occupant.city}<span class="strategy-city"
>{#if occupant.player.civilization === 'Barbarians'}<BarbarianIcon size={17} />{:else}<Landmark
size={17}
@ -42,15 +45,16 @@
title={occupant.city.mood_state}><Mood size={17} aria-hidden="true" /></span
>{/if}</span
>{/if}
{#if occupant.city}
{#each Object.entries(occupant.city.city_pieces ?? {}) as [building, owner]}
{@const info = buildingInfo[building[0].toUpperCase() + building.slice(1)]}
{#if typeof owner === 'number' && owner !== occupant.player.id && info}
<span class="foreign-building-icon" style={`color:${playerColor(owner, colorBlind, playerColors)}`}>
<info.icon size={17} />
</span>
{/if}
{/each}
{#if occupant.influencers.length}
<span class="strategy-influence-bubble" title={cityInfluenceSummary(occupant.influencers)}>
<CityInfluenceBubble
influencers={occupant.influencers}
{colorBlind}
{playerColors}
{playerSymbols}
compact
/>
</span>
{/if}
{#if occupant.army || occupant.ships || occupant.settlers}<span class="strategy-forces">
{#if occupant.army - occupant.aboard > 0}<span

View file

@ -24,7 +24,9 @@ import { explorationPreview } from './exploration-preview';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import type { Session, Terrain } from './types';
import { playerColor, playerSymbol } from './types';
import { buildingCivilization } from './building-owner';
import { drawOwnershipSymbol } from './ownership-symbol';
import { buildingCivilization, cityInfluencers, cityInfluenceSummary } from './building-owner';
import CityInfluenceBubble from './CityInfluenceBubble.svelte';
import { positionXY } from './model';
import { terrainInfo } from './terrain';
import { terrainDisplay, tileSurfaceHeight } from './terrain-display';
@ -198,7 +200,7 @@ export class World {
position: string;
at: THREE.Vector3;
node: HTMLButtonElement;
kind: 'city' | 'units' | 'destination' | 'collection' | 'strategy' | 'barbarian-city';
kind: 'city' | 'city-influence' | 'units' | 'destination' | 'collection' | 'strategy' | 'barbarian-city';
offsetX?: number;
offsetY?: number;
ownershipBounds?: THREE.Vector3[];
@ -548,11 +550,18 @@ export class World {
let x = ((v.x + 1) * w) / 2 + (label.offsetX ?? 0);
const y = ((-v.y + 1) * h) / 2 + (label.offsetY ?? 0);
if (label.ownershipBounds) {
const flagLeft = Math.min(
...label.ownershipBounds.map((point) => ((point.clone().project(this.camera).x + 1) * w) / 2),
const projectedX = label.ownershipBounds.map(
(point) => ((point.clone().project(this.camera).x + 1) * w) / 2,
);
// Screen-space clearance keeps the mood clear of flags at every zoom and rotation.
x = Math.min(x - 14, flagLeft - (this.topDown ? 9 : 11) - 4);
if (label.kind === 'city-influence') {
const flagRight = Math.max(...projectedX);
// Anchor by left edge so single- or multi-civ bubbles clear flags at every zoom and rotation.
x = Math.max(x + 14, flagRight + (this.topDown ? 8 : 11));
} else {
const flagLeft = Math.min(...projectedX);
// Screen-space clearance keeps the mood clear of flags at every zoom and rotation.
x = Math.min(x - 14, flagLeft - (this.topDown ? 9 : 11) - 4);
}
}
const edge = label.at
.clone()
@ -562,7 +571,10 @@ export class World {
label.kind === 'strategy'
? Math.min(1.4, Math.hypot((edge.x - v.x) * w, (edge.y - v.y) * h) / 2 / 96)
: 1;
label.node.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px) scale(${scale})`;
label.node.style.transform =
label.kind === 'city-influence'
? `translate(${x}px,${y}px)`
: `translate(-50%, -50%) translate(${x}px,${y}px) scale(${scale})`;
label.node.style.display = v.z > 1 || v.z < -1 ? 'none' : '';
if (label.kind === 'strategy') label.node.style.visibility = 'visible';
}
@ -878,7 +890,7 @@ export class World {
),
);
context.restore();
} else context.fillText(playerSymbol(index, symbols), 32, 33);
} else drawOwnershipSymbol(context, playerSymbol(index, symbols), 32, 14);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
this.textures.add(texture);
@ -1496,18 +1508,52 @@ export class World {
if (this.canPick(city.position)) this.pick(city.position, { kind: 'city', player: player.id });
};
this.bindTileHover(label, city.position);
const ownershipBounds = [ownership.min.x, ownership.max.x].flatMap((bx) =>
[ownership.min.y, ownership.max.y].flatMap((by) =>
[ownership.min.z, ownership.max.z].map((bz) => new THREE.Vector3(bx, by, bz)),
),
);
this.labelHost.append(label);
this.labelPositions.push({
position: city.position,
at: new THREE.Vector3(x, 1.4, z),
node: label,
kind: 'city',
ownershipBounds: [ownership.min.x, ownership.max.x].flatMap((x) =>
[ownership.min.y, ownership.max.y].flatMap((y) =>
[ownership.min.z, ownership.max.z].map((z) => new THREE.Vector3(x, y, z)),
),
),
ownershipBounds,
});
const influencers = cityInfluencers(city, player.id, s.game.players);
if (influencers.length) {
const bubble = document.createElement('button');
bubble.type = 'button';
bubble.className = 'city-influence-bubble';
bubble.dataset.position = city.position;
const summary = cityInfluenceSummary(influencers);
bubble.setAttribute('aria-label', summary);
bubble.title = summary;
this.unitBadges.push(
mount(CityInfluenceBubble, {
target: bubble,
props: {
influencers,
colorBlind: s.colorBlind,
playerColors: s.playerColors ?? [],
playerSymbols: s.playerSymbols ?? [],
},
}),
);
bubble.onclick = () => {
if (this.canPick(city.position)) this.pick(city.position, { kind: 'city', player: player.id });
};
this.bindTileHover(bubble, city.position);
this.labelHost.append(bubble);
this.labelPositions.push({
position: city.position,
at: new THREE.Vector3(x, 1.4, z),
node: bubble,
kind: 'city-influence',
ownershipBounds,
});
}
}
for (const unit of renderedUnits.get(player.id)!) {
const [x, z] = positionXY(unit.position);

View file

@ -1,11 +1,19 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { buildingCivilization, foreignBuildingCivilization } from './building-owner.ts';
import {
buildingCivilization,
cityInfluencers,
cityInfluenceSummary,
emblemInkColor,
foreignBuildingCivilization,
} from './building-owner.ts';
const rome = { id: 4, civilization: 'Rome' };
const greece = { id: 7, civilization: 'Greece' };
const egypt = { id: 9, civilization: 'Egypt' };
const barbarians = { id: 12, civilization: 'Barbarians' };
const players = [rome, greece, barbarians];
const players = [rome, greece, egypt, barbarians];
test('piece ownership uses player IDs, not viewer seat or array index', () => {
assert.equal(buildingCivilization(7, rome, players), 'Greece');
assert.equal(buildingCivilization(4, rome, players), 'Rome');
@ -13,9 +21,66 @@ test('piece ownership uses player IDs, not viewer seat or array index', () => {
assert.equal(foreignBuildingCivilization(7, rome, players), 'Greece');
assert.equal(foreignBuildingCivilization(4, rome, players), undefined);
});
test('missing and invalid owners safely retain host architecture without invented hover ownership', () => {
for (const owner of [undefined, null, -1, 99, '7', NaN]) {
assert.equal(buildingCivilization(owner, rome, players), 'Rome');
assert.equal(foreignBuildingCivilization(owner, rome, players), undefined);
}
});
test('cityInfluencers groups foreign buildings by owner and ignores host buildings, wonders, and invalid IDs', () => {
assert.deepEqual(
cityInfluencers({ city_pieces: { temple: 4, fortress: 4, wonders: ['Pyramids'] } }, rome.id, players),
[],
);
assert.deepEqual(
cityInfluencers(
{ city_pieces: { academy: 7, fortress: 4, port: 7, temple: 7, wonders: ['GreatGardens'] } },
rome.id,
players,
),
[{ owner: 7, civilization: 'Greece', count: 3, buildings: ['Academy', 'Port', 'Temple'] }],
);
// Multi-civ influence sorts by count desc then player order, regardless of city_pieces key order.
assert.deepEqual(
cityInfluencers({ city_pieces: { obelisk: 9, temple: 7, market: 99 } }, rome.id, players),
[
{ owner: 7, civilization: 'Greece', count: 1, buildings: ['Temple'] },
{ owner: 9, civilization: 'Egypt', count: 1, buildings: ['Obelisk'] },
],
);
// Barbarian cities with foreign buildings report influencing civilizations cleanly.
assert.deepEqual(
cityInfluencers({ city_pieces: { temple: 7, fortress: 12 } }, barbarians.id, players),
[{ owner: 7, civilization: 'Greece', count: 1, buildings: ['Temple'] }],
);
assert.deepEqual(cityInfluencers(undefined, rome.id, players), []);
});
test('cityInfluenceSummary formats single, counted, and multi-civilization influence labels', () => {
assert.equal(cityInfluenceSummary([]), '');
assert.equal(
cityInfluenceSummary([{ civilization: 'Greece', count: 1 }]),
'Influenced by Greece',
);
assert.equal(
cityInfluenceSummary([{ civilization: 'Greece', count: 3 }]),
'Influenced by Greece (3)',
);
assert.equal(
cityInfluenceSummary([
{ civilization: 'Greece', count: 1 },
{ civilization: 'Egypt', count: 1 },
]),
'Influenced by Greece, Egypt',
);
});
test('emblemInkColor matches light and dark contrast thresholds', () => {
assert.equal(emblemInkColor('#5086af'), '#fff4dc');
assert.equal(emblemInkColor('#b96c4c'), '#fff4dc');
assert.equal(emblemInkColor('#6d9173'), '#fff4dc');
assert.equal(emblemInkColor('#ae92b6'), '#293b37');
assert.equal(emblemInkColor('#e7d8b5'), '#293b37');
});

View file

@ -1,7 +1,14 @@
import type { Player } from './types';
import type { City, Player } from './types.ts';
type CivilizationOwner = Pick<Player, 'id' | 'civilization'>;
export interface CityInfluencer {
owner: number;
civilization: string;
count: number;
buildings: string[];
}
/** Use the piece owner's normal architecture, including NPCs; tolerate stale owner IDs. */
export function buildingCivilization(
owner: unknown,
@ -19,3 +26,57 @@ export function foreignBuildingCivilization(
): string | undefined {
return owner === cityOwner.id ? undefined : players.find((player) => player.id === owner)?.civilization;
}
/** Group foreign buildings in a player or Barbarian city by influencing player. */
export function cityInfluencers(
city: Pick<City, 'city_pieces'> | null | undefined,
cityOwner: number,
players: readonly CivilizationOwner[],
): CityInfluencer[] {
const byOwner = new Map<number, CityInfluencer>();
for (const [key, owner] of Object.entries(city?.city_pieces ?? {})) {
if (key === 'wonders' || typeof owner !== 'number' || !Number.isFinite(owner) || owner === cityOwner) continue;
const player = players.find((entry) => entry.id === owner);
if (!player) continue;
const building = key[0].toUpperCase() + key.slice(1);
const existing = byOwner.get(owner);
if (existing) {
existing.count++;
existing.buildings.push(building);
} else {
byOwner.set(owner, { owner, civilization: player.civilization, count: 1, buildings: [building] });
}
}
const order = new Map(players.map((player, index) => [player.id, index]));
return [...byOwner.values()].sort(
(a, b) => b.count - a.count || (order.get(a.owner) ?? a.owner) - (order.get(b.owner) ?? b.owner),
);
}
/** Concise accessible summary for hover titles and screen-reader labels. */
export function cityInfluenceSummary(
influencers: readonly Pick<CityInfluencer, 'civilization' | 'count'>[],
): string {
if (!influencers.length) return '';
const summary = influencers
.map((entry) => (entry.count > 1 ? `${entry.civilization} (${entry.count})` : entry.civilization))
.join(', ');
return `Influenced by ${summary}`;
}
function srgbChannel(hexByte: number) {
const value = hexByte / 255;
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
}
/** Match CivilizationFlags luminance contrast so medallion emblems stay legible on any player color. */
export function emblemInkColor(color: string): string {
const hex = color.trim().replace(/^#/, '');
const full = hex.length === 3 ? hex.replace(/./g, '$&$&') : hex;
if (!/^[0-9a-f]{6}$/i.test(full)) return '#fff4dc';
const r = srgbChannel(parseInt(full.slice(0, 2), 16));
const g = srgbChannel(parseInt(full.slice(2, 4), 16));
const b = srgbChannel(parseInt(full.slice(4, 6), 16));
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return luminance > 0.32 ? '#293b37' : '#fff4dc';
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Nybyggere blokeret af hunnernes plyndrere"
"Settlers blocked by Huns’ Raiders": "Nybyggere blokeret af hunnernes plyndrere",
"Influenced by {p0}": "Påvirket af {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Siedler durch die Plünderer der Hunnen blockiert"
"Settlers blocked by Huns’ Raiders": "Siedler durch die Plünderer der Hunnen blockiert",
"Influenced by {p0}": "Beeinflusst von {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Άποικοι μπλοκαρισμένοι από τους Επιδρομείς των Ούννων"
"Settlers blocked by Huns’ Raiders": "Άποικοι μπλοκαρισμένοι από τους Επιδρομείς των Ούννων",
"Influenced by {p0}": "Επηρεάζεται από: {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Settlers blocked by Huns’ Raiders"
"Settlers blocked by Huns’ Raiders": "Settlers blocked by Huns’ Raiders",
"Influenced by {p0}": "Influenced by {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "مهاجران توسط غارتگران هون‌ها مسدود شده‌اند"
"Settlers blocked by Huns’ Raiders": "مهاجران توسط غارتگران هون‌ها مسدود شده‌اند",
"Influenced by {p0}": "تحت نفوذ {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Colons bloqués par les Pillards des Huns"
"Settlers blocked by Huns’ Raiders": "Colons bloqués par les Pillards des Huns",
"Influenced by {p0}": "Influencée par {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "हूणों के हमलावरों द्वारा अवरुद्ध बसने वाले"
"Settlers blocked by Huns’ Raiders": "हूणों के हमलावरों द्वारा अवरुद्ध बसने वाले",
"Influenced by {p0}": "{p0} से प्रभावित",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Coloni bloccati dai Razziatori degli Unni"
"Settlers blocked by Huns’ Raiders": "Coloni bloccati dai Razziatori degli Unni",
"Influenced by {p0}": "Influenzata da {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "훈족의 약탈자에 의해 개척자 차단됨"
"Settlers blocked by Huns’ Raiders": "훈족의 약탈자에 의해 개척자 차단됨",
"Influenced by {p0}": "{p0}의 영향을 받음",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Kolonisten geblokkeerd door de plunderaars van de Hunnen"
"Settlers blocked by Huns’ Raiders": "Kolonisten geblokkeerd door de plunderaars van de Hunnen",
"Influenced by {p0}": "Beïnvloed door {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Osadnicy zablokowani przez najeźdźców Hunów"
"Settlers blocked by Huns’ Raiders": "Osadnicy zablokowani przez najeźdźców Hunów",
"Influenced by {p0}": "Pod wpływem: {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Colonos bloqueados pelos Saqueadores dos Hunos"
"Settlers blocked by Huns’ Raiders": "Colonos bloqueados pelos Saqueadores dos Hunos",
"Influenced by {p0}": "Influenciada por {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Coloniști blocați de Jefuitorii hunilor"
"Settlers blocked by Huns’ Raiders": "Coloniști blocați de Jefuitorii hunilor",
"Influenced by {p0}": "Influențat de {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Поселенцы заблокированы налётчиками гуннов"
"Settlers blocked by Huns’ Raiders": "Поселенцы заблокированы налётчиками гуннов",
"Influenced by {p0}": "Под влиянием: {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "Người định cư bị chặn bởi quân đột kích Hung Nô"
"Settlers blocked by Huns’ Raiders": "Người định cư bị chặn bởi quân đột kích Hung Nô",
"Influenced by {p0}": "Chịu ảnh hưởng bởi {p0}",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠夺者阻止"
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠夺者阻止",
"Influenced by {p0}": "受到{p0}影响",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -5309,5 +5309,7 @@
"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})",
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠奪者阻止"
"Settlers blocked by Huns’ Raiders": "定居者被匈人的掠奪者阻止",
"Influenced by {p0}": "受到{p0}影響",
"{p0} ({p1})": "{p0} ({p1})"
}

View file

@ -0,0 +1,142 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import {
drawOwnershipSymbol,
isStandardOwnershipSymbol,
STANDARD_OWNERSHIP_SYMBOLS,
type OwnershipSymbolCanvas,
} from './ownership-symbol.ts';
function mockCanvas(metrics: {
actualBoundingBoxLeft?: number;
actualBoundingBoxRight?: number;
actualBoundingBoxAscent?: number;
actualBoundingBoxDescent?: number;
} = {}) {
const calls: Array<{ op: string; args: unknown[] }> = [];
const canvas: OwnershipSymbolCanvas = {
fillStyle: '#25372e',
strokeStyle: '#2d392f',
lineWidth: 3,
lineCap: 'butt',
beginPath() {
calls.push({ op: 'beginPath', args: [] });
},
closePath() {
calls.push({ op: 'closePath', args: [] });
},
arc(x, y, radius, startAngle, endAngle) {
calls.push({ op: 'arc', args: [x, y, radius, startAngle, endAngle] });
},
moveTo(x, y) {
calls.push({ op: 'moveTo', args: [x, y] });
},
lineTo(x, y) {
calls.push({ op: 'lineTo', args: [x, y] });
},
fill() {
calls.push({ op: 'fill', args: [] });
},
stroke() {
calls.push({ op: 'stroke', args: [] });
},
fillRect(x, y, w, h) {
calls.push({ op: 'fillRect', args: [x, y, w, h] });
},
save() {
calls.push({ op: 'save', args: [] });
},
restore() {
calls.push({ op: 'restore', args: [] });
},
measureText(text) {
calls.push({ op: 'measureText', args: [text] });
return metrics;
},
fillText(text, x, y) {
calls.push({ op: 'fillText', args: [text, x, y] });
},
};
return { canvas, calls };
}
test('standard color-blind symbols draw centered geometric paths without font fillText', () => {
for (const symbol of STANDARD_OWNERSHIP_SYMBOLS) {
assert.equal(isStandardOwnershipSymbol(symbol), true);
const { canvas, calls } = mockCanvas();
drawOwnershipSymbol(canvas, symbol, 32, 14);
assert.equal(
calls.some((call) => call.op === 'fillText'),
false,
`${symbol} should render via geometric path, not fillText`,
);
assert.equal(
calls.some((call) => call.op === 'fill' || call.op === 'stroke' || call.op === 'fillRect'),
true,
`${symbol} must emit a draw command`,
);
}
// Verify exact symmetry around (32, 32) for circle, square, diamond, plus, and cross.
{
const { canvas, calls } = mockCanvas();
drawOwnershipSymbol(canvas, '●', 32, 14);
const arc = calls.find((call) => call.op === 'arc');
assert.ok(arc);
assert.equal(arc.args[0], 32);
assert.equal(arc.args[1], 32);
}
{
const { canvas, calls } = mockCanvas();
drawOwnershipSymbol(canvas, '■', 32, 14);
const rect = calls.find((call) => call.op === 'fillRect');
assert.ok(rect);
const [x, y, w, h] = rect.args as number[];
assert.equal(x + w / 2, 32);
assert.equal(y + h / 2, 32);
}
{
const { canvas, calls } = mockCanvas();
drawOwnershipSymbol(canvas, '✚', 32, 14);
const rects = calls.filter((call) => call.op === 'fillRect');
assert.equal(rects.length, 2);
for (const rect of rects) {
const [x, y, w, h] = rect.args as number[];
assert.equal(x + w / 2, 32);
assert.equal(y + h / 2, 32);
}
}
{
const { canvas, calls } = mockCanvas();
drawOwnershipSymbol(canvas, '◆', 32, 14);
const points = calls
.filter((call) => call.op === 'moveTo' || call.op === 'lineTo')
.map((call) => call.args as [number, number]);
assert.equal(points.length, 4);
const avgX = points.reduce((sum, [x]) => sum + x, 0) / points.length;
const avgY = points.reduce((sum, [, y]) => sum + y, 0) / points.length;
assert.equal(avgX, 32);
assert.equal(avgY, 32);
}
});
test('non-standard symbols center using actualBoundingBox metrics and fall back safely when unavailable', () => {
assert.equal(isStandardOwnershipSymbol('★'), false);
{
const { canvas, calls } = mockCanvas({
actualBoundingBoxLeft: 14,
actualBoundingBoxRight: 16,
actualBoundingBoxAscent: 19,
actualBoundingBoxDescent: 11,
});
drawOwnershipSymbol(canvas, '★', 32, 14);
const fillText = calls.find((call) => call.op === 'fillText');
assert.deepEqual(fillText?.args, ['★', 31, 36]);
}
{
const { canvas, calls } = mockCanvas({});
drawOwnershipSymbol(canvas, '⬢', 32, 14);
const fillText = calls.find((call) => call.op === 'fillText');
assert.deepEqual(fillText?.args, ['⬢', 32, 32]);
}
});

View file

@ -0,0 +1,114 @@
export const STANDARD_OWNERSHIP_SYMBOLS = ['●', '▲', '■', '◆', '✚', '✕'] as const;
export type StandardOwnershipSymbol = (typeof STANDARD_OWNERSHIP_SYMBOLS)[number];
export interface OwnershipSymbolCanvas {
fillStyle: string | CanvasGradient | CanvasPattern;
strokeStyle: string | CanvasGradient | CanvasPattern;
lineWidth: number;
lineCap: CanvasLineCap;
beginPath(): void;
closePath(): void;
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number): void;
moveTo(x: number, y: number): void;
lineTo(x: number, y: number): void;
fill(): void;
stroke(): void;
fillRect(x: number, y: number, w: number, h: number): void;
save(): void;
restore(): void;
measureText(text: string): {
actualBoundingBoxLeft?: number;
actualBoundingBoxRight?: number;
actualBoundingBoxAscent?: number;
actualBoundingBoxDescent?: number;
};
fillText(text: string, x: number, y: number): void;
}
export function isStandardOwnershipSymbol(symbol: string): symbol is StandardOwnershipSymbol {
return (STANDARD_OWNERSHIP_SYMBOLS as readonly string[]).includes(symbol);
}
/**
* Draw a color-blind ownership symbol dead-center at (center, center) on a 2D canvas.
* Standard symbols use crisp geometric paths so rendering does not depend on system font metrics;
* non-standard symbols (e.g. custom BGS playerSymbols) center using actualBoundingBox metrics.
*/
export function drawOwnershipSymbol(
context: OwnershipSymbolCanvas,
symbol: string,
center = 32,
radius = 14,
): void {
switch (symbol) {
case '●': {
context.beginPath();
context.arc(center, center, radius * 0.96, 0, Math.PI * 2);
context.fill();
return;
}
case '▲': {
context.beginPath();
context.moveTo(center, center - radius);
context.lineTo(center + radius, center + radius * 0.72);
context.lineTo(center - radius, center + radius * 0.72);
context.closePath();
context.fill();
return;
}
case '■': {
const half = radius * 0.86;
context.fillRect(center - half, center - half, half * 2, half * 2);
return;
}
case '◆': {
const r = radius * 1.08;
context.beginPath();
context.moveTo(center, center - r);
context.lineTo(center + r, center);
context.lineTo(center, center + r);
context.lineTo(center - r, center);
context.closePath();
context.fill();
return;
}
case '✚': {
const arm = radius;
const thick = radius * 0.34;
context.fillRect(center - arm, center - thick, arm * 2, thick * 2);
context.fillRect(center - thick, center - arm, thick * 2, arm * 2);
return;
}
case '✕': {
const arm = radius * 0.78;
context.save();
context.strokeStyle = context.fillStyle;
context.lineWidth = radius * 0.52;
context.lineCap = 'round';
context.beginPath();
context.moveTo(center - arm, center - arm);
context.lineTo(center + arm, center + arm);
context.moveTo(center + arm, center - arm);
context.lineTo(center - arm, center + arm);
context.stroke();
context.restore();
return;
}
default: {
const metrics = context.measureText(symbol);
const left = metrics.actualBoundingBoxLeft;
const right = metrics.actualBoundingBoxRight;
const ascent = metrics.actualBoundingBoxAscent;
const descent = metrics.actualBoundingBoxDescent;
const x =
typeof left === 'number' && Number.isFinite(left) && typeof right === 'number' && Number.isFinite(right)
? center + (left - right) / 2
: center;
const y =
typeof ascent === 'number' && Number.isFinite(ascent) && typeof descent === 'number' && Number.isFinite(descent)
? center + (ascent - descent) / 2
: center;
context.fillText(symbol, x, y);
}
}
}

View file

@ -1,3 +1,4 @@
import { cityInfluencers, cityInfluenceSummary } from './building-owner.ts';
import type { Game, Player } from './types.ts';
export function militarySummary(player: Player, position?: string) {
@ -39,7 +40,8 @@ export function strategyTiles(game: Pick<Game, 'map' | 'players'>) {
0,
)
: 0;
return [{ player, city, size, ...forces }];
const influencers = city ? cityInfluencers(city, player.id, game.players) : [];
return [{ player, city, size, influencers, ...forces }];
});
return { position, terrain, occupants };
});
@ -56,6 +58,7 @@ export function strategyDescription(tile: StrategyTile) {
o.player.civilization,
o.city ? (o.city.city_pieces?.fortress != null ? `city size ${o.size}, Fortress` : `city size ${o.size}`) : '',
o.city?.mood_state ?? '',
cityInfluenceSummary(o.influencers),
o.army ? (o.aboard ? `${o.army} army (${o.aboard} aboard)` : `${o.army} army`) : '',
o.ships ? `${o.ships} ships` : '',
o.settlers ? `${o.settlers} settlers` : '',

View file

@ -685,6 +685,150 @@ small {
0 0 0 2px #b5925570,
0 1px 5px #28483d30;
}
.city-influence-bubble,
.city-influence-bubble:disabled {
position: absolute;
left: 0;
top: 0;
translate: 0 -58%;
pointer-events: auto;
opacity: 1;
display: inline-flex;
align-items: center;
padding: 2.5px 3.5px;
border: 1px solid #bfac88;
border-radius: 999px;
background: linear-gradient(180deg, #fffaf0f8 0%, #f5eeddf6 100%);
box-shadow:
0 2px 6px #1e332b3d,
0 1px 0 #ffffffd8 inset;
transition:
box-shadow 0.12s,
background 0.12s;
line-height: 0;
overflow: visible;
}
.city-influence-bubble::before,
.city-influence-bubble::after {
content: '';
position: absolute;
border-radius: 50%;
background: #fbf4e4;
border: 1px solid #bfac88;
box-shadow: 0 1px 2px #1e332b36;
pointer-events: none;
}
.city-influence-bubble::before {
width: 5.5px;
height: 5.5px;
left: -5.5px;
bottom: 2.5px;
}
.city-influence-bubble::after {
width: 3.5px;
height: 3.5px;
left: -10px;
bottom: -0.5px;
}
.city-influence-bubble:disabled {
pointer-events: none;
cursor: default;
}
.city-influence-bubble:hover:not(:disabled) {
background: #fffdf7;
border-color: #b59255;
box-shadow:
0 2px 8px #1e332b45,
0 0 0 1px #b5925544;
}
.city-influence-bubble.selected {
box-shadow:
0 0 0 2px #b5925578,
0 2px 6px #1e332b38;
}
.influence-medallions {
display: inline-flex;
align-items: center;
gap: 3px;
line-height: 0;
}
.influence-medallions.compact {
gap: 2px;
}
.influence-medallion {
position: relative;
display: grid;
place-items: center;
width: 18px;
height: 18px;
border-radius: 50%;
background: var(--medallion-bg);
color: var(--medallion-ink);
box-shadow:
inset 0 0 0 1px #0000001f,
0 0.5px 1px #00000024;
flex-shrink: 0;
}
.influence-medallions.compact .influence-medallion {
width: 15px;
height: 15px;
}
.influence-medallion svg {
stroke-width: 2.3;
}
.influence-count {
position: absolute;
top: -4px;
right: -4px;
min-width: 11px;
height: 11px;
padding: 0 2px;
border-radius: 999px;
display: grid;
place-items: center;
background: #23332f;
color: #fff8e8;
border: 1px solid #fff8e8;
font:
700 8px/1 'DM Sans',
sans-serif;
letter-spacing: -0.02em;
}
.influence-medallions.compact .influence-count {
top: -3.5px;
right: -3.5px;
min-width: 10px;
height: 10px;
font-size: 7.5px;
}
.influence-symbol {
position: absolute;
bottom: -4px;
left: -4px;
width: 11px;
height: 11px;
border-radius: 50%;
display: grid;
place-items: center;
background: #fff8e8;
color: #1f2e2b;
border: 1px solid #23332f48;
font:
700 7px/1 'DM Sans',
sans-serif;
}
.influence-medallions.compact .influence-symbol {
width: 10px;
height: 10px;
font-size: 6.5px;
}
.ownership-symbol-svg {
display: block;
}
.ownership-symbol-glyph {
display: block;
line-height: 1;
}
.unit-map-label,
.unit-map-label:disabled {
position: absolute;
@ -1686,8 +1830,9 @@ small {
border: 2px solid currentColor;
}
.ownership-symbol {
font: 18px system-ui;
line-height: 1;
display: grid;
place-items: center;
font: 18px/1 system-ui;
}
@media (min-width: 1550px) {
.play-layout {
@ -3147,6 +3292,30 @@ small {
width: 14px;
height: 14px;
}
.world-labels.top-down .city-influence-bubble {
padding: 2px 2.5px;
}
.world-labels.top-down .city-influence-bubble::before {
width: 4.5px;
height: 4.5px;
left: -4.5px;
bottom: 2px;
}
.world-labels.top-down .city-influence-bubble::after {
width: 3px;
height: 3px;
left: -8px;
bottom: 0;
}
.world-labels.top-down .city-influence-bubble .influence-medallion {
width: 15px;
height: 15px;
}
.world-labels.top-down .city-influence-bubble .influence-medallion > .civilization-emblem,
.world-labels.top-down .city-influence-bubble .influence-medallion > svg {
width: 11px !important;
height: 11px !important;
}
.map-control-help {
display: flex;
@ -3850,7 +4019,7 @@ small {
margin-left: auto;
white-space: nowrap;
}
.world-labels.collecting :is(.city-map-label:not(.collection-city), .unit-map-label) {
.world-labels.collecting :is(.city-map-label:not(.collection-city), .city-influence-bubble, .unit-map-label) {
display: none !important;
}
@ -4236,6 +4405,9 @@ small {
.world-labels.choosing-pieces .city-map-label {
pointer-events: none;
}
.world-labels.choosing-pieces .city-influence-bubble {
pointer-events: none;
}
@media (max-width: 760px), (max-width: 1000px) and (max-height: 500px) {
.game-shell .action-panel.floating-panel {
@ -5860,6 +6032,40 @@ small {
.strategy-city {
font-size: 15px;
}
.strategy-influence-bubble {
position: relative;
display: inline-flex;
align-items: center;
margin: 3px 0 0 6px;
padding: 1.5px 3px;
border: 1px solid #bfac88;
border-radius: 999px;
background: linear-gradient(180deg, #fffaf0 0%, #f5eedd 100%);
box-shadow: 0 1px 2px #1e332b28;
line-height: 0;
max-width: calc(100% - 6px);
}
.strategy-influence-bubble::before,
.strategy-influence-bubble::after {
content: '';
position: absolute;
border-radius: 50%;
background: #fbf4e4;
border: 1px solid #bfac88;
pointer-events: none;
}
.strategy-influence-bubble::before {
width: 3.5px;
height: 3.5px;
left: -4px;
bottom: 2px;
}
.strategy-influence-bubble::after {
width: 2.5px;
height: 2.5px;
left: -6.5px;
bottom: 0;
}
.strategy-forces {
flex-wrap: wrap;
}
@ -5874,7 +6080,10 @@ small {
font-size: 10px;
}
.strategy-symbol {
display: inline-grid;
place-items: center;
font-size: 14px;
line-height: 1;
}
.strategy-player-forces {
display: flex;