Compare commits

...

2 Commits

Author SHA1 Message Date
Brian Fertig 09324f5b20 feat(civilization): replace yield text with icon rows and unit chips on city screen
Replace the four-line text yield breakdown with five icon-based rows that draw
total production as icons and show surplus/loss as a signed group. Hovering any
row reveals exact figures and derived facts like growth/starvation timers.

Replace the comma-separated supported units list with wrapped unit chips that
show each unit individually, including veteran status (gold dot) and upkeep
color coding. Chips display a "+N" overflow marker when units exceed the
visible grid.

Extract citySupport() from cityYields() to compute per-unit upkeep in one pass,
ensuring the Shields/Gold rows and unit chips always agree on costs. Add
describeYieldRow() and describeSupportedUnitTooltip() tooltips for the new
visual elements. Add comprehensive headless tests covering icon run logic,
yield identities, government upkeep rules, and tooltip rendering.
2026-07-23 21:09:08 -06:00
Brian Fertig 3122bb2f28 feat(civilization): city screen overhaul with fat-cross map, scrollable builds, and yield tracking
- Add CivilizationCityMap.js: draws the 21-tile fat cross in the city screen
  with terrain, specials, city sprite, pips, borders, units, and veiled tiles
- Replace fixed 28-row build list with a scrollable window; add shield cost
  and turn-estimate annotations per build choice
- Add garrison display: fortified units shown as clickable roundels
- Refactor tileYield() to accept a `notes` array that records each rule's
  delta, enabling accurate tooltips that can never drift from engine math
- Extract paintTerrainDiamond() and specialColor() from CivilizationMapView
  so the city map and main map share identical rendering
- Add cityCentreYield() enforcing the 1-shield/1-trade market-economy floor
- Add cityTileStatus() for consistent worked/idle/taken/offmap classification
- Add describeCityTileTooltip() with terrain title, yield breakdown, missing
  improvement explanations, and status line
- Wire improvementSheet and iconSheet paths in civilization-artwork.json
- Add comprehensive verifyCivilization checks for yield notes, centre floor,
  tile status, tooltips, and build list capacity
2026-07-23 19:21:54 -06:00
12 changed files with 1412 additions and 175 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -10,9 +10,9 @@
],
"terrainSheet": { "key": "civilization-terrain", "path": "assets/images/civilization/civilization-terrain.png", "frameWidth": 128, "frameHeight": 96 },
"resourceSheet": { "key": "civilization-resources", "path": "assets/images/civilization/civilization-resources.png", "frameWidth": 64, "frameHeight": 64 },
"improvementSheet": { "key": "civilization-improvements", "path": null, "frameWidth": 64, "frameHeight": 64 },
"improvementSheet": { "key": "civilization-improvements", "path": "assets/images/civilization/civilization-improvements.png", "frameWidth": 64, "frameHeight": 64 },
"unitSheet": { "key": "civilization-units", "path": "assets/images/civilization/civilization-units.png", "frameWidth": 64, "frameHeight": 96 },
"iconSheet": { "key": "civilization-icons", "path": null, "frameWidth": 48, "frameHeight": 48 },
"iconSheet": { "key": "civilization-icons", "path": "assets/images/civilization/civilization-icons.png", "frameWidth": 48, "frameHeight": 48 },
"citySheets": {
"classic": { "key": "civilization-cities-classic", "path": "assets/images/civilization/civilization-cities-classic.png", "frameWidth": 128, "frameHeight": 96 },
"cyberpunk": { "key": "civilization-cities-cyberpunk", "path": "assets/images/civilization/civilization-cities-cyberpunk.png", "frameWidth": 128, "frameHeight": 96 },

View File

@ -0,0 +1,254 @@
// Civilization — the fat-cross city map drawn in the city screen's lower-right
// quarter: the 21 tiles this city can reach, what's on them, which ones its
// citizens are working, and why the rest are off limits.
//
// This is a small, static, display-only view — not a second CivilizationMapView.
// The main map is a chunked-RenderTexture system built for panning a whole
// world; twenty-one tiles in a modal want plain game objects. What the two DO
// share is the tile art itself (paintTerrainDiamond, specialColor, the frame
// offsets and the city-sprite tier maths), so the inset can never drift from
// the map it is a window onto.
//
// Tiles are drawn front-to-back by (dx + dy) exactly as CivilizationMapView
// orders them, and each tile's overlays (border, pips, units) are drawn with
// that tile rather than in a later pass — so a mountain in front correctly
// occludes the tile behind it through its 32px of frame headroom.
import * as Phaser from 'phaser';
import { COLORS } from '../../config.js';
import * as Logic from './CivilizationLogic.js';
import { shieldGrassAt } from './CivilizationWorldGen.js';
import {
TILE_W, TILE_H, FRAME_H, paintTerrainDiamond, specialColor,
} from './CivilizationMapView.js';
import { describeCityTileTooltip } from './CivilizationTooltips.js';
const FONT = '"Julius Sans One"';
// The fat cross spans 3 tiles either side of centre in iso space, so its art
// is 4 tiles wide and (with the frame headroom) 4 tiles + 32px tall.
export const MAP_W = TILE_W * 4;
export const MAP_H = TILE_H * 4 + (FRAME_H - TILE_H);
const PIP_MAX = 5; // more than this on one tile is unreachable in practice
const PIP_GAP = 7;
const PIP_Y = 9; // below the diamond's centre, clear of the special marker
const DIAMOND = [
[0, -TILE_H / 2], [TILE_W / 2, 0], [0, TILE_H / 2], [-TILE_W / 2, 0],
];
function diamondPath(g) {
g.beginPath();
g.moveTo(DIAMOND[0][0], DIAMOND[0][1]);
for (const [x, y] of DIAMOND.slice(1)) g.lineTo(x, y);
g.closePath();
}
// Draws the map centred so the CITY's own tile sits at (cx, cy). Adds every
// object to `parent` and attaches hover tooltips to the shared `tooltip`.
export function drawCityMap(scene, rules, state, city, parent, tooltip, cx, cy) {
const { world } = state;
const civ = state.civs[city.civ];
const civColor = Phaser.Display.Color.HexStringToColor(civ.color).color;
const human = state.humanIndex;
const tiles = [...Logic.CITY_RADIUS]
.sort(([ax, ay], [bx, by]) => (ax + ay) - (bx + by) || ax - bx);
for (const [dx, dy] of tiles) {
const tx = city.x + dx;
const ty = city.y + dy;
const dcx = cx + (dx - dy) * (TILE_W / 2);
const dcy = cy + (dx + dy) * (TILE_H / 2);
const status = Logic.cityTileStatus(state, city, tx, ty);
if (status.kind === 'offmap') {
const g = scene.add.graphics({ x: dcx, y: dcy });
g.fillStyle(0x05070a, 1);
diamondPath(g);
g.fillPath();
g.lineStyle(1, COLORS.muted, 0.3);
g.strokePath();
parent.add(g);
} else {
drawTerrain(scene, rules, state, parent, world, tx, ty, dcx, dcy);
if (status.kind === 'centre') drawCitySprite(scene, parent, civ, city, dcx, dcy);
else drawSpecial(scene, rules, parent, world, tx, ty, dcx, dcy);
// Unavailable tiles are veiled rather than hidden: the player still sees
// the wheat they can't reach, which is the point of showing it at all.
if (status.kind === 'taken' || status.kind === 'city') {
const veil = scene.add.graphics({ x: dcx, y: dcy });
veil.fillStyle(0x000000, 0.45);
diamondPath(veil);
veil.fillPath();
parent.add(veil);
} else {
drawPips(scene, rules, state, city, parent, tx, ty, dcx, dcy, status.kind === 'centre');
}
drawBorder(scene, parent, dcx, dcy, status.kind, civColor);
drawUnits(scene, rules, state, parent, human, tx, ty, dcx, dcy);
}
// Exact diamond hit area so neighbouring tiles never steal each other's
// hover. Hit-area coordinates are relative to the object's top-left, hence
// the +TILE_W/2 / +TILE_H/2 shift off the DIAMOND points.
const zone = scene.add.zone(dcx, dcy, TILE_W, TILE_H).setInteractive(
new Phaser.Geom.Polygon(DIAMOND.map(([x, y]) => [x + TILE_W / 2, y + TILE_H / 2]).flat()),
Phaser.Geom.Polygon.Contains,
);
tooltip.attachTo(zone, () => describeCityTileTooltip(rules, state, city, tx, ty));
parent.add(zone);
}
drawFooter(scene, rules, state, city, parent, cx, cy);
}
function drawTerrain(scene, rules, state, parent, world, tx, ty, dcx, dcy) {
const idx = Logic.tileIndex(world, tx, ty);
const terr = rules.terrainList[world.terrain[idx]];
const shieldGrass = shieldGrassAt(tx, ty) && world.special[idx] < 0;
if (scene.textures.exists('civilization-terrain')) {
const frame = terr.id === 'grassland' && shieldGrass ? rules.grasslandShieldFrame : terr.frame;
// Same offsets as CivilizationMapView.paintTile: the frame's bottom edge
// is the diamond's bottom vertex, with 32px of headroom above.
parent.add(scene.add.image(dcx - TILE_W / 2, dcy - TILE_H / 2 - (FRAME_H - TILE_H),
'civilization-terrain', frame).setOrigin(0, 0));
return;
}
const g = scene.add.graphics({ x: dcx, y: dcy - TILE_H / 2 });
paintTerrainDiamond(g, terr, shieldGrass);
parent.add(g);
}
function drawSpecial(scene, rules, parent, world, tx, ty, dcx, dcy) {
const idx = Logic.tileIndex(world, tx, ty);
if (world.special[idx] < 0) return;
const spec = rules.specialList[world.special[idx]];
if (scene.textures.exists('civilization-resources')) {
parent.add(scene.add.image(dcx - 32, dcy - TILE_H / 2, 'civilization-resources', spec.frame)
.setOrigin(0, 0));
return;
}
const g = scene.add.graphics({ x: dcx, y: dcy });
g.fillStyle(0xffffff, 0.85);
g.fillCircle(0, -6, 9);
g.fillStyle(specialColor(spec.id), 1);
g.fillCircle(0, -6, 7);
parent.add(g);
}
// Mirrors CivilizationMapView.drawCity's tier/walled frame maths so the inset
// shows the same city the map does.
function drawCitySprite(scene, parent, civ, city, dcx, dcy) {
const tier = city.size >= 13 ? 3 : city.size >= 8 ? 2 : city.size >= 4 ? 1 : 0;
const walled = !!city.buildings.citywalls;
const themeKey = `civilization-cities-${civ.citySheet ?? 'classic'}`;
if (scene.textures.exists(themeKey)) {
parent.add(scene.add.image(dcx, dcy - TILE_H / 2 - (FRAME_H - TILE_H) + 48,
themeKey, walled ? 4 + tier : tier).setOrigin(0.5, 0));
return;
}
const g = scene.add.graphics({ x: dcx, y: dcy });
g.fillStyle(0x6b6255, 1);
for (let i = 0; i <= tier; i += 1) {
const bw = 26 - i * 3;
const bh = 16 + i * 8;
g.fillRect(-24 + i * 16, 4 - bh, bw, bh);
g.fillStyle(0x7d7466, 1);
}
if (walled) {
g.lineStyle(3, 0x9a8866, 1);
g.strokeRect(-34, -14, 68, 22);
}
parent.add(g);
}
// Food/shield/trade marks on the tile itself, so tiles can be compared without
// hovering every one. Sits on a dark pill because the pips have to read against
// desert and ocean alike.
function drawPips(scene, rules, state, city, parent, tx, ty, dcx, dcy, isCentre) {
const out = isCentre
? Logic.cityCentreYield(rules, state, city)
: Logic.tileYield(rules, state, city.civ, city, tx, ty);
const marks = [
...Array(Math.min(PIP_MAX, out.food)).fill('food'),
...Array(Math.min(PIP_MAX, out.shield)).fill('shield'),
...Array(Math.min(PIP_MAX, out.trade)).fill('trade'),
];
if (!marks.length) return;
const g = scene.add.graphics({ x: dcx, y: dcy });
const w = marks.length * PIP_GAP + 6;
g.fillStyle(0x000000, 0.5);
g.fillRoundedRect(-w / 2, PIP_Y - 6, w, 12, 6);
marks.forEach((kind, i) => {
const x = -w / 2 + 3 + PIP_GAP / 2 + i * PIP_GAP;
if (kind === 'food') {
g.fillStyle(0x6fd15f, 1);
g.fillCircle(x, PIP_Y, 2.5);
} else if (kind === 'shield') {
g.fillStyle(0xc9cdd4, 1);
g.fillRect(x - 2.5, PIP_Y - 2.5, 5, 5);
} else {
g.fillStyle(0xe8c84a, 1);
g.fillTriangle(x, PIP_Y - 3, x + 3, PIP_Y + 2.5, x - 3, PIP_Y + 2.5);
}
});
parent.add(g);
}
function drawBorder(scene, parent, dcx, dcy, kind, civColor) {
const g = scene.add.graphics({ x: dcx, y: dcy });
const worked = kind === 'worked' || kind === 'centre';
g.lineStyle(worked ? 3 : 1, worked ? civColor : COLORS.muted, worked ? 1 : 0.45);
diamondPath(g);
g.strokePath();
parent.add(g);
}
// Small civ-coloured roundels rather than the 64x96 unit sprites: at this size
// a real unit frame would cover the tile it is standing on, and the point of
// showing units here is "someone is sitting on my wheat", not unit detail.
function drawUnits(scene, rules, state, parent, human, tx, ty, dcx, dcy) {
if (!state.explored[human]?.[Logic.tileIndex(state.world, tx, ty)]) return;
const units = Logic.unitsAt(state, tx, ty); // already excludes carried units
if (!units.length) return;
const civ = state.civs[units[0].civ];
const color = Phaser.Display.Color.HexStringToColor(civ.color).color;
const g = scene.add.graphics({ x: dcx, y: dcy });
g.fillStyle(color, 0.95);
g.fillCircle(0, -10, 11);
g.lineStyle(2, 0xffffff, 0.85);
g.strokeCircle(0, -10, 11);
parent.add(g);
parent.add(scene.add.text(dcx, dcy - 10, rules.units[units[0].type].abbr, {
fontFamily: FONT, fontSize: '11px', color: '#ffffff', fontStyle: 'bold',
}).setOrigin(0.5));
if (units.length > 1) {
parent.add(scene.add.circle(dcx + 12, dcy - 19, 7, 0x000000, 0.85));
parent.add(scene.add.text(dcx + 12, dcy - 19, `${units.length}`, {
fontFamily: FONT, fontSize: '10px', color: '#ffffff',
}).setOrigin(0.5));
}
}
// Ties the map back to the yields panel on the left. Explicitly "before routes
// and corruption" — those are city-wide, not per-tile, so the numbers here
// would otherwise look wrong next to the panel's.
function drawFooter(scene, rules, state, city, parent, cx, cy) {
const total = Logic.cityCentreYield(rules, state, city);
for (const idx of city.worked) {
const tx = idx % state.world.cols;
const ty = (idx / state.world.cols) | 0;
const out = Logic.tileYield(rules, state, city.civ, city, tx, ty);
total.food += out.food;
total.shield += out.shield;
total.trade += out.trade;
}
parent.add(scene.add.text(cx, cy + TILE_H * 2 + 22,
`Worked ${city.worked.length}/${city.size} tiles · ${total.food} food · ${total.shield} shields · ${total.trade} trade (before routes and corruption)`, {
fontFamily: FONT, fontSize: '16px', color: COLORS.mutedHex,
}).setOrigin(0.5, 0));
}

View File

@ -1,13 +1,174 @@
// Civilization — city detail modal: growth, yields, worked-tile emphasis,
// build queue with buy, buildings, supported units and trade routes.
// Civilization — city detail modal.
//
// Left half: growth, yields, worker emphasis, improvements, supported units,
// trade routes. Right half is split — the scrollable build picker above, and
// the fat-cross city map (CivilizationCityMap.js) below, so the numbers on the
// left have visible land behind them.
import * as Phaser from 'phaser';
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { Tooltip } from '../../ui/Tooltip.js';
import * as Logic from './CivilizationLogic.js';
import { describeUnitTooltip, describeBuildingTooltip, describeSpecialBuildTooltip } from './CivilizationTooltips.js';
import {
describeUnitTooltip, describeBuildingTooltip, describeSpecialBuildTooltip, describeYieldRow,
describeSupportedUnitTooltip,
} from './CivilizationTooltips.js';
import { drawIconRun, hasIcons } from './CivilizationIcons.js';
import { drawCityMap, MAP_H } from './CivilizationCityMap.js';
const FONT = '"Julius Sans One"';
const ROW_H = 38;
// The five yield rows. Each is a label, every point produced drawn as an icon,
// then a gap and the surplus/loss repeated as its own signed group — so "makes
// 5 trade, 2 of it eaten by corruption" is one glance rather than a sentence.
// Deduction groups vanish when there's nothing to lose; food's surplus group
// always renders, because an empty space where the growth number belongs reads
// as a bug rather than as break-even.
// Five rows of this height starting at the y below have to land clear of the
// worker-emphasis buttons at top + 270, or the last row's hover zone clips them.
const YIELD_ROW_H = 27;
const YIELD_TOP = 104;
const TOTAL_CAP = 12; // beyond this a group collapses to "icon xN"
const DELTA_CAP = 8;
const GROUP_GAP = 26;
const LABEL_W = 96;
function drawYields(scene, rules, state, city, yields, parent, tooltip, x, y0) {
// Every sheet in this game is optional (data/civilization-artwork.json), and
// this one was unpainted until recently — the text rows have to keep working.
if (!hasIcons(scene)) {
parent.add(scene.add.text(x, y0, [
`Food ${yields.food} (need ${yields.foodNeed}) surplus ${yields.foodSurplus >= 0 ? '+' : ''}${yields.foodSurplus}`,
`Shields ${yields.shield}${yields.waste ? ` waste −${yields.waste}` : ''}${yields.supportShields ? ` (support −${yields.supportShields})` : ''}`,
`Trade ${yields.trade} corruption −${yields.corruption}${yields.routeTrade ? ` routes +${yields.routeTrade}` : ''}`,
`Gold +${yields.gold} · Science +${yields.science} · Upkeep −${yields.upkeep}`,
].join('\n'), {
fontFamily: FONT, fontSize: '20px', color: COLORS.textHex, lineSpacing: 8,
}));
return;
}
const rows = [
{ id: 'food', label: 'Food', frame: 'food', total: yields.food, delta: yields.foodSurplus, alwaysDelta: true },
{ id: 'shield', label: 'Shields', frame: 'shield', total: yields.grossShield, delta: -(yields.waste + yields.supportShields) },
{ id: 'trade', label: 'Trade', frame: 'trade', total: yields.trade, delta: -yields.corruption },
{ id: 'gold', label: 'Gold', frame: 'gold', total: yields.gold, delta: -(yields.upkeep + yields.supportGold) },
{ id: 'science', label: 'Science', frame: 'beaker', total: yields.science, delta: 0 },
];
rows.forEach((row, i) => {
const cy = y0 + i * YIELD_ROW_H + YIELD_ROW_H / 2;
parent.add(scene.add.text(x, cy, row.label, {
fontFamily: FONT, fontSize: '19px', color: COLORS.mutedHex,
}).setOrigin(0, 0.5));
let cursor = x + LABEL_W;
cursor += drawIconRun(scene, parent, cursor, cy, row.frame, row.total, { cap: TOTAL_CAP });
if (row.delta || row.alwaysDelta) {
cursor += GROUP_GAP;
const positive = row.delta >= 0;
const color = row.delta === 0 ? COLORS.mutedHex : (positive ? '#6fd15f' : COLORS.dangerHex);
if (row.delta === 0) {
const zero = scene.add.text(cursor, cy, '0', {
fontFamily: FONT, fontSize: '19px', color,
}).setOrigin(0, 0.5);
parent.add(zero);
cursor += zero.width;
} else {
cursor += drawIconRun(scene, parent, cursor, cy, row.frame, Math.abs(row.delta), {
cap: DELTA_CAP, sign: positive ? '+' : '−', color, alpha: positive ? 1 : 0.55,
});
}
}
// Icons only means the numbers went away — hovering the whole row brings
// them back, with more detail than the old text lines carried.
const zone = scene.add.zone(x, cy - YIELD_ROW_H / 2, Math.max(cursor - x, LABEL_W + 60), YIELD_ROW_H)
.setOrigin(0, 0).setInteractive();
tooltip.attachTo(zone, () => describeYieldRow(rules, state, city, yields, row.id));
parent.add(zone);
});
}
// Supported units as a wrapped strip of sprite chips instead of a comma-joined
// list of names. Each chip is one unit instance, not a stacked count, because
// two Warriors homed here are genuinely different things — one may be a
// fortified veteran in the city and the other a wounded conscript six tiles
// away, and the tooltip says so. The border tells you at a glance which units
// this city is actually paying for.
const CHIP_W = 40;
const CHIP_H = 50;
const CHIP_STEP_X = 46;
const CHIP_STEP_Y = 56;
const CHIP_ROWS = 2; // 532..644 leaves the trade-routes line at 660 alone
function drawSupportedUnits(scene, rules, state, city, support, parent, tooltip, x, y0) {
if (!support.entries.length) {
parent.add(scene.add.text(x, y0 + 6, '(none)', {
fontFamily: FONT, fontSize: '17px', color: COLORS.mutedHex,
}));
return;
}
const perRow = Math.floor(640 / CHIP_STEP_X);
const slots = perRow * CHIP_ROWS;
const overflow = Math.max(0, support.entries.length - slots);
// One slot goes to the "+N" marker when the strip can't hold everything.
const shown = overflow ? support.entries.slice(0, slots - 1) : support.entries;
const spriteMode = scene.textures.exists('civilization-units');
shown.forEach((entry, i) => {
const cx = x + (i % perRow) * CHIP_STEP_X + CHIP_W / 2;
const cy = y0 + Math.floor(i / perRow) * CHIP_STEP_Y + CHIP_H / 2;
const paid = entry.shield || entry.gold || entry.food;
const box = scene.add.rectangle(cx, cy, CHIP_W, CHIP_H, 0x181510)
.setStrokeStyle(2, paid ? COLORS.danger : COLORS.muted, paid ? 0.9 : 0.6);
parent.add(box);
if (spriteMode) {
parent.add(scene.add.image(cx, cy, 'civilization-units', entry.def.frame)
.setDisplaySize(CHIP_W - 8, CHIP_H - 4));
} else {
parent.add(scene.add.text(cx, cy, entry.def.abbr, {
fontFamily: FONT, fontSize: '15px', color: COLORS.textHex, fontStyle: 'bold',
}).setOrigin(0.5));
}
// Same gold dot the map uses for veterans (see CivilizationMapView).
if (entry.unit.vet) {
parent.add(scene.add.circle(cx + CHIP_W / 2 - 6, cy - CHIP_H / 2 + 6, 4, 0xd4a017)
.setStrokeStyle(1, 0x000000, 0.6));
}
box.setInteractive();
tooltip.attachTo(box, () => describeSupportedUnitTooltip(rules, state, city, entry, support.freeUnits));
});
if (overflow) {
const i = slots - 1;
const cx = x + (i % perRow) * CHIP_STEP_X + CHIP_W / 2;
const cy = y0 + Math.floor(i / perRow) * CHIP_STEP_Y + CHIP_H / 2;
parent.add(scene.add.rectangle(cx, cy, CHIP_W, CHIP_H, 0x181510)
.setStrokeStyle(2, COLORS.muted, 0.6));
parent.add(scene.add.text(cx, cy, `+${overflow + 1}`, {
fontFamily: FONT, fontSize: '16px', color: COLORS.mutedHex,
}).setOrigin(0.5));
}
}
// Right-hand annotation on a build-list row: what the choice costs in shields
// and how long it would take at this city's current output, or the per-turn
// conversion rate for Coinage/Public Works (which never complete).
function buildRowNote(rules, city, yields, choice) {
if (choice.type === 'gold' || choice.type === 'food') {
const spec = Logic.SPECIAL_BUILDS[choice.type];
const gain = Math.floor(yields.shield / spec.den) * spec.num;
return `+${gain} ${choice.type === 'gold' ? 'gold' : 'food'}/turn`;
}
const cost = choice.ruleObj.cost;
if (yields.shield <= 0) return `${cost} shields · ∞`;
const turns = Math.max(1, Math.ceil(cost / yields.shield));
return `${cost} shields · ${turns} turn${turns === 1 ? '' : 's'}`;
}
export function openCityScreen(scene, rules, state, city, onClose) {
const root = scene.add.container(0, 0).setDepth(65);
@ -25,8 +186,17 @@ export function openCityScreen(scene, rules, state, city, onClose) {
root.add(dynamic);
const tooltip = new Tooltip(scene, { depth: 70 });
// The build list's clipping mask is made with add:false, so it isn't a child
// of `root` and won't be swept up by destroy(true) — it's tracked here and
// released on every redraw and on close.
let listMask = null;
const close = () => { tooltip.destroy(); root.destroy(true); onClose(); };
const close = () => {
tooltip.destroy();
listMask?.destroy();
root.destroy(true);
onClose();
};
const closeBtn = new Button(scene, px + W / 2 - 80, py - H / 2 + 40, '✕', close,
{ width: 60, height: 44, fontSize: 22, variant: 'ghost' });
root.add(closeBtn);
@ -58,16 +228,10 @@ export function openCityScreen(scene, rules, state, city, onClose) {
fontFamily: FONT, fontSize: '18px', color: COLORS.textHex,
}));
// Yields breakdown.
const lines = [
`Food ${y.food} (need ${y.foodNeed}) surplus ${y.foodSurplus >= 0 ? '+' : ''}${y.foodSurplus}`,
`Shields ${y.shield}${y.waste ? ` waste −${y.waste}` : ''}${y.supportShields ? ` (support −${y.supportShields})` : ''}`,
`Trade ${y.trade} corruption −${y.corruption}${y.routeTrade ? ` routes +${y.routeTrade}` : ''}`,
`Gold +${y.gold} · Science +${y.science} · Upkeep −${y.upkeep}`,
];
dynamic.add(scene.add.text(left, top + 112, lines.join('\n'), {
fontFamily: FONT, fontSize: '20px', color: COLORS.textHex, lineSpacing: 8,
}));
// Yields breakdown: a label, the whole production drawn as icons, then the
// surplus (or the loss) repeated as its own signed group. Hovering a row
// gives back the exact figures — see describeYieldRow.
drawYields(scene, rules, state, city, y, dynamic, tooltip, left, top + YIELD_TOP);
// Emphasis toggle.
dynamic.add(scene.add.text(left, top + 260, 'Worker emphasis:', {
@ -98,95 +262,35 @@ export function openCityScreen(scene, rules, state, city, onClose) {
}));
// Supported units + routes.
const supported = state.units.filter((u) => u.homeCity === city.id)
.map((u) => rules.units[u.type].name);
dynamic.add(scene.add.text(left, top + 500, `Supported units (${supported.length})`, {
fontFamily: FONT, fontSize: '21px', color: COLORS.accentHex,
}));
dynamic.add(scene.add.text(left, top + 535, supported.length ? supported.join(', ') : '(none)', {
fontFamily: FONT, fontSize: '17px', color: COLORS.textHex,
wordWrap: { width: 640 }, lineSpacing: 5,
}));
const support = Logic.citySupport(rules, state, city);
const upkeepBits = [];
if (support.supportShields) upkeepBits.push(`−${support.supportShields} shields`);
if (support.supportGold) upkeepBits.push(`−${support.supportGold} gold`);
if (support.settlerFood) upkeepBits.push(`−${support.settlerFood} food`);
dynamic.add(scene.add.text(left, top + 500,
`Supported units (${support.entries.length})${upkeepBits.length ? ` ${upkeepBits.join(' ')} per turn` : ''}`, {
fontFamily: FONT, fontSize: '21px', color: COLORS.accentHex,
}));
drawSupportedUnits(scene, rules, state, city, support, dynamic, tooltip, left, top + 532);
const routes = city.routes.map((r) => {
const other = Logic.cityById(state, r.cityId);
return other ? `${other.name} (+${r.amount})` : `(lost city +${r.amount})`;
});
dynamic.add(scene.add.text(left, top + 660, `Trade routes: ${routes.length ? routes.join(', ') : '(none)'}`, {
const routesTxt = scene.add.text(left, top + 660, `Trade routes: ${routes.length ? routes.join(', ') : '(none)'}`, {
fontFamily: FONT, fontSize: '18px', color: COLORS.textHex, wordWrap: { width: 640 },
}));
// --- Build picker (right column)
const rx = px + 60;
const isSpecialBuild = city.build.type === 'gold' || city.build.type === 'food';
if (isSpecialBuild) {
const spec = Logic.SPECIAL_BUILDS[city.build.type];
const gain = Math.floor((city.shieldBox + y.shield) / spec.den) * spec.num;
const unitLabel = city.build.type === 'gold' ? 'gold' : 'food';
dynamic.add(scene.add.text(rx, top + 64,
`Producing: ${spec.name} +${gain} ${unitLabel}/turn`, {
fontFamily: FONT, fontSize: '22px', color: COLORS.textHex,
}));
} else {
const cost = Logic.buildCost(rules, city);
const cur = city.build.type === 'unit' ? rules.units[city.build.id] : rules.buildings[city.build.id];
const shownShields = Math.min(city.shieldBox, cost);
const turns = y.shield > 0 ? Math.max(0, Math.ceil((cost - shownShields) / y.shield)) : '∞';
dynamic.add(scene.add.text(rx, top + 64,
`Building: ${cur.name} ${shownShields}/${cost} shields (${turns} turns)`, {
fontFamily: FONT, fontSize: '22px', color: COLORS.textHex,
}));
const buyPrice = Logic.buyCost(rules, city);
const buyBtn = new Button(scene, rx + 560, top + 120, `BUY (${buyPrice}g)`, () => {
if (Logic.buyBuild(rules, state, city)) redraw();
}, { width: 190, height: 46, fontSize: 18, variant: civ.gold >= buyPrice && !city.boughtThisTurn ? 'solid' : 'ghost' });
dynamic.add(buyBtn);
}
dynamic.add(scene.add.text(rx, top + 108, `Treasury: ${civ.gold} gold`, {
fontFamily: FONT, fontSize: '19px', color: COLORS.goldHex,
}));
// Choices: Coinage/Public Works, then units, then buildings, two columns of rows.
const specialChoices = Object.entries(Logic.SPECIAL_BUILDS)
.map(([type, spec]) => ({ type, id: spec.id, label: spec.name }));
const unitChoices = Logic.availableUnits(rules, state, civ, city)
.map((u) => ({ type: 'unit', id: u.id, label: `${u.name} (${u.cost})`, ruleObj: u }));
const bldChoices = Logic.availableBuildings(rules, state, civ, city)
.map((b) => ({ type: 'building', id: b.id, label: `${b.name} (${b.cost})`, ruleObj: b }));
const choices = [...specialChoices, ...unitChoices, ...bldChoices];
const colW = 330;
const rowH = 36;
const perCol = 14; // leaves room below for the garrison strip
choices.slice(0, perCol * 2).forEach((ch, i) => {
const colX = rx + Math.floor(i / perCol) * (colW + 20);
const rowY = top + 170 + (i % perCol) * rowH;
const active = city.build.type === ch.type && city.build.id === ch.id;
const rect = scene.add.rectangle(colX + colW / 2, rowY, colW, rowH - 4,
active ? 0x3a3222 : 0x181510)
.setStrokeStyle(1, active ? COLORS.gold : COLORS.muted, active ? 1 : 0.5);
const rowColor = ch.type === 'unit' ? '#cfe3ff' : (ch.type === 'building' ? '#ffe9bd' : '#c9f2c0');
const txt = scene.add.text(colX + 10, rowY, ch.label, {
fontFamily: FONT, fontSize: '16px', color: rowColor,
}).setOrigin(0, 0.5);
rect.setInteractive({ useHandCursor: true });
rect.on('pointerdown', () => {
Logic.setBuild(rules, state, city, ch.type, ch.id);
redraw();
});
tooltip.attachTo(rect, () => {
if (ch.type === 'unit') return describeUnitTooltip(rules, ch.ruleObj);
if (ch.type === 'building') return describeBuildingTooltip(rules, ch.ruleObj);
return describeSpecialBuildTooltip(ch.type);
});
dynamic.add(rect);
dynamic.add(txt);
});
dynamic.add(routesTxt);
// Garrison — units fortified here are hidden on the map (see
// CivilizationMapView); clicking one un-fortifies it and closes the city.
// Lives under the left column now that the right half belongs to the build
// picker and the city map.
const garrison = Logic.unitsAt(state, city.x, city.y).filter((u) => u.fortified);
if (garrison.length) {
const gTop = top + 170 + perCol * rowH + 20;
dynamic.add(scene.add.text(rx, gTop, 'Garrison (click to unfortify)', {
// Measured off the routes line rather than a fixed y: a city with three
// trade routes wraps that text onto extra lines.
const gTop = Math.max(top + 700, routesTxt.y + routesTxt.height + 20);
dynamic.add(scene.add.text(left, gTop, 'Garrison (click to unfortify)', {
fontFamily: FONT, fontSize: '16px', color: COLORS.mutedHex,
}));
const boxW = 150;
@ -196,7 +300,7 @@ export function openCityScreen(scene, rules, state, city, onClose) {
garrison.forEach((u, i) => {
const col = i % perRow;
const row = (i / perRow) | 0;
const bx = rx + col * (boxW + gap) + boxW / 2;
const bx = left + col * (boxW + gap) + boxW / 2;
const by = gTop + 30 + row * (boxH + gap) + boxH / 2;
const rect = scene.add.rectangle(bx, by, boxW, boxH, 0x181510)
.setStrokeStyle(2, COLORS.gold, 1);
@ -209,6 +313,134 @@ export function openCityScreen(scene, rules, state, city, onClose) {
dynamic.add(label);
});
}
// --- Right column, upper half: what this city is building, and the full
// scrollable list of everything it could build instead.
const rx = px + 40;
const rW = W / 2 - 80;
const isSpecialBuild = city.build.type === 'gold' || city.build.type === 'food';
if (isSpecialBuild) {
const spec = Logic.SPECIAL_BUILDS[city.build.type];
const gain = Math.floor((city.shieldBox + y.shield) / spec.den) * spec.num;
const unitLabel = city.build.type === 'gold' ? 'gold' : 'food';
dynamic.add(scene.add.text(rx, top + 58,
`Producing: ${spec.name} +${gain} ${unitLabel}/turn`, {
fontFamily: FONT, fontSize: '22px', color: COLORS.textHex,
}));
} else {
const cost = Logic.buildCost(rules, city);
const cur = city.build.type === 'unit' ? rules.units[city.build.id] : rules.buildings[city.build.id];
const shownShields = Math.min(city.shieldBox, cost);
const turns = y.shield > 0 ? Math.max(0, Math.ceil((cost - shownShields) / y.shield)) : '∞';
dynamic.add(scene.add.text(rx, top + 58,
`Building: ${cur.name} ${shownShields}/${cost} shields (${turns} turns)`, {
fontFamily: FONT, fontSize: '22px', color: COLORS.textHex,
}));
const buyPrice = Logic.buyCost(rules, city);
const buyBtn = new Button(scene, rx + rW - 100, top + 104, `BUY (${buyPrice}g)`, () => {
if (Logic.buyBuild(rules, state, city)) redraw();
}, { width: 190, height: 46, fontSize: 18, variant: civ.gold >= buyPrice && !city.boughtThisTurn ? 'solid' : 'ghost' });
dynamic.add(buyBtn);
}
dynamic.add(scene.add.text(rx, top + 96, `Treasury: ${civ.gold} gold`, {
fontFamily: FONT, fontSize: '19px', color: COLORS.goldHex,
}));
dynamic.add(scene.add.text(rx, top + 134, 'WHAT TO BUILD', {
fontFamily: FONT, fontSize: '19px', color: COLORS.accentHex,
}));
// Coinage/Public Works first, then units, then buildings — the whole list,
// scrolled rather than truncated (a fully-teched civ has far more options
// than fit, and anything cut off was simply unbuildable through this UI).
const choices = [
...Object.entries(Logic.SPECIAL_BUILDS).map(([type, spec]) => ({ type, id: spec.id, name: spec.name })),
...Logic.availableUnits(rules, state, civ, city).map((u) => ({ type: 'unit', id: u.id, name: u.name, ruleObj: u })),
...Logic.availableBuildings(rules, state, civ, city).map((b) => ({ type: 'building', id: b.id, name: b.name, ruleObj: b })),
];
const listX = rx;
const listY = top + 160;
const listH = 268;
const contentH = choices.length * ROW_H + 12;
const listBg = scene.add.rectangle(listX + rW / 2, listY + listH / 2, rW, listH, 0x0a0d12)
.setStrokeStyle(2, COLORS.muted, 0.7);
dynamic.add(listBg);
const listLayer = scene.add.container(0, 0);
dynamic.add(listLayer);
listMask?.destroy();
listMask = scene.make.graphics({ add: false });
listMask.fillStyle(0xffffff);
listMask.fillRect(listX, listY, rW, listH);
listLayer.setMask(listMask.createGeometryMask());
const rows = [];
choices.forEach((ch, i) => {
const rowY = listY + 6 + i * ROW_H + ROW_H / 2;
const active = city.build.type === ch.type && city.build.id === ch.id;
const rect = scene.add.rectangle(listX + rW / 2, rowY, rW - 22, ROW_H - 4,
active ? 0x3a3222 : 0x181510)
.setStrokeStyle(1, active ? COLORS.gold : COLORS.muted, active ? 1 : 0.5);
const rowColor = ch.type === 'unit' ? '#cfe3ff' : (ch.type === 'building' ? '#ffe9bd' : '#c9f2c0');
const name = scene.add.text(listX + 22, rowY, ch.name, {
fontFamily: FONT, fontSize: '17px', color: rowColor,
}).setOrigin(0, 0.5);
const note = scene.add.text(listX + rW - 22, rowY, buildRowNote(rules, city, y, ch), {
fontFamily: FONT, fontSize: '15px', color: COLORS.mutedHex,
}).setOrigin(1, 0.5);
rect.setInteractive({ useHandCursor: true });
rect.on('pointerdown', () => {
Logic.setBuild(rules, state, city, ch.type, ch.id);
redraw();
});
tooltip.attachTo(rect, () => {
if (ch.type === 'unit') return describeUnitTooltip(rules, ch.ruleObj);
if (ch.type === 'building') return describeBuildingTooltip(rules, ch.ruleObj);
return describeSpecialBuildTooltip(ch.type);
});
listLayer.add([rect, name, note]);
rows.push({ rect, rowY });
});
// Scrollbar, and the wheel handler scoped to this window rather than the
// whole scene (see the diplomacy chat panel in CivilizationScreens.js).
const maxScroll = Math.max(0, contentH - listH);
let scrollY = 0;
const thumbH = maxScroll ? Math.max(30, listH * (listH / contentH)) : 0;
const thumb = maxScroll
? scene.add.rectangle(listX + rW - 8, listY, 6, thumbH, COLORS.accent, 0.8).setOrigin(0.5, 0)
: null;
if (thumb) dynamic.add(thumb);
// The geometry mask clips pixels, not input: a row scrolled out of the
// window would still swallow hovers over the city map below it, so input
// is toggled per row to match what is actually visible.
const syncRows = () => {
listLayer.y = -scrollY;
for (const r of rows) {
const screenY = r.rowY - scrollY;
r.rect.input.enabled = screenY >= listY && screenY <= listY + listH;
}
if (thumb) thumb.y = listY + (listH - thumbH) * (scrollY / maxScroll);
};
listBg.setInteractive();
listBg.on('wheel', (pointer, dx, dy) => {
scrollY = Phaser.Math.Clamp(scrollY + dy * 0.5, 0, maxScroll);
// A row disabled mid-hover never fires pointerout, so its tooltip would
// hang around over the list.
tooltip.hide();
syncRows();
});
syncRows();
// --- Right column, lower half: the land this city works. The fat cross is
// MAP_W x MAP_H (512x288) of tile art at 1:1 scale — it fits this column
// without resampling, which is why the tiles stay as crisp as on the map.
const mapCx = rx + rW / 2;
const mapCy = top + 630;
dynamic.add(scene.add.text(mapCx, mapCy - MAP_H / 2 - 42, 'THE CITY AND ITS LAND', {
fontFamily: FONT, fontSize: '19px', color: COLORS.accentHex,
}).setOrigin(0.5, 0));
drawCityMap(scene, rules, state, city, dynamic, tooltip, mapCx, mapCy);
}
redraw();

View File

@ -0,0 +1,90 @@
// Civilization — the shared HUD icon sheet (civilization-icons.png).
//
// One owner for the sheet so its frame numbers live in code rather than only in
// sprites.md. First consumer is the city screen's yields block; the HUD, the
// diplomacy mood dots and the spaceship screen are the obvious next ones.
//
// The sheet is optional like every other in data/civilization-artwork.json —
// callers must check hasIcons() and keep a text path for when it is absent.
export const ICON_KEY = 'civilization-icons';
export const ICON_FRAMES = 20; // 480x96 sheet at 48x48 = 10 columns x 2 rows
// Frame map, pinned to the table in sprites.md section 6. Append-only: the
// government entries are also committed to in data/civilization-rules.json as
// governments[].frame, and verifyCivilization cross-checks the two.
export const ICON_FRAME = Object.freeze({
food: 0,
shield: 1,
trade: 2,
gold: 3,
beaker: 4,
pop: 5,
'ss-structural': 6,
'ss-component': 7,
'ss-module': 8,
vet: 9,
'gov-despotism': 10,
'gov-anarchy': 11,
'gov-monarchy': 12,
'gov-communism': 13,
'gov-republic': 14,
'gov-democracy': 15,
'mood-happy': 16,
'mood-idle': 17,
'mood-upset': 18,
});
export function hasIcons(scene) {
return scene.textures.exists(ICON_KEY);
}
// How to draw `count` of something: either that many icons, or — once the run
// would grow the row without bound — a single icon and a multiplier. Pure, so
// the boundary behaviour is checked headlessly in verifyCivilization.
export function iconRun(count, cap) {
const n = Math.max(0, Math.floor(count));
if (n <= cap) return { drawn: n, multiplier: null };
return { drawn: 1, multiplier: n };
}
// Draws one group of icons left to right starting at `x` (icons vertically
// centred on `y`), optionally prefixed by a sign glyph and followed by a "×N"
// when the count overflows the cap. Returns the width consumed so callers can
// place whatever comes next.
//
// `color` tints only the sign and multiplier TEXT, never the icons — these are
// painted, coloured sprites (a wheat sheaf, a coin) and tinting them red would
// just wreck the art. A group that represents something lost is dimmed with
// `alpha` instead, which reads as "this went away" while leaving the icon
// recognisable.
export function drawIconRun(scene, container, x, y, frameName, count, opts = {}) {
const {
size = 18, step = 20, cap = 12, sign = null, color = '#f2ead8', alpha = 1,
font = '"Julius Sans One"',
} = opts;
let cursor = x;
if (sign) {
const glyph = scene.add.text(cursor, y, sign, {
fontFamily: font, fontSize: '19px', color,
}).setOrigin(0, 0.5);
container.add(glyph);
cursor += glyph.width + 5;
}
const { drawn, multiplier } = iconRun(count, cap);
for (let i = 0; i < drawn; i += 1) {
container.add(scene.add.image(cursor + size / 2, y, ICON_KEY, ICON_FRAME[frameName])
.setDisplaySize(size, size).setAlpha(alpha));
cursor += step;
}
if (multiplier !== null) {
const mult = scene.add.text(cursor, y, `×${multiplier}`, {
fontFamily: font, fontSize: '17px', color,
}).setOrigin(0, 0.5);
container.add(mult);
cursor += mult.width + 4;
}
return cursor - x;
}

View File

@ -257,7 +257,14 @@ export function isCoastal(rules, state, city) {
// ---------------------------------------------------------------------------
// Tile yields
export function tileYield(rules, state, civIdx, city, x, y) {
// `notes`, when an array is passed, collects the provenance of the yields —
// one { label, food, shield, trade } entry per contributing rule, each holding
// the delta it actually made. That way a multiplier (farmland) or a penalty
// (despotism) is described as accurately as a flat bonus, and the entries
// always sum to the returned totals — the city screen's tile tooltip reads
// them straight out (see describeCityTileTooltip) instead of re-deriving the
// rules and drifting from them. verifyCivilization asserts the sum.
export function tileYield(rules, state, civIdx, city, x, y, notes = null) {
const { world } = state;
const i = tileIndex(world, x, y);
const terr = rules.terrainList[world.terrain[i]];
@ -265,32 +272,71 @@ export function tileYield(rules, state, civIdx, city, x, y) {
let food = special ? special.food : terr.food;
let shield = special ? special.shield : terr.shield;
let trade = special ? special.trade : terr.trade;
let pf = food;
let ps = shield;
let pt = trade;
if (notes) notes.push({ label: special ? special.name : terr.name, food, shield, trade });
const note = (label) => {
if (!notes || (food === pf && shield === ps && trade === pt)) return;
notes.push({ label, food: food - pf, shield: shield - ps, trade: trade - pt });
pf = food; ps = shield; pt = trade;
};
if (!special && terr.id === 'grassland' && shieldGrassAt(x, y)) shield += 1;
note('Shield grassland');
const imp = world.improvements[i];
if ((imp & IMP.IRRIGATION) && terr.irrigate) food += terr.irrigate;
note('Irrigation');
if ((imp & IMP.MINE) && terr.mine) shield += terr.mine;
note('Mine');
if ((imp & IMP.ROAD) && !terr.water && terr.move === 1) trade += 1;
note('Road');
if ((imp & IMP.RAILROAD) && shield >= 1) shield += 1;
note('Railroad');
if ((imp & IMP.FARMLAND) && city && city.buildings.supermarket) {
food = Math.floor(food * 1.5);
}
note('Farmland (Supermarket)');
if (city) {
if (terr.water && city.buildings.harbor) food += 1;
note('Harbor');
if (terr.water && city.buildings.offshoreplatform) shield += 1;
note('Offshore Platform');
}
const civ = state.civs[civIdx];
const gov = rules.governments[civ.government];
if (gov.tradeBonus && trade >= 1) trade += gov.tradeBonus;
note(`${gov.name} trade bonus`);
if (gov.despotPenalty) {
if (food >= 3) food -= 1;
if (shield >= 3) shield -= 1;
if (trade >= 3) trade -= 1;
}
note(`${gov.name} penalty`);
return { food, shield, trade };
}
// How a tile inside a city's fat cross relates to that city. The city screen's
// map uses it to decide borders and dimming, and its tooltip to explain them,
// so both agree by construction. 'taken'/'city' are the two cases
// autoAssignTiles silently skips below — the reasons a city can look poorer
// than its land suggests.
export function cityTileStatus(state, city, x, y) {
if (!inBounds(state.world, x, y)) return { kind: 'offmap' };
if (x === city.x && y === city.y) return { kind: 'centre' };
const here = cityAt(state, x, y);
if (here) return { kind: 'city', other: here };
const idx = tileIndex(state.world, x, y);
if (city.worked.includes(idx)) return { kind: 'worked' };
for (const other of state.cities) {
if (other.id !== city.id && other.worked.includes(idx)) return { kind: 'taken', other };
}
return { kind: 'idle' };
}
const EMPHASIS_WEIGHTS = {
balanced: { food: 3, shield: 2, trade: 1 },
food: { food: 6, shield: 1, trade: 1 },
@ -323,13 +369,66 @@ export function autoAssignTiles(rules, state, city) {
city.worked = options.slice(0, city.size).map((o) => o.idx);
}
// Per-unit upkeep for everything this city is the home of: which units the
// government's free allowance covers and which cost a shield (or a gold, under
// Democracy), plus the food settlers eat while out in the field. Free units are
// the FIRST combatants in state.units order, so the breakdown has to be
// computed in one pass rather than per unit on demand.
//
// cityYields sums this, and the city screen labels each supported-unit chip
// from the same entries — so a chip can never claim an upkeep the Shields row
// above it doesn't charge.
export function citySupport(rules, state, city) {
const gov = rules.governments[state.civs[city.civ].government];
const entries = [];
let supportShields = 0;
let supportGold = 0;
let settlerFood = 0;
let combatants = 0;
for (const unit of state.units) {
if (unit.homeCity !== city.id) continue;
const def = rules.units[unit.type];
const entry = { unit, def, food: 0, shield: 0, gold: 0 };
if (def.flags.includes('settler')) {
entry.food = gov.settlerFood;
settlerFood += gov.settlerFood;
}
if (def.domain !== 'project' && !def.flags.includes('noncombat')) {
combatants += 1;
if (combatants > gov.freeUnits) {
if (gov.unitUpkeep === 'gold') { entry.gold = 1; supportGold += 1; } else { entry.shield = 1; supportShields += 1; }
}
}
entries.push(entry);
}
return { entries, supportShields, supportGold, settlerFood, freeUnits: gov.freeUnits };
}
// The city's own tile as the city actually counts it: the centre always makes
// at least 1 shield and 1 trade (the market-economy floor — without it a city
// founded on the wrong terrain researches nothing forever). Shared with the
// city screen so the map shows the same number the yields panel does.
export function cityCentreYield(rules, state, city, notes = null) {
const raw = tileYield(rules, state, city.civ, city, city.x, city.y, notes);
const out = { food: raw.food, shield: Math.max(1, raw.shield), trade: Math.max(1, raw.trade) };
if (notes && (out.shield !== raw.shield || out.trade !== raw.trade)) {
notes.push({
label: 'City centre minimum',
food: 0,
shield: out.shield - raw.shield,
trade: out.trade - raw.trade,
});
}
return out;
}
export function cityYields(rules, state, city) {
const civ = state.civs[city.civ];
const gov = rules.governments[civ.government];
const centre = tileYield(rules, state, city.civ, city, city.x, city.y);
const centre = cityCentreYield(rules, state, city);
let food = centre.food;
let shield = Math.max(1, centre.shield); // city tile always makes 1 shield...
let trade = Math.max(1, centre.trade); // ...and 1 trade (the market economy floor)
let shield = centre.shield;
let trade = centre.trade;
for (const idx of city.worked) {
const x = idx % state.world.cols;
const y = (idx / state.world.cols) | 0;
@ -376,23 +475,7 @@ export function cityYields(rules, state, city) {
// aiAggression handles war odds, this is the shield-output lever).
if (!civ.human) shieldMult *= rules.difficulties[state.difficultyId].aiProdBonus;
// Unit support: shields per supported unit beyond the free allowance
// (Democracy pays gold instead), settlers also eat food.
const supported = state.units.filter((u) => u.homeCity === city.id);
let supportShields = 0;
let supportGold = 0;
let settlerFood = 0;
let combatants = 0;
for (const u of supported) {
const def = rules.units[u.type];
if (def.flags.includes('settler')) settlerFood += gov.settlerFood;
if (def.domain === 'project' || def.flags.includes('noncombat')) continue;
combatants += 1;
if (combatants > gov.freeUnits) {
if (gov.unitUpkeep === 'gold') supportGold += 1;
else supportShields += 1;
}
}
const { supportShields, supportGold, settlerFood } = citySupport(rules, state, city);
const grossShield = Math.floor(shield * shieldMult);
// Waste — corruption's production sibling: the same capital-distance decay

View File

@ -35,6 +35,71 @@ const SEL_RING_W = SEL_RING_H * (TILE_W / TILE_H);
const ZOOMS = [0.5, 0.75, 1.0, 1.5, 2.0];
// Draws one terrain tile — filled diamond plus its per-terrain glyphs — into
// `g` at the graphics object's own origin, with the diamond's centre at
// (0, TILE_H / 2). Neither clears nor positions `g`, so callers own both:
// this view stamps it into a chunk RenderTexture, while the city screen's
// fat-cross map (CivilizationCityMap.js) places a Graphics per tile. This is
// the fallback path used when data/civilization-artwork.json has no terrain
// sheet painted; keeping it in one place stops the two views from drifting.
export function paintTerrainDiamond(g, terr, shieldGrass = false) {
const base = Phaser.Display.Color.HexStringToColor(terr.color).color;
const cy = TILE_H / 2;
g.fillStyle(base, 1);
g.beginPath();
g.moveTo(0, cy - TILE_H / 2);
g.lineTo(TILE_W / 2, cy);
g.lineTo(0, cy + TILE_H / 2);
g.lineTo(-TILE_W / 2, cy);
g.closePath();
g.fillPath();
g.lineStyle(1, 0x000000, 0.18);
g.strokePath();
// Simple per-terrain glyphs.
const darker = Phaser.Display.Color.ValueToColor(base).darken(25).color;
const lighter = Phaser.Display.Color.ValueToColor(base).lighten(20).color;
if (terr.id === 'forest' || terr.id === 'jungle') {
g.fillStyle(darker, 1);
for (const [tx, ty] of [[-24, 0], [0, -8], [22, 2]]) {
g.fillTriangle(tx - 9, cy + ty + 8, tx + 9, cy + ty + 8, tx, cy + ty - 12);
}
} else if (terr.id === 'mountains') {
g.fillStyle(darker, 1);
g.fillTriangle(-28, cy + 12, 4, cy + 12, -12, cy - 22);
g.fillTriangle(-4, cy + 14, 30, cy + 14, 13, cy - 16);
g.fillStyle(0xffffff, 0.9);
g.fillTriangle(-16, cy - 14, -8, cy - 14, -12, cy - 22);
} else if (terr.id === 'hills') {
g.fillStyle(darker, 1);
g.fillEllipse(-16, cy + 4, 34, 16);
g.fillEllipse(14, cy + 8, 38, 18);
} else if (terr.id === 'ocean') {
g.lineStyle(2, lighter, 0.7);
for (const [tx, ty] of [[-24, -6], [8, 2], [-8, 10]]) {
g.beginPath();
g.moveTo(tx, cy + ty);
g.lineTo(tx + 14, cy + ty);
g.strokePath();
}
} else if (terr.id === 'swamp') {
g.lineStyle(2, darker, 0.8);
for (const [tx, ty] of [[-20, 4], [4, -4], [18, 8]]) {
g.beginPath();
g.moveTo(tx, cy + ty);
g.lineTo(tx, cy + ty - 8);
g.strokePath();
}
} else if (terr.id === 'desert') {
g.fillStyle(darker, 0.6);
g.fillEllipse(-14, cy + 4, 10, 4);
g.fillEllipse(12, cy - 4, 12, 4);
} else if (terr.id === 'grassland' && shieldGrass) {
g.fillStyle(lighter, 1);
g.fillCircle(18, cy - 6, 5);
}
}
export class CivilizationMapView {
constructor(scene, rules, state, opponentsData, callbacks = {}) {
this.scene = scene;
@ -281,64 +346,8 @@ export class CivilizationMapView {
paintProceduralTile(c, r, terr, x, y) {
const g = this.stamp;
g.clear();
const base = Phaser.Display.Color.HexStringToColor(terr.color).color;
const cy = TILE_H / 2; // stamp-local diamond centre
g.fillStyle(base, 1);
g.beginPath();
g.moveTo(0, cy - TILE_H / 2);
g.lineTo(TILE_W / 2, cy);
g.lineTo(0, cy + TILE_H / 2);
g.lineTo(-TILE_W / 2, cy);
g.closePath();
g.fillPath();
g.lineStyle(1, 0x000000, 0.18);
g.strokePath();
// Simple per-terrain glyphs.
const darker = Phaser.Display.Color.ValueToColor(base).darken(25).color;
const lighter = Phaser.Display.Color.ValueToColor(base).lighten(20).color;
if (terr.id === 'forest' || terr.id === 'jungle') {
g.fillStyle(darker, 1);
for (const [tx, ty] of [[-24, 0], [0, -8], [22, 2]]) {
g.fillTriangle(tx - 9, cy + ty + 8, tx + 9, cy + ty + 8, tx, cy + ty - 12);
}
} else if (terr.id === 'mountains') {
g.fillStyle(darker, 1);
g.fillTriangle(-28, cy + 12, 4, cy + 12, -12, cy - 22);
g.fillTriangle(-4, cy + 14, 30, cy + 14, 13, cy - 16);
g.fillStyle(0xffffff, 0.9);
g.fillTriangle(-16, cy - 14, -8, cy - 14, -12, cy - 22);
} else if (terr.id === 'hills') {
g.fillStyle(darker, 1);
g.fillEllipse(-16, cy + 4, 34, 16);
g.fillEllipse(14, cy + 8, 38, 18);
} else if (terr.id === 'ocean') {
g.lineStyle(2, lighter, 0.7);
for (const [tx, ty] of [[-24, -6], [8, 2], [-8, 10]]) {
g.beginPath();
g.moveTo(tx, cy + ty);
g.lineTo(tx + 14, cy + ty);
g.strokePath();
}
} else if (terr.id === 'swamp') {
g.lineStyle(2, darker, 0.8);
for (const [tx, ty] of [[-20, 4], [4, -4], [18, 8]]) {
g.beginPath();
g.moveTo(tx, cy + ty);
g.lineTo(tx, cy + ty - 8);
g.strokePath();
}
} else if (terr.id === 'desert') {
g.fillStyle(darker, 0.6);
g.fillEllipse(-14, cy + 4, 10, 4);
g.fillEllipse(12, cy - 4, 12, 4);
} else if (terr.id === 'grassland') {
const idx = tileIndex(this.state.world, c, r);
if (shieldGrassAt(c, r) && this.state.world.special[idx] < 0) {
g.fillStyle(lighter, 1);
g.fillCircle(18, cy - 6, 5);
}
}
const idx = tileIndex(this.state.world, c, r);
paintTerrainDiamond(g, terr, shieldGrassAt(c, r) && this.state.world.special[idx] < 0);
this.drawStampAt(g, x, y);
}
@ -1065,7 +1074,7 @@ export class CivilizationMapView {
}
}
function specialColor(id) {
export function specialColor(id) {
const map = {
buffalo: 0x8a5a2a, wheat: 0xe8c84a, pheasant: 0xc06030, silk: 0xe8e8f0,
coal: 0x30302e, wine: 0x7a2050, gold: 0xffd700, iron: 0x8a8a92,

View File

@ -1,6 +1,8 @@
import { COLORS } from '../../config.js';
import {
cityById, cityAt, tileIndex, defenderStrength, unitsOnBoat, IMP, SPECIAL_BUILDS,
tileYield, cityTileStatus, cityCentreYield, sizeCap, cheb,
FOOD_PER_CITIZEN, FOODBOX_PER_SIZE,
} from './CivilizationLogic.js';
// Flavor/ability text for unit flags — data/civilization-rules.json has no
@ -238,6 +240,207 @@ export function describeCityTooltip(rules, civ, opponentsData, city) {
};
}
// Hover tooltip for one tile of a city's fat cross in the city screen. The
// yield breakdown is not re-derived here — tileYield fills a `notes` array as
// it applies each rule, so this can only ever say what the engine actually
// did. IMP bits that changed nothing still get a line, since "why does my road
// give me nothing?" is exactly the question this tooltip exists to answer.
const IMP_BITS = [
['irrigation', IMP.IRRIGATION], ['farmland', IMP.FARMLAND], ['mine', IMP.MINE],
['road', IMP.ROAD], ['railroad', IMP.RAILROAD], ['fortress', IMP.FORTRESS],
];
function yieldDelta({ food, shield, trade }) {
const parts = [];
const add = (n, label) => { if (n) parts.push(`${n > 0 ? '+' : '−'}${Math.abs(n)} ${label}`); };
add(food, 'food');
add(shield, 'shields');
add(trade, 'trade');
return parts.length ? parts.join(', ') : 'nothing';
}
export function describeCityTileTooltip(rules, state, city, x, y) {
const status = cityTileStatus(state, city, x, y);
if (status.kind === 'offmap') {
return {
title: 'Beyond the map',
lines: [{ text: 'The world ends here — this tile can never be worked.', color: COLORS.mutedHex }],
};
}
const { world } = state;
const i = tileIndex(world, x, y);
const terr = rules.terrainList[world.terrain[i]];
const special = world.special[i] >= 0 ? rules.specialList[world.special[i]] : null;
const notes = [];
const out = status.kind === 'centre'
? cityCentreYield(rules, state, city, notes)
: tileYield(rules, state, city.civ, city, x, y, notes);
const lines = [{
text: `Food ${out.food} · Shields ${out.shield} · Trade ${out.trade}`,
color: COLORS.goldHex,
}];
if (status.kind === 'centre') {
lines.push({ text: 'The city centre is always worked, on top of the tiles its citizens work.' });
}
for (const n of notes) lines.push({ text: `• ${n.label}: ${yieldDelta(n)}` });
// Improvements that produced nothing here (a road on hills, a mine on
// grassland, a fortress) get their blurb so the absence is explained.
// Prefix match, not equality: tileYield labels the farmland step
// "Farmland (Supermarket)" to name what made it work.
const labels = notes.map((n) => n.label.toLowerCase());
for (const [id, bit] of IMP_BITS) {
if (!(world.improvements[i] & bit)) continue;
const name = rules.improvements[id]?.name ?? id;
if (labels.some((l) => l.startsWith(name.toLowerCase()))) continue;
const text = IMPROVEMENT_TEXT[id];
lines.push({ text: `• ${name} — no effect here.${text ? ` ${text}` : ''}`, color: COLORS.mutedHex });
}
const civ = state.civs[city.civ];
const STATUS = {
centre: { text: `The heart of ${city.name}`, color: civ.color },
worked: { text: `Worked by ${city.name}`, color: civ.color },
idle: { text: 'Not worked — this city has no citizen to spare for it.', color: COLORS.mutedHex },
taken: { text: `Worked by ${status.other?.name} — one city may work a tile.`, color: COLORS.mutedHex },
city: { text: `${status.other?.name} stands here.`, color: COLORS.mutedHex },
};
lines.push(STATUS[status.kind] ?? STATUS.idle);
return { title: special ? `${special.name} (${terr.name})` : terr.name, lines };
}
// Hover tooltips for the city screen's five icon yield rows. The rows
// themselves are icons only (see CivilizationIcons.js), so these carry the
// exact figures the old text lines used to spell out — plus the derived facts
// the text never had, like how many turns until the city grows or starves.
// `yields` is a Logic.cityYields result; `row` is one of the ids below.
export const YIELD_ROWS = ['food', 'shield', 'trade', 'gold', 'science'];
export function describeYieldRow(rules, state, city, yields, row) {
const civ = state.civs[city.civ];
const gov = rules.governments[civ.government];
const lines = [];
const head = (text) => lines.push({ text, color: COLORS.goldHex });
const bullet = (text, color) => lines.push({ text: `• ${text}`, color });
switch (row) {
case 'food': {
const eaten = city.size * FOOD_PER_CITIZEN;
const settlerFood = yields.foodNeed - eaten;
head(`${yields.food} food from the tiles this city works`);
bullet(`${city.size} citizen${city.size === 1 ? '' : 's'} eat ${eaten}`);
if (settlerFood > 0) bullet(`Settlers in the field eat ${settlerFood}`);
const boxSize = (city.size + 1) * FOODBOX_PER_SIZE;
if (yields.foodSurplus > 0) {
bullet(`Surplus +${yields.foodSurplus} into the food store (${city.foodBox}/${boxSize})`);
const cap = sizeCap(rules, city);
if (city.size >= cap) {
bullet('The store is full — this city cannot grow further without an Aqueduct or Sewer System.', COLORS.dangerHex);
} else {
const turns = Math.max(1, Math.ceil((boxSize - city.foodBox) / yields.foodSurplus));
bullet(`Grows in ${turns} turn${turns === 1 ? '' : 's'}`);
}
} else if (yields.foodSurplus < 0) {
bullet(`Shortfall −${-yields.foodSurplus} — the food store is draining (${city.foodBox}/${boxSize})`, COLORS.dangerHex);
const turns = Math.max(1, Math.ceil(city.foodBox / -yields.foodSurplus) + 1);
bullet(`Starves in ${turns} turn${turns === 1 ? '' : 's'} — a settler is lost first, otherwise a citizen`, COLORS.dangerHex);
} else {
bullet('Break-even: this city is neither growing nor starving.');
}
return { title: 'Food', lines };
}
case 'shield': {
head(`${yields.grossShield} shields produced`);
if (yields.waste) bullet(`Waste −${yields.waste} — distance from your palace`, COLORS.dangerHex);
if (yields.supportShields) bullet(`Unit support −${yields.supportShields} (${gov.name} supports ${gov.freeUnits} free)`, COLORS.dangerHex);
bullet(`${yields.shield} into the build box each turn`);
if (city.buildings.courthouse) bullet('A Courthouse is halving the waste.');
return { title: 'Shields', lines };
}
case 'trade': {
head(`${yields.trade} trade`);
if (yields.routeTrade) bullet(`Trade routes contribute +${yields.routeTrade}`);
if (yields.corruption) {
bullet(`Corruption −${yields.corruption} — distance from your palace`, COLORS.dangerHex);
} else {
bullet('No corruption here.');
}
bullet(`${yields.netTrade} reaches your treasury, split evenly into gold and beakers`);
bullet(`That split gives ${yields.gold} gold and ${yields.science} science after this city's multipliers.`);
return { title: 'Trade', lines };
}
case 'gold': {
head(`+${yields.gold} gold per turn`);
bullet(`Half of this city's ${yields.netTrade} net trade, before building multipliers`);
if (yields.upkeep) bullet(`Building upkeep −${yields.upkeep}/turn`, COLORS.dangerHex);
if (yields.supportGold) bullet(`Unit upkeep −${yields.supportGold}/turn (${gov.name} pays units in gold)`, COLORS.dangerHex);
const net = yields.gold - yields.upkeep - yields.supportGold;
bullet(`Net ${net >= 0 ? `+${net}` : `−${-net}`} gold per turn from this city`,
net < 0 ? COLORS.dangerHex : undefined);
return { title: 'Gold', lines };
}
default: {
head(`+${yields.science} beakers per turn`);
if (gov.noScience) {
bullet(`${gov.name} produces no research at all.`, COLORS.dangerHex);
} else {
bullet(`Half of this city's ${yields.netTrade} net trade — science takes the odd point`);
}
const boosts = Object.keys(city.buildings)
.map((id) => rules.buildings[id])
.filter((b) => b && b.effect === 'science');
for (const b of boosts) bullet(`${b.name} adds +${Math.round(b.value * 100)}%`);
return { title: 'Science', lines };
}
}
}
// Hover tooltip for one of the supported-unit chips in the city screen.
// `entry` is a Logic.citySupport() entry, so what this says an individual unit
// costs is by construction the same arithmetic the Shields and Gold rows are
// showing — not a second opinion about the upkeep rules.
export function describeSupportedUnitTooltip(rules, state, city, entry, freeUnits) {
const { unit, def } = entry;
const gov = rules.governments[state.civs[city.civ].government];
const lines = [
{ text: `Attack ${def.attack} · Defense ${def.defense} · Move ${def.move}`, color: COLORS.goldHex },
];
const dist = cheb(unit.x, unit.y, city.x, city.y);
if (dist === 0) lines.push({ text: '• Stationed in the city' });
else lines.push({ text: `• ${dist} tile${dist === 1 ? '' : 's'} from home` });
if (unit.vet) lines.push({ text: '• Veteran' });
if (unit.fortified) lines.push({ text: '• Fortified' });
if (unit.hp !== undefined && def.hp && unit.hp < def.hp) {
lines.push({ text: `• Damaged — ${unit.hp}/${def.hp} hit points`, color: COLORS.dangerHex });
}
const costs = [];
if (entry.shield) costs.push(`${entry.shield} shield`);
if (entry.gold) costs.push(`${entry.gold} gold`);
if (entry.food) costs.push(`${entry.food} food`);
if (costs.length) {
lines.push({ text: `• Costs ${city.name} ${costs.join(' and ')} per turn`, color: COLORS.dangerHex });
} else if (def.domain === 'project' || def.flags.includes('noncombat')) {
// Noncombat units don't just happen to be free — they never take up one of
// the government's paid-support slots at all.
lines.push({ text: '• Noncombat — never counts against unit support', color: COLORS.mutedHex });
} else {
lines.push({
text: `• Supported free — ${gov.name} supports ${freeUnits} unit${freeUnits === 1 ? '' : 's'} at no cost`,
color: COLORS.mutedHex,
});
}
for (const flag of def.flags ?? []) {
const text = FLAG_TEXT[flag];
if (text) lines.push({ text: `• ${text}` });
}
return { title: def.name, lines };
}
// Hover tooltip for a tech-tree entry: prerequisites (only worth showing
// once — omitted for techs the civ already knows) followed by everything
// the tech unlocks, grouped by kind. `civ` is used only to decide whether

View File

@ -23,6 +23,12 @@ import * as Logic from '../src/games/civilization/CivilizationLogic.js';
import * as AI from '../src/games/civilization/CivilizationAI.js';
import * as Diplo from '../src/games/civilization/CivilizationDiplomacy.js';
import * as Chat from '../src/games/civilization/CivilizationChat.js';
// Pure data module (no Phaser) even though its consumers are UI — the city
// screen's tooltips are checkable headlessly, and worth checking.
import * as Tooltips from '../src/games/civilization/CivilizationTooltips.js';
// Icon frame map + the pure run/overflow maths behind the city screen's yield
// rows (the drawing half needs Phaser, the deciding half doesn't).
import * as Icons from '../src/games/civilization/CivilizationIcons.js';
const QUICK = process.argv.includes('--quick');
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
@ -752,6 +758,366 @@ if (RULES) {
check('idle AI city settles on Coinage or Public Works',
city.build.type === 'gold' || city.build.type === 'food');
}
// --- City-screen data layer (the fat-cross map + its tile tooltips).
//
// The drawing is Phaser and can't run here, but everything it reads can.
// The load-bearing check is the first one: the tooltip explains a tile's
// yields from tileYield's own `notes`, so if those ever stop summing to the
// returned totals the tooltip starts lying.
{
const terrains = ['grassland', 'plains', 'hills', 'mountains', 'forest', 'desert', 'swamp', 'ocean'];
const impSets = [
0, Logic.IMP.ROAD, Logic.IMP.IRRIGATION, Logic.IMP.MINE, Logic.IMP.ROAD | Logic.IMP.RAILROAD,
Logic.IMP.IRRIGATION | Logic.IMP.FARMLAND,
Logic.IMP.IRRIGATION | Logic.IMP.FARMLAND | Logic.IMP.ROAD | Logic.IMP.RAILROAD,
Logic.IMP.MINE | Logic.IMP.ROAD | Logic.IMP.FORTRESS,
];
let sumOk = true;
let labelsOk = true;
let why = '';
for (const terrId of terrains) {
for (const gov of ['despotism', 'republic', 'democracy']) {
for (const imps of impSets) {
for (const withBuildings of [false, true]) {
// Grassland everywhere so the city can be founded, with only the
// measured tile switched to the terrain under test — that keeps
// the city tile's implicit road out of the measurement too.
const st = makeFlatState();
st.civs[0].government = gov;
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 5, 5, null));
if (withBuildings) {
city.buildings.supermarket = true;
city.buildings.harbor = true;
city.buildings.offshoreplatform = true;
}
const tx = 6;
const ty = 5;
const i = Logic.tileIndex(st.world, tx, ty);
st.world.terrain[i] = T(terrId);
st.world.improvements[i] = imps;
if (withBuildings && RULES.specialList.length) st.world.special[i] = 0;
const notes = [];
const out = Logic.tileYield(RULES, st, 0, city, tx, ty, notes);
const sum = notes.reduce((a, n) => ({
food: a.food + n.food, shield: a.shield + n.shield, trade: a.trade + n.trade,
}), { food: 0, shield: 0, trade: 0 });
if (sum.food !== out.food || sum.shield !== out.shield || sum.trade !== out.trade) {
sumOk = false;
why = `${terrId}/${gov}/imp${imps}: notes ${JSON.stringify(sum)} vs ${JSON.stringify(out)}`;
}
if (notes.some((n) => !n.label || (!n.food && !n.shield && !n.trade && notes.indexOf(n) > 0))) {
labelsOk = false;
why = why || `${terrId}/${gov}: empty note`;
}
}
}
}
}
check('tile yield notes sum to the yields they explain', sumOk, why);
check('tile yield notes are labelled and never empty', labelsOk, why);
}
// The city centre's 1-shield/1-trade floor is applied in one place, so the
// map, the tooltip and the yields panel can't disagree about it.
{
// Swamp yields 0 shields and 0 trade, and at move 2 the city tile's
// implicit road adds no trade either — so both floors have to do work.
const st = makeFlatState({ terrain: 'swamp' });
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 5, 5, null));
const raw = Logic.tileYield(RULES, st, 0, city, 5, 5);
const centre = Logic.cityCentreYield(RULES, st, city);
check('city centre never yields under 1 shield / 1 trade',
centre.shield >= 1 && centre.trade >= 1, `${JSON.stringify(centre)}`);
const notes = [];
Logic.cityCentreYield(RULES, st, city, notes);
const sum = notes.reduce((a, n) => ({
shield: a.shield + n.shield, trade: a.trade + n.trade,
}), { shield: 0, trade: 0 });
check('centre floor is itself explained in the breakdown',
sum.shield === centre.shield && sum.trade === centre.trade,
`raw ${JSON.stringify(raw)} centre ${JSON.stringify(centre)} notes ${JSON.stringify(sum)}`);
}
// cityTileStatus drives both the map's borders/dimming and the tooltip's
// closing line — every case a fat cross can actually contain.
{
const st = makeFlatState({ cols: 16, rows: 16 });
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 5, 5, null));
const neighbour = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 8, 5, null));
city.size = 3;
Logic.autoAssignTiles(RULES, st, city);
Logic.autoAssignTiles(RULES, st, neighbour);
const kindAt = (x, yy) => Logic.cityTileStatus(st, city, x, yy).kind;
check('centre tile reads as the city itself', kindAt(5, 5) === 'centre');
check('a tile holding another city is flagged', kindAt(8, 5) === 'city');
const workedIdx = city.worked[0];
check('worked tiles read as worked',
kindAt(workedIdx % st.world.cols, (workedIdx / st.world.cols) | 0) === 'worked');
const takenIdx = neighbour.worked.find((idx) => {
const x = idx % st.world.cols;
const yy = (idx / st.world.cols) | 0;
return Math.max(Math.abs(x - city.x), Math.abs(yy - city.y)) <= 2;
});
if (takenIdx !== undefined) {
check('a neighbour\'s tile inside our radius is flagged as taken',
kindAt(takenIdx % st.world.cols, (takenIdx / st.world.cols) | 0) === 'taken');
}
// Found at the map edge so part of the fat cross falls off the world.
const edge = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 0, 0, null));
check('tiles past the map edge are flagged',
Logic.cityTileStatus(st, edge, -2, 0).kind === 'offmap');
}
// The tooltip itself: title, the yield line, and the right closing status.
{
const st = makeFlatState({ cols: 16, rows: 16 });
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 5, 5, null));
city.size = 2;
Logic.autoAssignTiles(RULES, st, city);
const tip = Tooltips.describeCityTileTooltip(RULES, st, city, 6, 5);
const out = Logic.tileYield(RULES, st, 0, city, 6, 5);
check('tile tooltip is titled with its terrain', tip.title === RULES.terrains.grassland.name);
check('tile tooltip leads with the yields it explains',
tip.lines[0].text === `Food ${out.food} · Shields ${out.shield} · Trade ${out.trade}`,
tip.lines[0].text);
check('tile tooltip closes with a status line', tip.lines.length >= 2
&& /Worked|Not worked|heart of/.test(tip.lines[tip.lines.length - 1].text),
tip.lines[tip.lines.length - 1].text);
check('centre tooltip names the city', /heart of/.test(
Tooltips.describeCityTileTooltip(RULES, st, city, 5, 5).lines.at(-1).text,
));
const off = Tooltips.describeCityTileTooltip(RULES, st, city, -1, 5);
check('off-map tooltip degrades gracefully', off.title === 'Beyond the map' && off.lines.length > 0);
// Every template must resolve — a stray {token} would ship to the player.
let clean = true;
for (const [dx, dy] of Logic.CITY_RADIUS) {
const t = Tooltips.describeCityTileTooltip(RULES, st, city, city.x + dx, city.y + dy);
if (/\{|undefined|NaN/.test(t.title + t.lines.map((l) => l.text).join(''))) clean = false;
}
check('no tile tooltip in the fat cross renders a hole', clean);
}
// The build list used to be sliced to 28 rows; a developed city has more
// options than that, so the scroll window is load-bearing, not decoration.
{
const st = makeFlatState();
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 5, 5, null));
for (const t of RULES.techList) if (!t.repeatable) st.civs[0].known[t.id] = true;
const total = 2 + Logic.availableUnits(RULES, st, st.civs[0], city).length
+ Logic.availableBuildings(RULES, st, st.civs[0], city).length;
check('a fully-teched city offers more builds than the old 28-row cap',
total > 28, `${total} options`);
}
// --- Icon yield rows (CivilizationIcons.js + the city screen's yields block)
{
const cap = 12;
const runs = [
[0, { drawn: 0, multiplier: null }],
[1, { drawn: 1, multiplier: null }],
[cap - 1, { drawn: cap - 1, multiplier: null }],
[cap, { drawn: cap, multiplier: null }],
[cap + 1, { drawn: 1, multiplier: cap + 1 }],
[99, { drawn: 1, multiplier: 99 }],
];
let ok = true;
let why = '';
for (const [n, want] of runs) {
const got = Icons.iconRun(n, cap);
if (got.drawn !== want.drawn || got.multiplier !== want.multiplier) {
ok = false;
why = `iconRun(${n}) = ${JSON.stringify(got)}, wanted ${JSON.stringify(want)}`;
}
if (got.drawn > cap) { ok = false; why = `iconRun(${n}) drew ${got.drawn} > cap`; }
}
check('iconRun collapses to a multiplier exactly past the cap', ok, why);
check('iconRun never draws a negative or fractional run', (() => {
const a = Icons.iconRun(-5, cap);
const b = Icons.iconRun(3.7, cap);
return a.drawn === 0 && a.multiplier === null && b.drawn === 3;
})());
// The frame map is duplicated in sprites.md and, for governments, in the
// rules JSON. Keep all three honest.
check('every icon frame exists on the 480x96 @ 48x48 sheet',
Object.values(Icons.ICON_FRAME).every((f) => Number.isInteger(f) && f >= 0 && f < Icons.ICON_FRAMES));
check('icon frames are unique',
new Set(Object.values(Icons.ICON_FRAME)).size === Object.keys(Icons.ICON_FRAME).length);
check('government icon frames agree with governments[].frame in the rules',
RULES.governmentList.every((g) => Icons.ICON_FRAME[`gov-${g.id}`] === g.frame),
RULES.governmentList.map((g) => `${g.id}:${g.frame}/${Icons.ICON_FRAME[`gov-${g.id}`]}`).join(' '));
}
// Each row draws a total and then a deduction as though these identities
// hold. If cityYields is ever reworked they must fail here, rather than the
// display quietly showing the wrong number of icons.
{
let ok = true;
let why = '';
for (const govId of ['despotism', 'monarchy', 'communism', 'republic', 'democracy']) {
for (const size of [1, 4, 12]) {
for (const extras of [false, true]) {
const st = makeFlatState({ cols: 24, rows: 24 });
st.civs[0].government = govId;
const capital = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 2, 2, null));
capital.buildings.palace = true;
// A second city far from the palace, so waste and corruption bite.
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 18, 18, null));
city.size = size;
if (extras) {
city.buildings.courthouse = true;
city.buildings.marketplace = true;
city.buildings.library = true;
for (let k = 0; k < 6; k += 1) Logic.spawnUnit(RULES, st, 0, 'warriors', 18, 18, city.id);
Logic.spawnUnit(RULES, st, 0, 'settlers', 18, 17, city.id);
}
Logic.autoAssignTiles(RULES, st, city);
const y = Logic.cityYields(RULES, st, city);
const label = `${govId}/size${size}${extras ? '/extras' : ''}`;
if (y.foodSurplus !== y.food - y.foodNeed) { ok = false; why = `${label}: food`; }
if (y.shield !== Math.max(0, y.grossShield - y.waste - y.supportShields)) { ok = false; why = `${label}: shields`; }
if (y.netTrade !== y.trade - y.corruption) { ok = false; why = `${label}: trade`; }
if (y.waste > y.grossShield || y.corruption > y.trade) { ok = false; why = `${label}: loss exceeds output`; }
if ([y.food, y.grossShield, y.trade, y.gold, y.science].some((v) => v < 0 || !Number.isInteger(v))) {
ok = false;
why = `${label}: non-integer or negative total`;
}
}
}
}
check('yield rows can draw total-minus-loss without lying about the engine', ok, why);
}
// describeYieldRow gives the numbers back that the icons-only rows drop.
{
const build = ({ govId = 'despotism', size = 3, starve = false, democracy = false } = {}) => {
// Bare mountains grow nothing, so a city of any size on them starves no
// matter how autoAssignTiles reshuffles its citizens.
const st = makeFlatState({ cols: 24, rows: 24, terrain: starve ? 'mountains' : 'grassland' });
st.civs[0].government = democracy ? 'democracy' : govId;
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 12, 12, null));
city.size = starve ? 6 : size;
if (starve) city.foodBox = 5;
if (democracy) for (let k = 0; k < 5; k += 1) Logic.spawnUnit(RULES, st, 0, 'warriors', 12, 12, city.id);
Logic.autoAssignTiles(RULES, st, city);
return { st, city, y: Logic.cityYields(RULES, st, city) };
};
const cases = [
['ordinary city', build()],
['size-1 city', build({ size: 1 })],
['starving city', build({ starve: true })],
['anarchy (no science)', build({ govId: 'anarchy' })],
['democracy (gold unit upkeep)', build({ democracy: true })],
];
let ok = true;
let why = '';
for (const [label, { st, city, y }] of cases) {
for (const row of Tooltips.YIELD_ROWS) {
const tip = Tooltips.describeYieldRow(RULES, st, city, y, row);
const blob = `${tip.title}${tip.lines.map((l) => l.text).join('')}`;
if (!tip.title || !tip.lines.length) { ok = false; why = `${label}/${row}: empty`; }
if (/\{|undefined|NaN|Infinity/.test(blob)) { ok = false; why = `${label}/${row}: ${blob}`; }
}
}
check('every yield row tooltip renders for every kind of city', ok, why);
const { st, city, y } = build({ starve: true });
const food = Tooltips.describeYieldRow(RULES, st, city, y, 'food');
check('a starving city is told how long it has',
y.foodSurplus < 0 && food.lines.some((l) => /Starves in \d+ turn/.test(l.text)),
food.lines.map((l) => l.text).join(' | '));
const growing = build();
const growTip = Tooltips.describeYieldRow(RULES, growing.st, growing.city, growing.y, 'food');
check('a growing city is told when it grows',
growing.y.foodSurplus > 0 && growTip.lines.some((l) => /Grows in \d+ turn/.test(l.text)),
growTip.lines.map((l) => l.text).join(' | '));
}
// --- Supported-unit chips. Each chip states what that one unit costs, so
// the per-entry costs have to add up to the totals the Shields/Gold rows
// charge — otherwise the strip and the rows above it disagree on screen.
{
const stage = (govId) => {
const st = makeFlatState({ cols: 20, rows: 20 });
st.civs[0].government = govId;
const city = Logic.foundCity(RULES, st, Logic.spawnUnit(RULES, st, 0, 'settlers', 8, 8, null));
for (let k = 0; k < 5; k += 1) Logic.spawnUnit(RULES, st, 0, 'warriors', 8, 8, city.id);
Logic.spawnUnit(RULES, st, 0, 'settlers', 9, 8, city.id); // eats food, never shields
Logic.spawnUnit(RULES, st, 0, 'explorer', 9, 9, city.id); // noncombat, always free
Logic.spawnUnit(RULES, st, 0, 'warriors', 8, 8, null); // homed nowhere — not ours
return { st, city, sup: Logic.citySupport(RULES, st, city), y: Logic.cityYields(RULES, st, city) };
};
let ok = true;
let why = '';
for (const govId of RULES.governmentList.map((g) => g.id)) {
const { sup, y, city } = stage(govId);
const sum = (k) => sup.entries.reduce((a, e) => a + e[k], 0);
if (sum('shield') !== sup.supportShields) { ok = false; why = `${govId}: shield entries`; }
if (sum('gold') !== sup.supportGold) { ok = false; why = `${govId}: gold entries`; }
if (sum('food') !== sup.settlerFood) { ok = false; why = `${govId}: food entries`; }
if (y.supportShields !== sup.supportShields || y.supportGold !== sup.supportGold) {
ok = false;
why = `${govId}: cityYields disagrees with citySupport`;
}
if (y.foodNeed !== city.size * Logic.FOOD_PER_CITIZEN + sup.settlerFood) {
ok = false;
why = `${govId}: settler food missing from foodNeed`;
}
if (sup.entries.some((e) => e.shield && e.gold)) { ok = false; why = `${govId}: charged twice`; }
}
check('supported-unit chips add up to the upkeep the city is charged', ok, why);
// Only the first `freeUnits` COMBATANTS ride free, in state.units order.
{
const { sup } = stage('despotism'); // freeUnits 3, shield upkeep
const combatants = sup.entries.filter((e) => e.def.domain !== 'project'
&& !e.def.flags.includes('noncombat'));
const freeCount = combatants.filter((e) => !e.shield && !e.gold).length;
check('the free allowance covers the first combatants only',
freeCount === 3 && combatants.slice(0, 3).every((e) => !e.shield)
&& combatants.slice(3).every((e) => e.shield === 1),
`${freeCount} free of ${combatants.length}`);
check('noncombat and settler units never cost shields',
sup.entries.filter((e) => e.def.flags.includes('noncombat')).every((e) => !e.shield && !e.gold));
check('settlers in the field eat food',
sup.entries.some((e) => e.def.flags.includes('settler') && e.food > 0));
}
{
const { sup } = stage('democracy'); // pays units in gold, 0 free
check('Democracy charges gold for units, not shields',
sup.supportGold > 0 && sup.supportShields === 0, `${sup.supportGold}g/${sup.supportShields}s`);
}
// Every chip's tooltip must render — including the wounded, the veteran,
// the fortified and the far-from-home.
{
const { st, city, sup } = stage('monarchy');
sup.entries[1].unit.vet = true;
sup.entries[2].unit.fortified = true;
sup.entries[3].unit.hp = 3;
let clean = true;
let bad = '';
for (const entry of sup.entries) {
const tip = Tooltips.describeSupportedUnitTooltip(RULES, st, city, entry, sup.freeUnits);
const blob = `${tip.title}${tip.lines.map((l) => l.text).join('')}`;
if (!tip.title || tip.lines.length < 2 || /\{|undefined|NaN/.test(blob)) { clean = false; bad = blob; }
}
check('every supported-unit tooltip renders', clean, bad);
const vetTip = Tooltips.describeSupportedUnitTooltip(RULES, st, city, sup.entries[1], sup.freeUnits);
check('a veteran chip says so', vetTip.lines.some((l) => l.text.includes('Veteran')));
const paid = sup.entries.find((e) => e.shield || e.gold);
const paidTip = Tooltips.describeSupportedUnitTooltip(RULES, st, city, paid, sup.freeUnits);
check('a chip that costs upkeep names the cost',
paidTip.lines.some((l) => /Costs .* per turn/.test(l.text)),
paidTip.lines.map((l) => l.text).join(' | '));
const free = sup.entries.find((e) => !e.shield && !e.gold && !e.food);
const freeTip = Tooltips.describeSupportedUnitTooltip(RULES, st, city, free, sup.freeUnits);
check('a free chip explains the allowance',
freeTip.lines.some((l) => /Supported free/.test(l.text)));
}
}
}
// ---------------------------------------------------------------------------