Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances, roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map, alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js. Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push, bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
220 lines
12 KiB
JavaScript
220 lines
12 KiB
JavaScript
'use strict';
|
|
/*
|
|
* Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the
|
|
* tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40
|
|
* chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are
|
|
* implied by the API (only rural areas, incumbent sites and POPs are listed).
|
|
*/
|
|
(function () {
|
|
const { h, icon, openSheet, closeSheet, toast } = UI;
|
|
const R = UpstreamRules;
|
|
const F = UpstreamData.FORMULAS;
|
|
|
|
const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2;
|
|
|
|
// ------------------------------------------------------------------ chunk store
|
|
class Store {
|
|
constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; }
|
|
reset() { this.chunks.clear(); }
|
|
key(i, j) { return i + ',' + j; }
|
|
|
|
// Make sure every chunk touching the rect is loaded and fresh.
|
|
ensure(v, radius) {
|
|
const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK);
|
|
const want = [];
|
|
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
|
|
if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue;
|
|
const c = this.chunks.get(this.key(i, j));
|
|
const now = Date.now();
|
|
if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]);
|
|
}
|
|
// nearest to the view centre first
|
|
want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy));
|
|
for (const [i, j] of want) this.fetch(i, j);
|
|
}
|
|
|
|
async fetch(i, j) {
|
|
const k = this.key(i, j);
|
|
const prev = this.chunks.get(k);
|
|
if (prev && prev.state === 'loading') return;
|
|
if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; }
|
|
const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 };
|
|
rec.state = 'loading';
|
|
this.chunks.set(k, rec);
|
|
this.active++;
|
|
const x0 = i * CHUNK, y0 = j * CHUNK;
|
|
try {
|
|
const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 });
|
|
const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK;
|
|
rec.specials = r.specials.filter(inChunk);
|
|
rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s]));
|
|
rec.towns = r.towns.filter(inChunk);
|
|
rec.state = 'ok'; rec.at = Date.now();
|
|
} catch (e) {
|
|
rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails
|
|
if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); }
|
|
} finally {
|
|
this.active--;
|
|
if (this.onChange) this.onChange();
|
|
}
|
|
}
|
|
|
|
chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); }
|
|
special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; }
|
|
townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; }
|
|
loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; }
|
|
|
|
forEachSpecial(x0, y0, x1, y1, fn) {
|
|
for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s);
|
|
}
|
|
townsInRect(x0, y0, x1, y1) {
|
|
const out = [];
|
|
for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t);
|
|
return out;
|
|
}
|
|
// After a rename the capital on the map must not show a stale name.
|
|
patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); }
|
|
}
|
|
|
|
// ------------------------------------------------------------------ screen
|
|
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
|
|
const store = new Store();
|
|
let infoSheet = null;
|
|
|
|
const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null);
|
|
const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null;
|
|
|
|
function updateCoords() {
|
|
if (!coordsEl || !view) return;
|
|
coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy);
|
|
}
|
|
|
|
function centreOnOwn() {
|
|
const c = App.state.towns.find((t) => t.id === App.state.townId) || capital();
|
|
if (!c) return;
|
|
view.setView(c.x, c.y, 30);
|
|
}
|
|
|
|
function setup() {
|
|
if (ready) return;
|
|
ready = true;
|
|
canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') });
|
|
coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' });
|
|
legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' });
|
|
const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name));
|
|
const controls = h('div', { class: 'map-controls' },
|
|
zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)),
|
|
zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)),
|
|
zoomBtn('locate', App.t('map.centre'), centreOnOwn));
|
|
controls.dataset.role = 'controls';
|
|
box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls);
|
|
|
|
const source = {
|
|
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
|
|
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
|
|
isOwn: (t) => t.owner.id === ownOperatorId(),
|
|
};
|
|
view = new MapRender.MapView(canvas, source, {
|
|
onTap: onTap,
|
|
onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); },
|
|
});
|
|
view.labelFn = (t, own) => (own ? t.name : t.owner.name);
|
|
view.reachTiles = F.ruralReach;
|
|
store.onChange = () => view.invalidate();
|
|
new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box);
|
|
// The camera moves are frequent; keep the coords chip in step cheaply.
|
|
canvas.addEventListener('pointermove', () => updateCoords());
|
|
canvas.addEventListener('wheel', () => updateCoords(), { passive: true });
|
|
drawLegend();
|
|
}
|
|
|
|
function drawLegend() {
|
|
UI.clear(legendEl);
|
|
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
|
|
legendEl.appendChild(item('you', App.t('map.legend.you')));
|
|
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
|
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
|
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
|
}
|
|
|
|
// ------------------------------------------------------------------ tile info
|
|
function onTap(x, y) {
|
|
const w = App.state.world;
|
|
if (!w) return;
|
|
if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return;
|
|
showTile(x, y);
|
|
}
|
|
|
|
function showTile(x, y) {
|
|
view.setSelected(x, y);
|
|
const town = store.townAt(x, y);
|
|
const special = store.special(x, y);
|
|
const known = store.loaded(x, y);
|
|
const type = town ? 'pop' : special ? special.type : 'land';
|
|
const cap = capital();
|
|
const body = [];
|
|
const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value }));
|
|
|
|
if (town) {
|
|
const own = town.owner.id === ownOperatorId();
|
|
body.push(h('div', { class: 'pill-row' },
|
|
own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }),
|
|
town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null,
|
|
town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null));
|
|
body.push(row(App.t('map.info.operator'), town.owner.name));
|
|
body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber)));
|
|
} else if (special && special.type === 'rural') {
|
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) }));
|
|
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
|
|
} else if (special && special.type === 'incumbent') {
|
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
|
|
} else if (!known) {
|
|
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
|
|
} else {
|
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
|
}
|
|
body.push(row('', App.t('map.info.coords', { x, y })));
|
|
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
|
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
|
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
|
}
|
|
const title = town ? town.name : App.t('tile.' + type);
|
|
infoSheet = openSheet({
|
|
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
|
|
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
|
|
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
|
|
});
|
|
}
|
|
|
|
// ------------------------------------------------------------------ screen registration
|
|
App.registerScreen({
|
|
id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true,
|
|
render(container) {
|
|
box = container;
|
|
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
|
|
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
|
|
},
|
|
onShow(params) {
|
|
visible = true;
|
|
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
|
|
setup();
|
|
view.setWorld(App.state.world.mapRadius);
|
|
const apply = () => {
|
|
if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40);
|
|
else if (pendingFocus) { centreOnOwn(); pendingFocus = null; }
|
|
else view.setView(view.cx, view.cy);
|
|
updateCoords();
|
|
};
|
|
// the container was display:none until now: measure after layout
|
|
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
|
|
},
|
|
onHide() { visible = false; closeSheet(); },
|
|
onLang() {
|
|
if (!ready) return;
|
|
canvas.setAttribute('aria-label', App.t('map.label'));
|
|
drawLegend();
|
|
const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre'];
|
|
box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i])));
|
|
},
|
|
});
|
|
}());
|