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
118 lines
6.5 KiB
JavaScript
118 lines
6.5 KiB
JavaScript
'use strict';
|
|
/*
|
|
* Read models. Every read first catches the event queue up to now, so what a player sees is never stale by an
|
|
* overdue event. Reads never write (settling is only done by commands and events).
|
|
*/
|
|
const R = require('../public/js/rules.js');
|
|
const D = require('../public/js/data.js');
|
|
const { GameError } = require('./errors');
|
|
const { loadWorld, townFromRow, pendingBuilds } = require('./state');
|
|
const { allianceBrief } = require('./alliances');
|
|
|
|
function createQueries({ db, clock, scheduler }) {
|
|
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
|
|
|
function worldView(w) {
|
|
return { id: w.id, name: w.name, speed: w.speed, mapRadius: w.map_radius, seed: w.seed, startAt: w.start_at, endAt: w.end_at, status: w.status, preset: w.preset };
|
|
}
|
|
|
|
function me(userId) {
|
|
const now = fresh();
|
|
const user = db.get('SELECT id, username, created_at FROM users WHERE id = ?', userId);
|
|
if (!user) throw new GameError('unauthorized');
|
|
const operators = db.all('SELECT * FROM operators WHERE user_id = ? ORDER BY id', userId).map((o) => {
|
|
const world = loadWorld(db, o.world_id);
|
|
const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id)
|
|
.map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital }));
|
|
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, alliance: allianceBrief(db, o.alliance_id), protectionUntil: o.protection_until, world: worldView(world), towns };
|
|
});
|
|
return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators };
|
|
}
|
|
|
|
function planView(p) {
|
|
return { ok: p.ok, code: p.ok ? null : p.code, toLevel: p.toLevel, cost: p.cost, durationMs: p.durationMs, missing: p.missing || [] };
|
|
}
|
|
|
|
// Full POP state for its owner.
|
|
function town(userId, townId) {
|
|
const now = fresh();
|
|
const row = db.get('SELECT t.* FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?', townId, userId);
|
|
if (!row) throw new GameError('not_found', { what: 'town' });
|
|
const world = loadWorld(db, row.world_id);
|
|
const t = townFromRow(db, row, world);
|
|
const pending = pendingBuilds(db, t.id);
|
|
const cur = R.resourcesAt(t, now);
|
|
const rates = cur.rates;
|
|
const resources = {};
|
|
for (const r of D.RESOURCES) resources[r] = { amount: cur.amounts[r], rate: rates[r], cap: cur.caps[r] };
|
|
const power = { out: rates.powerOut, draw: rates.powerDraw, net: rates.powerNet, buffer: cur.amounts.battery, bufferCap: cur.caps.battery, bufferRate: rates.powerNet * world.speed, online: R.unitsOnline(t, now) };
|
|
|
|
const buildings = [];
|
|
const entry = (key, type, level) => {
|
|
const plan = R.buildPlan(t, key, now, pending);
|
|
const def = D.BUILDINGS[type];
|
|
buildings.push({ key, type, kind: def.kind, level, maxLevel: def.maxLevel, next: planView(plan) });
|
|
};
|
|
for (let i = 1; i <= D.FIELD_SLOTS; i++) { const k = 'f' + i; if (t.buildings[k]) entry(k, t.buildings[k].type, t.buildings[k].level); }
|
|
for (const type of Object.keys(D.BUILDINGS)) {
|
|
const def = D.BUILDINGS[type];
|
|
if (def.kind !== 'infra') continue;
|
|
if (def.special && !t.buildings[type]) continue;
|
|
entry(type, type, t.buildings[type] ? t.buildings[type].level : 0);
|
|
}
|
|
const queue = pending.map((p) => ({ id: p.id, key: p.key, type: p.type, toLevel: p.toLevel, startedAt: p.startedAt, dueAt: p.dueAt }));
|
|
const loyalty = R.loyaltyAt(t.loyalty, t.loyaltyAt, now, world.speed);
|
|
return {
|
|
serverTime: now,
|
|
town: {
|
|
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: t.isCapital, ownerId: t.ownerId, worldId: t.worldId,
|
|
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
|
|
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
|
|
bonus: t.bonus,
|
|
military: require('./military/views').townMilitary(db, t, now, world),
|
|
},
|
|
};
|
|
}
|
|
|
|
// Map viewport: everything non-trivial inside the square (x±r, y±r). Land tiles are implied (not listed).
|
|
function map(userId, { worldId, x, y, r }) {
|
|
const now = fresh();
|
|
let world;
|
|
if (worldId !== undefined) world = loadWorld(db, worldId);
|
|
else {
|
|
const op = db.get('SELECT world_id FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
|
|
world = op ? loadWorld(db, op.world_id) : null;
|
|
}
|
|
if (!world) throw new GameError('not_found', { what: 'world' });
|
|
if (!db.get('SELECT 1 AS x FROM operators WHERE user_id = ? AND world_id = ?', userId, world.id)) throw new GameError('not_found', { what: 'world' });
|
|
const rad = world.map_radius;
|
|
r = Math.min(r, 40);
|
|
const x0 = Math.max(-rad, x - r), x1 = Math.min(rad, x + r), y0 = Math.max(-rad, y - r), y1 = Math.min(rad, y + r);
|
|
const specials = [];
|
|
for (let yy = y0; yy <= y1; yy++) {
|
|
for (let xx = x0; xx <= x1; xx++) {
|
|
const t = R.tileAt(world.seed, rad, xx, yy);
|
|
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
|
}
|
|
}
|
|
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, a.tag AS atag, a.name AS aname, o.protection_until AS prot
|
|
FROM towns t JOIN operators o ON o.id = t.owner_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
|
|
world.id, x0, x1, y0, y1).map((t) => ({
|
|
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital,
|
|
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, alliance: t.ally ? { id: t.ally, tag: t.atag, name: t.aname } : null, protected: t.prot > now },
|
|
}));
|
|
return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns };
|
|
}
|
|
|
|
function notifications(userId, { after, limit }) {
|
|
const now = fresh();
|
|
const rows = db.all('SELECT id, type, payload, created_at, read_at, world_id FROM notifications WHERE user_id = ? AND id > ? ORDER BY id LIMIT ?', userId, after || 0, (limit || 50) + 1);
|
|
const more = rows.length > (limit || 50);
|
|
const items = rows.slice(0, limit || 50).map((n) => ({ id: n.id, type: n.type, worldId: n.world_id, payload: JSON.parse(n.payload), createdAt: n.created_at, readAt: n.read_at }));
|
|
return { serverTime: now, items, next: more ? items[items.length - 1].id : null };
|
|
}
|
|
|
|
return { me, town, map, notifications, worldView };
|
|
}
|
|
|
|
module.exports = { createQueries };
|