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);
269 console.log(unit, amount);
271 // validate that they have enough of the buildings to support this
273 // ok they have everything, lets update their city
274 // and create the entry in the training queue
276 city.credits -= unit.credits * amount;
277 city.food -= unit.food * amount;
278 city.population -= unit.population * amount;
279 city.soldiers -= unit.soldiers * amount;
280 city.attackers -= unit.attackers * amount;
281 city.defenders -= unit.defenders * amount;
285 await this.save(city);
287 // barracks can drop this by 0.01% for each barrack.
289 let additionalOffset = 0;
290 if(unit.slug === 'sp_attackers') {
291 additionalOffset = (this.spAttackerTraininerBoost(city) * unit.time);
293 else if(unit.slug === 'sp_defenders') {
294 additionalOffset = (this.spDefenderTraininerBoost(city) * unit.time);
297 const barracksOffset = _.round((this.barracksImprovement(city) * unit.time) + unit.time - additionalOffset, 2);
299 const due = Duration.fromObject({ hours: barracksOffset });
301 const queue = await this.unitTrainigQueue.create(
303 DateTime.now().plus({ milliseconds: due.as('milliseconds') }).toMillis(),
311 async power(checkUnits: {soldiers: number, attackers: number, defenders: number, sp_attackers: number, sp_defenders: number}): Promise<number> {
312 const units = _.keyBy(await this.unitRepository.list(), 'slug');
315 _.each(checkUnits, (count, slug) => {
317 power += units[slug].attack * count;
326 barracksImprovement(city: City): number {
327 return city.barracks * 0.0001;
330 spAttackerTraininerBoost(city: City): number {
331 return city.special_attacker_trainer * 0.002;
334 spDefenderTraininerBoost(city: City): number {
335 return city.special_defender_trainer * 0.002;
338 maxPopulation(city: City): number {
339 return city.homes * 25;
342 maxFood(city: City): number {
343 return city.warehouses * 250;
346 maxEnergy(city: City): number {
347 return city.accumulators * 150;
350 maxAlloy(city: City): number {
351 return city.ore_refinery * 75;
354 async foodProductionPerTick(city: City): Promise<number> {
355 // eventually we should supply the warehouse formula
356 // to calculate the max amount of food created per tick
357 return city.farms * 50;
360 async foodUsagePerTick(city: City): Promise<number> {
362 (city.soldiers * 0.5) +
363 (city.population * 0.25) +
364 (city.attackers * 0.75) +
365 (city.attackers * 0.75) +
366 (city.sp_attackers * 1.3) +
367 (city.sp_defenders * 1.3)
371 async energyProductionPerTick(city: City): Promise<number> {
372 return city.solar_panels * 125;
375 async energyUsagePerTick(city: City): Promise<number> {
376 const buildings = await this.buildingRepository.list();
377 const buildingsMap = pluck<Building>(buildings, 'slug');
378 const totalEnergy = Math.ceil(_.sum([
379 city.farms * (buildingsMap['farms'].energy * 0.1),
380 city.barracks * (buildingsMap['barracks'].energy * 0.1),
381 city.special_defender_trainer * (buildingsMap['special_defender_trainer'].energy * 0.1),
382 city.special_attacker_trainer * (buildingsMap['special_attacker_trainer'].energy * 0.1),
383 city.homes * (buildingsMap['homes'].energy * 0.1),
384 city.warehouses * (buildingsMap['warehouses'].energy * 0.1),
385 city.solar_panels * (buildingsMap['solar_panels'].energy * 0.1),
386 city.mining_facilities * (buildingsMap['mining_facilities'].energy * 0.1),
387 city.ore_refinery * (buildingsMap['ore_refinery'].energy * 0.1)
392 async attack(attacker: CityWithLocation, attacked: CityWithLocation, army: Army): Promise<ArmyQueue> {
393 // validate the user has enough of a military!
394 if(attacker.soldiers < army.soldiers) {
395 throw new InsufficientResourceError('soldiers', army.soldiers, attacker.soldiers);
397 if(attacker.attackers < army.attackers) {
398 throw new InsufficientResourceError('attackers', army.attackers, attacker.attackers);
400 if(attacker.defenders < army.defenders) {
401 throw new InsufficientResourceError('defenders', army.defenders, attacker.defenders);
403 if(attacker.sp_attackers < army.sp_attackers) {
404 throw new InsufficientResourceError('sp_attackers', army.sp_attackers, attacker.sp_attackers);
406 if(attacker.sp_defenders < army.sp_defenders) {
407 throw new InsufficientResourceError('sp_defenders', army.sp_defenders, attacker.sp_defenders);
410 // ok, it's a real army lets send it off!
411 attacker.soldiers -= army.soldiers;
412 attacker.attackers -= army.attackers;
413 attacker.defenders -= army.defenders;
414 attacker.sp_attackers -= army.sp_attackers;
415 attacker.sp_defenders -= army.sp_defenders;
417 await this.save(attacker);
419 return this.armyRepository.create(
424 this.distanceInSeconds(attacker, attacked)
428 async getBuildQueues(owner: string): Promise<BuildQueue[]> {
429 return this.buildQueue.list(owner);
432 async getUnitTrainingQueues(owner: string): Promise<UnitTrainingQueue[]> {
433 return this.unitTrainigQueue.list(owner);