'use strict'; /* * POST /towns/:id/train. Queue a batch of one unit type. Batches of the same training building run one after another * (each is a `trainDone` event); different buildings train in parallel. Units appear when the batch finishes. */ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const { settle, spend } = require('../state'); const { ownedTown } = require('./build'); // Pending batches of a training building, in due order: [{ id, dueAt, ...payload }]. function pendingBatches(db, townId, building) { return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", townId) .map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload))) .filter((b) => !building || b.building === building); } module.exports = function train(ctx, { userId, townId, unit, count }) { const { db, now, scheduler } = ctx; const town = ownedTown(db, userId, townId); const def = R.unitDef(unit); if (!def) throw new GameError('unknown_unit', { unit }); settle(db, town, now); const queue = pendingBatches(db, town.id, def.building); if (queue.length >= D.MILITARY.maxTrainQueue) throw new GameError('queue_full', { building: def.building, max: D.MILITARY.maxTrainQueue }); const tail = queue.length ? queue[queue.length - 1].dueAt : 0; const plan = R.trainPlan(town, unit, count, now, tail); if (!plan.ok) throw new GameError(plan.code, { unit, count, cost: plan.cost, missing: plan.missing }); spend(db, town, plan.cost); const eventId = scheduler.enqueue({ worldId: town.worldId, townId: town.id, type: 'trainDone', dueAt: plan.dueAt, payload: { unit, count, building: def.building, startAt: plan.startAt, cost: plan.cost, userId }, }); return { eventId, unit, count, building: def.building, startAt: plan.startAt, dueAt: plan.dueAt, cost: plan.cost }; }; module.exports.pendingBatches = pendingBatches;