'use strict'; /* * Data helpers for units, reinforcements, research and operators, shared by the military commands, events and views. * Units are always { unitId: count }. Always settle() a town before changing its units: unit power draw is part of its * rates (state.unitDraw reads town_units and stationed). */ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const { loadTown } = require('../state'); function homeUnits(db, townId) { const out = {}; for (const r of db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) out[r.unit] = r.count; return out; } function setHomeUnit(db, townId, unit, count) { if (count > 0) db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, unit, count); else db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', townId, unit); } function addHome(db, townId, units) { const cur = homeUnits(db, townId); for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, (cur[k] || 0) + units[k]); } // Removes `units` from home; throws not_enough_units when the town does not have them (callers check first). function removeHome(db, townId, units) { const cur = homeUnits(db, townId); for (const k of Object.keys(units || {})) { if (!(units[k] > 0)) continue; if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] }); } for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, cur[k] - units[k]); } // Reinforcements standing in a host town: [{ ownerTownId, units }] grouped by the POP they belong to. function hostedGroups(db, hostTownId) { const by = new Map(); for (const r of db.all('SELECT owner_town_id, unit, count FROM stationed WHERE host_town_id = ? ORDER BY owner_town_id, unit', hostTownId)) { if (!by.has(r.owner_town_id)) by.set(r.owner_town_id, {}); by.get(r.owner_town_id)[r.unit] = r.count; } return Array.from(by, ([ownerTownId, units]) => ({ ownerTownId, units })); } // Units of owner_town_id's operator standing in other POPs: [{ hostTownId, units }]. function awayGroups(db, ownerTownId) { const by = new Map(); for (const r of db.all('SELECT host_town_id, unit, count FROM stationed WHERE owner_town_id = ? ORDER BY host_town_id, unit', ownerTownId)) { if (!by.has(r.host_town_id)) by.set(r.host_town_id, {}); by.get(r.host_town_id)[r.unit] = r.count; } return Array.from(by, ([hostTownId, units]) => ({ hostTownId, units })); } function stationedOf(db, hostTownId, ownerTownId) { const out = {}; for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', hostTownId, ownerTownId)) out[r.unit] = r.count; return out; } function setStationed(db, hostTownId, ownerTownId, unit, count) { if (count > 0) db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (host_town_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', hostTownId, ownerTownId, unit, count); else db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ? AND unit = ?', hostTownId, ownerTownId, unit); } function addStationed(db, hostTownId, ownerTownId, units) { const cur = stationedOf(db, hostTownId, ownerTownId); for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, (cur[k] || 0) + units[k]); } function removeStationed(db, hostTownId, ownerTownId, units) { const cur = stationedOf(db, hostTownId, ownerTownId); for (const k of Object.keys(units || {})) { if (!(units[k] > 0)) continue; if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] }); } for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, cur[k] - units[k]); } // Research levels of a POP as { 'unit:stat': level }. function researchLevels(db, townId) { const out = {}; for (const r of db.all('SELECT unit, stat, level FROM town_research WHERE town_id = ?', townId)) out[R.researchKey(r.unit, r.stat)] = r.level; return out; } // Snapshot of the research of `townId` for the unit types in `units` (stored on a movement at departure). function researchSnapshot(db, townId, units) { const all = researchLevels(db, townId); const out = {}; for (const u of Object.keys(units)) for (const stat of D.RESEARCH.stats) { const k = R.researchKey(u, stat); if (all[k]) out[k] = all[k]; } return out; } // Validates and normalises the `units` object of a request: known ids, whole numbers >= 0, zeros dropped. function cleanUnits(raw) { if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new GameError('validation_failed', { errors: [{ path: 'units', message: 'must be an object' }] }); const out = {}; for (const k of Object.keys(raw)) { if (!R.unitDef(k)) throw new GameError('unknown_unit', { unit: k }); const n = raw[k]; if (!Number.isInteger(n) || n < 0 || n > 1e7) throw new GameError('validation_failed', { errors: [{ path: 'units.' + k, message: 'must be a whole number >= 0' }] }); if (n > 0) out[k] = n; } return out; } const sumInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; }; const isEmpty = (units) => !Object.keys(units || {}).some((k) => units[k] > 0); // ---- operators function getOperator(db, id) { return db.get('SELECT * FROM operators WHERE id = ?', id); } function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; } function operatorTowns(db, operatorId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', operatorId); } // Footprint over all POPs of the operator at `now` (each POP's footprint keeps growing from its buildings). function operatorFootprint(db, operatorId, now) { let sum = 0; for (const t of operatorTowns(db, operatorId)) sum += R.footprintAt(loadTown(db, t.id), now); return sum; } function incumbentTakes(db, operatorId) { return db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', operatorId).n; } function researchBonusOf(db, operatorId) { return R.researchSpeedBonus(incumbentTakes(db, operatorId)); } // Where do units of `operatorId` go when their origin POP is gone: the capital, else the oldest POP; null if none. function homeTownFor(db, operatorId, preferTownId) { if (preferTownId) { const t = db.get('SELECT * FROM towns WHERE id = ? AND owner_id = ?', preferTownId, operatorId); if (t) return t; } return db.get('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id LIMIT 1', operatorId) || null; } // May `fromOp` stand units in a POP of `toOp`? Own POPs, same alliance, confederation. function mayReinforce(db, fromOp, toOp) { if (fromOp === toOp) return true; return require('../alliances').confederated(db, fromOp, toOp); } // Pacts (same alliance, NAP, confederation) forbid hostile movements between the partners. function pactBlocks(db, fromOp, toOp) { if (fromOp === toOp) return false; return require('../alliances').pactPartners(db, fromOp, toOp); } module.exports = { homeUnits, setHomeUnit, addHome, removeHome, hostedGroups, awayGroups, stationedOf, setStationed, addStationed, removeStationed, researchLevels, researchSnapshot, cleanUnits, sumInto, isEmpty, getOperator, userOfOperator, operatorTowns, operatorFootprint, incumbentTakes, researchBonusOf, homeTownFor, mayReinforce, pactBlocks, };