6e08ff8ae8c6af3301605b0a722ae2c4b53aa2ff
[browser-rts.git] / src / repository / city.ts
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';
13
14 export type City = {
15         id: string;
16     owner: string;
17     totalSpace: number;
18     usedSpace: number;
19     credits: number;
20     alloys: number;
21     energy: number;
22     food: number;
23     population: number;
24     soldiers: number;
25     attackers: number;
26     defenders: number;
27     sp_attackers: number;
28     sp_defenders: number;
29     homes: number;
30     farms: number;
31     warehouses: number;
32     solar_panels: number;
33     accumulators: number;
34     barracks: number;
35     special_attacker_trainer: number;
36     special_defender_trainer: number;
37     icon: string;
38 }
39
40 export type CityWithLocation = {
41     sector_id: number;
42     location_x: number;
43     location_y: number;
44 } & City;
45
46 export class CityRepository extends Repository<City> {
47     buildQueue: BuildQueueRepository;
48     buildingRepository: BuildingRepository;
49     unitRepository: UnitRepository;
50     unitTrainigQueue: UnitTrainingQueueRepository;
51     armyRepository: ArmyRepository;
52
53     constructor() {
54         super('cities');
55         this.buildingRepository = new BuildingRepository();
56         this.buildQueue = new BuildQueueRepository();
57         this.unitRepository = new UnitRepository();
58         this.unitTrainigQueue = new UnitTrainingQueueRepository();
59         this.armyRepository = new ArmyRepository();
60     }
61
62     async create(accountId: string, rebel: boolean = false): Promise<CityWithLocation> {
63       const icon = rebel ? `/colony-ships/rebels/${random(1, 6)}.png` : '/colony-ships/01.png';
64         const info: City = {
65             id: uuid(),
66             owner: accountId,
67             totalSpace: 100,
68             usedSpace: 0,
69             credits: 10000,
70             alloys: 10000,
71             energy: 10000,
72             food: 10000,
73             population: 1000,
74             soldiers: 100,
75             attackers: 0,
76             defenders: 0,
77             sp_attackers: 0,
78             sp_defenders: 0,
79             homes: 20,
80             farms: 5,
81             warehouses: 5,
82             solar_panels: 5,
83             accumulators: 5,
84             barracks: 0,
85             special_attacker_trainer: 0,
86             special_defender_trainer: 0,
87             icon
88         };
89
90         await this.Insert(info);
91
92         // placement can happen randomly
93         const availableSectors = config.AVAILABLE_SECTORS;
94         const sector = _.random(1, availableSectors);
95
96         const location = {
97             sector_id: await this.getAvailableSector(),
98             location_x: random(0, 25),
99             location_y: random(0, 25)
100         }
101
102         await this.db.raw('insert into locations (sector_id, city_id, location_x, location_y) values (?, ?, ?, ?)', [
103             location.sector_id,
104             info.id,
105             location.location_x,
106             location.location_y
107         ]);
108
109         return {
110             ...info,
111             sector_id: location.sector_id,
112             location_x: location.location_x,
113             location_y: location.location_y
114         };
115     }
116
117     async getAvailableSector(): Promise<number> {
118         // figure out which sectors have space (40% fill rate at 25x25);
119         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`);
120         const sample = _.sample(availableSectors.filter(sector => sector.count < 250)) as {count: number, sector_id: number};
121
122         if(!sample) {
123             return _.sortBy(availableSectors, 'sector_id').pop().sector_id+1;
124         }
125         
126         return sample.sector_id;
127     }
128
129     async save(city: City) {
130       const fieldsToSave = [
131         'totalSpace', 'usedSpace', 'credits', 'alloys', 'energy', 'food',
132         'poulation', 'soldiers', 'attackers', 'defenders', 'sp_attackers', 'sp_defenders',
133         'homes', 'farms', 'barracks', 'special_attacker_trainer', 'special_defender_trainer'
134       ];
135       
136       const finalData = {};
137
138       fieldsToSave.forEach(field => {
139         if(city.hasOwnProperty(field)) {
140           finalData[field] = city[field];
141         }
142       });
143
144       await this.Save(finalData, {id: city.id});
145       return city;
146     }
147
148     async findById(cityId: string): Promise<CityWithLocation> {
149         const city = await this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
150         join locations l on c.id = l.city_id 
151         where id = ? limit 1`, [cityId]);
152
153         if(!city) {
154             throw new NotFoundError('User has no city', ERROR_CODE.NO_CITY);
155         }
156
157         return city.pop();
158
159     }
160
161     async getUsersCity(owner: string): Promise<CityWithLocation> {
162         const city = await this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
163         join locations l on c.id = l.city_id 
164         where owner = ? limit 1`, [owner]);
165
166         if(!city) {
167             throw new NotFoundError('User has no city', ERROR_CODE.NO_CITY);
168         }
169
170         return city.pop();
171     }
172
173     findAllInSector(sector_id: number): Promise<CityWithLocation[]> {
174         return this.db.raw<CityWithLocation[]>(`select c.*, l.sector_id, l.location_x, l.location_y from cities c
175 join locations l on c.id = l.city_id 
176 where l.sector_id = ?`, [sector_id]);
177     }
178
179     async buildBuilding(building: Building, amount: number, city: City): Promise<BuildQueue> {
180         const freeSpace = city.totalSpace - city.usedSpace;
181
182         if(freeSpace < building.land) {
183             throw new InsufficientResourceError('land', building.land, freeSpace);
184         }
185
186         if(city.credits < building.credits) {
187             throw new InsufficientResourceError('credits', building.credits, city.credits);
188         }
189
190         if(city.alloys < building.alloys) {
191             throw new InsufficientResourceError('alloys', building.alloys, city.alloys);
192         }
193
194         if(city.energy < building.energy) {
195             throw new InsufficientResourceError('energy', building.energy, city.energy);
196         }
197
198         city.usedSpace += (building.land * amount);
199         city.credits -= (building.credits * amount);
200         city.alloys -= (building.alloys * amount);
201         city.energy -= (building.energy * amount);
202
203         await this.save(city);
204
205         const due = Duration.fromObject({ hours: building.time});
206         const queue = await this.buildQueue.create(
207             city.owner, 
208             DateTime.now().plus({ milliseconds: due.as('milliseconds') }).toMillis(), 
209             building.slug,
210             amount
211         );
212
213         return queue;
214     }
215
216     /**
217      * Returns the distance in seconds
218      * @param city1 
219      * @param city2 
220      */
221     distanceInSeconds(city1: CityWithLocation, city2: CityWithLocation): number {
222         return this.distanceInHours(city1, city2) * 60 * 60;
223     }
224
225     distanceInHours(city1: CityWithLocation, city2: CityWithLocation): number {
226         const dist = Math.sqrt(
227             Math.pow((city2.location_x - city1.location_x), 2) 
228             + 
229             Math.pow((city2.location_y - city1.location_y), 2)
230         );
231
232         // sectors always add 4 hours
233         const sector_dist = Math.abs(city1.sector_id - city2.sector_id) * 6;
234
235         return _.round(dist/4, 2) + sector_dist;
236
237     }
238
239     async train(unit: Unit, amount: number, city: City): Promise<UnitTrainingQueue> {
240         if(city.credits < unit.credits) {
241             throw new InsufficientResourceError('credits', unit.credits, city.credits);
242         }
243
244         if(city.food < unit.food) {
245             throw new InsufficientResourceError('food', unit.food, city.food);
246         }
247
248         if(city.population < coalesce(unit.population, 0)) {
249             throw new InsufficientResourceError('population', unit.population, city.population);
250         }
251
252         if(city.soldiers < coalesce(unit.soldiers, 0)) {
253             throw new InsufficientResourceError('soldiers', unit.soldiers, city.soldiers);
254         }
255
256         if(city.attackers < coalesce(unit.attackers, 0)) {
257             throw new InsufficientResourceError('attackers', unit.attackers, city.attackers);
258         }
259
260         if(city.defenders < coalesce(unit.defenders, 0)) {
261             throw new InsufficientResourceError('defenders', unit.defenders, city.defenders);
262         }
263
264         // validate that they have enough of the buildings to support this
265
266         // ok they have everything, lets update their city 
267         // and create the entry in the training queue
268
269         city.credits -= unit.credits * amount;
270         city.food -= unit.food * amount;
271         city.population -= coalesce(unit.population, 0) * amount;
272         city.soldiers -= coalesce(unit.soldiers, 0) * amount;
273         city.attackers -= coalesce(unit.attackers, 0) * amount;
274         city.defenders -= coalesce(unit.defenders, 0) * amount;
275
276         await this.save(city);
277
278         // barracks can drop this by 0.01% for each barrack.
279
280         let additionalOffset = 0;
281         if(unit.slug === 'sp_attackers') {
282           additionalOffset = (this.spAttackerTraininerBoost(city) * unit.time);
283         }
284         else if(unit.slug === 'sp_defenders') {
285           additionalOffset = (this.spDefenderTraininerBoost(city) * unit.time);
286         }
287
288         const barracksOffset = _.round((this.barracksImprovement(city) * unit.time) + unit.time - additionalOffset, 2);
289
290         const due = Duration.fromObject({ hours: barracksOffset });
291
292         const queue = await this.unitTrainigQueue.create(
293             city.owner, 
294             DateTime.now().plus({ milliseconds: due.as('milliseconds') }).toMillis(), 
295             unit.slug,
296             amount
297         );
298
299         return queue;
300     }
301
302     async power(checkUnits: {soldiers: number, attackers: number, defenders: number, sp_attackers: number, sp_defenders: number}): Promise<number> {
303         const units = _.keyBy(await this.unitRepository.list(), 'slug');
304         let power = 0;
305
306         _.each(checkUnits, (count, slug) => {
307             try {
308                 power += units[slug].attack * count;
309             }
310             catch(e) {
311             }
312         });
313
314         return power
315     }
316
317     barracksImprovement(city: City): number {
318       return city.barracks * 0.0001;
319     }
320
321     spAttackerTraininerBoost(city: City): number {
322       return city.special_attacker_trainer * 0.002;
323     }
324
325     spDefenderTraininerBoost(city: City): number {
326       return city.special_defender_trainer * 0.002;
327     }
328
329     maxPopulation(city: City): number {
330       return city.homes * 25;
331     }
332
333     maxFood(city: City): number {
334       return city.warehouses * 250;
335     }
336
337     maxEnergy(city: City): number {
338       return city.accumulators * 150;
339     }
340
341     async foodProductionPerTick(city: City): Promise<number> {
342       // eventually we should supply the warehouse formula 
343       // to calculate the max amount of food created per tick
344       return _.max([
345         city.population + _.round(city.farms * 50)
346       ])
347     }
348
349     async foodUsagePerTick(city: City): Promise<number> {
350       return (
351         (city.soldiers * 0.5) + 
352         (city.population * 0.25) + 
353         (city.attackers * 0.75) + 
354         (city.attackers * 0.75) + 
355         (city.sp_attackers * 1.3) + 
356         (city.sp_defenders * 1.3)
357       )
358     }
359
360     async energyProductionPerTick(city: City): Promise<number> {
361       return city.solar_panels * 125;
362     }
363
364     async energyUsagePerTick(city: City): Promise<number> {
365       const buildings = await this.buildingRepository.list();
366       const buildingsMap = pluck<Building>(buildings, 'slug');
367       const totalEnergy = _.sum([
368         city.farms * buildingsMap['farms'].energy,
369         city.barracks * buildingsMap['barracks'].energy,
370         city.special_defender_trainer * buildingsMap['special_defender_trainer'].energy,
371         city.special_attacker_trainer * buildingsMap['special_attacker_trainer'].energy,
372         city.homes * buildingsMap['homes'].energy,
373         city.warehouses * buildingsMap['warehouses'].energy,
374         city.solar_panels * buildingsMap['solar_panels'].energy
375       ]);
376       return totalEnergy;
377     }
378
379     async attack(attacker: CityWithLocation, attacked: CityWithLocation, army: Army): Promise<ArmyQueue> {
380         // validate the user has enough of a military! 
381         if(attacker.soldiers < army.soldiers) {
382             throw new InsufficientResourceError('soldiers', army.soldiers, attacker.soldiers);
383         }
384         if(attacker.attackers < army.attackers) {
385             throw new InsufficientResourceError('attackers', army.attackers, attacker.attackers);
386         }
387         if(attacker.defenders < army.defenders) {
388             throw new InsufficientResourceError('defenders', army.defenders, attacker.defenders);
389         }
390         if(attacker.sp_attackers < army.sp_attackers) {
391             throw new InsufficientResourceError('sp_attackers', army.sp_attackers, attacker.sp_attackers);
392         }
393         if(attacker.sp_defenders < army.sp_defenders) {
394             throw new InsufficientResourceError('sp_defenders', army.sp_defenders, attacker.sp_defenders);
395         }
396
397         // ok, it's a real army lets send it off!
398         attacker.soldiers -= army.soldiers;
399         attacker.attackers -= army.attackers;
400         attacker.defenders -= army.defenders;
401         attacker.sp_attackers -= army.sp_attackers;
402         attacker.sp_defenders -= army.sp_defenders;
403
404         await this.save(attacker);
405
406         return this.armyRepository.create(
407             attacker.owner,
408             attacker,
409             attacked,
410             army,
411             this.distanceInSeconds(attacker, attacked)
412         );
413     }
414
415     async getBuildQueues(owner: string): Promise<BuildQueue[]> {
416         return this.buildQueue.list(owner);
417     }
418
419     async getUnitTrainingQueues(owner: string): Promise<UnitTrainingQueue[]> {
420         return this.unitTrainigQueue.list(owner);
421     }
422 }