1 import { v4 as uuid } from 'uuid';
2 import { ERROR_CODE, InsufficientResourceError, NotFoundError } from '../errors';
3 import {Repository} from './base';
4 import * as config from '../config';
5 import { BuildQueue, BuildQueueRepository } from './build-queue';
6 import { DateTime, Duration } from 'luxon';
7 import { UnitTrainingQueue, UnitTrainingQueueRepository } from './training-queue';
8 import { coalesce, pluck } from '../lib/util';
9 import { Building, BuildingRepository } from './buildings';
10 import { Unit, UnitRepository } from './unit';
11 import _, { random } from 'lodash';
12 import { Army, ArmyQueue, ArmyRepository } from './army';
34 mining_facilities: number;
37 special_attacker_trainer: number;
38 special_defender_trainer: number;
42 export type CityWithLocation = {
48 export class CityRepository extends Repository<City> {
49 buildQueue: BuildQueueRepository;
50 buildingRepository: BuildingRepository;
51 unitRepository: UnitRepository;
52 unitTrainigQueue: UnitTrainingQueueRepository;
53 armyRepository: ArmyRepository;
57 this.buildingRepository = new BuildingRepository();
58 this.buildQueue = new BuildQueueRepository();
59 this.unitRepository = new UnitRepository();
60 this.unitTrainigQueue = new UnitTrainingQueueRepository();
61 this.armyRepository = new ArmyRepository();
64 async create(accountId: string, rebel: boolean = false): Promise<CityWithLocation> {
65 const icon = rebel ? `/colony-ships/rebels/${random(1, 6)}.png` : '/colony-ships/01.png';
89 special_attacker_trainer: 0,
90 special_defender_trainer: 0,
94 await this.Insert(info);
96 // placement can happen randomly
97 const availableSectors = config.AVAILABLE_SECTORS;
98 const sector = _.random(1, availableSectors);
101 sector_id: await this.getAvailableSector(),
102 location_x: random(0, 25),
103 location_y: random(0, 25)
106 await this.db.raw('insert into locations (sector_id, city_id, location_x, location_y) values (?, ?, ?, ?)', [
115 sector_id: location.sector_id,
116 location_x: location.location_x,
117 location_y: location.location_y
121 async getAvailableSector(): Promise<number> {
122 // figure out which sectors have space (40% fill rate at 25x25);
123 const availableSectors = await this.db.raw<{count: Number, sector_id: number}[]>(`select count(sector_id) as count, sector_id from locations group by sector_id`);
124 const sample = _.sample(availableSectors.filter(sector => sector.count < 250)) as {count: number, sector_id: number};
127 return _.sortBy(availableSectors, 'sector_id').pop().sector_id+1;
130 return sample.sector_id;
133 async save(city: City) {
134 const fieldsToSave = [
135 'totalSpace', 'usedSpace', 'credits', 'alloys', 'energy', 'food',
136 'poulation', 'soldiers', 'attackers', 'defenders', 'sp_attackers', 'sp_defenders',
137 'homes', 'farms', 'barracks', 'special_attacker_trainer', 'special_defender_trainer'
140 const finalData = {};
142 fieldsToSave.forEach(field => {
143 if(city.hasOwnProperty(field)) {
144 finalData[field] = city[field];
148 await this.Save(finalData, {id: city.id});
152 async findById(cityId: string): Promise<CityWithLocation> {
153 const city = await this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
154 join locations l on c.id = l.city_id
155 where id = ? limit 1`, [cityId]);
158 throw new NotFoundError('User has no city', ERROR_CODE.NO_CITY);
165 async getUsersCity(owner: string): Promise<CityWithLocation> {
166 const city = await this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
167 join locations l on c.id = l.city_id
168 where owner = ? limit 1`, [owner]);
171 throw new NotFoundError('User has no city', ERROR_CODE.NO_CITY);
177 findAllInSector(sector_id: number): Promise<CityWithLocation[]> {
178 return this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
179 join locations l on c.id = l.city_id
180 where l.sector_id = ?`, [sector_id]);
183 async buildBuilding(building: Building, amount: number, city: City): Promise<BuildQueue> {
184 const freeSpace = city.totalSpace - city.usedSpace;
186 if(freeSpace < building.land) {
187 throw new InsufficientResourceError('land', building.land, freeSpace);
190 if(city.credits < building.credits) {
191 throw new InsufficientResourceError('credits', building.credits, city.credits);
194 if(city.alloys < building.alloys) {
195 throw new InsufficientResourceError('alloys', building.alloys, city.alloys);
198 if(city.energy < building.energy) {
199 throw new InsufficientResourceError('energy', building.energy, city.energy);
202 city.usedSpace += (building.land * amount);
203 city.credits -= (building.credits * amount);
204 city.alloys -= (building.alloys * amount);
205 city.energy -= (building.energy * amount);
207 await this.save(city);
209 const due = Duration.fromObject({ hours: building.time});
210 const queue = await this.buildQueue.create(
212 DateTime.now().plus({ milliseconds: due.as('milliseconds') }).toMillis(),
221 * Returns the distance in seconds
225 distanceInSeconds(city1: CityWithLocation, city2: CityWithLocation): number {
226 return this.distanceInHours(city1, city2) * 60 * 60;
229 distanceInHours(city1: CityWithLocation, city2: CityWithLocation): number {
230 const dist = Math.sqrt(
231 Math.pow((city2.location_x - city1.location_x), 2)
233 Math.pow((city2.location_y - city1.location_y), 2)
236 // sectors always add 4 hours
237 const sector_dist = Math.abs(city1.sector_id - city2.sector_id) * 6;
239 return _.round(dist/4, 2) + sector_dist;
243 async train(unit: Unit, amount: number, city: City): Promise<UnitTrainingQueue> {
244 if(city.credits < unit.credits) {
245 throw new InsufficientResourceError('credits', unit.credits, city.credits);
248 if(city.food < unit.food) {
249 throw new InsufficientResourceError('food', unit.food, city.food);
252 if(city.population < coalesce(unit.population, 0)) {
253 throw new InsufficientResourceError('population', unit.population, city.population);
256 if(city.soldiers < coalesce(unit.soldiers, 0)) {
257 throw new InsufficientResourceError('soldiers', unit.soldiers, city.soldiers);
260 if(city.attackers < coalesce(unit.attackers, 0)) {
261 throw new InsufficientResourceError('attackers', unit.attackers, city.attackers);
264 if(city.defenders < coalesce(unit.defenders, 0)) {
265 throw new InsufficientResourceError('defenders', unit.defenders, city.defenders);
268 // validate that they have enough of the buildings to support this
270 // ok they have everything, lets update their city
271 // and create the entry in the training queue
273 city.credits -= unit.credits * amount;
274 city.food -= unit.food * amount;
275 city.population -= coalesce(unit.population, 0) * amount;
276 city.soldiers -= coalesce(unit.soldiers, 0) * amount;
277 city.attackers -= coalesce(unit.attackers, 0) * amount;
278 city.defenders -= coalesce(unit.defenders, 0) * amount;
280 await this.save(city);
282 // barracks can drop this by 0.01% for each barrack.
284 let additionalOffset = 0;
285 if(unit.slug === 'sp_attackers') {
286 additionalOffset = (this.spAttackerTraininerBoost(city) * unit.time);
288 else if(unit.slug === 'sp_defenders') {
289 additionalOffset = (this.spDefenderTraininerBoost(city) * unit.time);
292 const barracksOffset = _.round((this.barracksImprovement(city) * unit.time) + unit.time - additionalOffset, 2);
294 const due = Duration.fromObject({ hours: barracksOffset });
296 const queue = await this.unitTrainigQueue.create(
298 DateTime.now().plus({ milliseconds: due.as('milliseconds') }).toMillis(),
306 async power(checkUnits: {soldiers: number, attackers: number, defenders: number, sp_attackers: number, sp_defenders: number}): Promise<number> {
307 const units = _.keyBy(await this.unitRepository.list(), 'slug');
310 _.each(checkUnits, (count, slug) => {
312 power += units[slug].attack * count;
321 barracksImprovement(city: City): number {
322 return city.barracks * 0.0001;
325 spAttackerTraininerBoost(city: City): number {
326 return city.special_attacker_trainer * 0.002;
329 spDefenderTraininerBoost(city: City): number {
330 return city.special_defender_trainer * 0.002;
333 maxPopulation(city: City): number {
334 return city.homes * 25;
337 maxFood(city: City): number {
338 return city.warehouses * 250;
341 maxEnergy(city: City): number {
342 return city.accumulators * 150;
345 maxAlloy(city: City): number {
346 return city.ore_refinery * 75;
349 async foodProductionPerTick(city: City): Promise<number> {
350 // eventually we should supply the warehouse formula
351 // to calculate the max amount of food created per tick
352 return city.farms * 50;
355 async foodUsagePerTick(city: City): Promise<number> {
357 (city.soldiers * 0.5) +
358 (city.population * 0.25) +
359 (city.attackers * 0.75) +
360 (city.attackers * 0.75) +
361 (city.sp_attackers * 1.3) +
362 (city.sp_defenders * 1.3)
366 async energyProductionPerTick(city: City): Promise<number> {
367 return city.solar_panels * 125;
370 async energyUsagePerTick(city: City): Promise<number> {
371 const buildings = await this.buildingRepository.list();
372 const buildingsMap = pluck<Building>(buildings, 'slug');
373 const totalEnergy = _.sum([
374 city.farms * buildingsMap['farms'].energy,
375 city.barracks * buildingsMap['barracks'].energy,
376 city.special_defender_trainer * buildingsMap['special_defender_trainer'].energy,
377 city.special_attacker_trainer * buildingsMap['special_attacker_trainer'].energy,
378 city.homes * buildingsMap['homes'].energy,
379 city.warehouses * buildingsMap['warehouses'].energy,
380 city.solar_panels * buildingsMap['solar_panels'].energy
385 async attack(attacker: CityWithLocation, attacked: CityWithLocation, army: Army): Promise<ArmyQueue> {
386 // validate the user has enough of a military!
387 if(attacker.soldiers < army.soldiers) {
388 throw new InsufficientResourceError('soldiers', army.soldiers, attacker.soldiers);
390 if(attacker.attackers < army.attackers) {
391 throw new InsufficientResourceError('attackers', army.attackers, attacker.attackers);
393 if(attacker.defenders < army.defenders) {
394 throw new InsufficientResourceError('defenders', army.defenders, attacker.defenders);
396 if(attacker.sp_attackers < army.sp_attackers) {
397 throw new InsufficientResourceError('sp_attackers', army.sp_attackers, attacker.sp_attackers);
399 if(attacker.sp_defenders < army.sp_defenders) {
400 throw new InsufficientResourceError('sp_defenders', army.sp_defenders, attacker.sp_defenders);
403 // ok, it's a real army lets send it off!
404 attacker.soldiers -= army.soldiers;
405 attacker.attackers -= army.attackers;
406 attacker.defenders -= army.defenders;
407 attacker.sp_attackers -= army.sp_attackers;
408 attacker.sp_defenders -= army.sp_defenders;
410 await this.save(attacker);
412 return this.armyRepository.create(
417 this.distanceInSeconds(attacker, attacked)
421 async getBuildQueues(owner: string): Promise<BuildQueue[]> {
422 return this.buildQueue.list(owner);
425 async getUnitTrainingQueues(owner: string): Promise<UnitTrainingQueue[]> {
426 return this.unitTrainigQueue.list(owner);