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