d12f1af2d05187b152f30e8cf94bf20ff1e915d3
[browser-rts.git] / src / tasks / tick.ts
1 import { Task } from './task';
2 import { db } from '../lib/db';
3
4 type Tick = {
5         lastTickAt: number;
6         lastTick: number;
7 };
8
9 export const tick = new Task<Tick>('tick', async (task, job) => {
10
11         const nextTick = job.data.lastTick+1;
12
13         // +population*1.1 is where we take into account farms for bonus food production
14         let sql = `update cities set 
15         credits = credits + population * 2, 
16         food = round(
17                 max(
18                         food - (
19                                 (soldiers*0.5)+
20                                 (population*0.25)+
21                                 (attackers*0.75)+
22                                 (defenders*0.75)+
23                                 (sp_attackers * 1.3)+
24                                 (sp_defenders * 1.3)
25                         ),
26                         0
27                 )
28                  + farms * 50
29         ),
30   energy = min(
31     max(
32       energy - (
33         farms * 40 + 
34         barracks * 60 + 
35         special_attacker_trainer * 100 + 
36         special_defender_trainer * 80 + 
37         homes * 10 + 
38         warehouses * 30 + 
39         solar_panels * 10 +
40         accumulators * 100
41       ),
42       0
43     ),
44     accumulators * 150
45   ),
46   alloys = min(
47     (alloys + mining_facilities * 20),
48     ore_refinery * 75
49   ),
50         population = min(
51                 (population + round(population * 0.08)),
52                 homes * 25
53         )`;
54
55         try {
56                 await Promise.all([
57                         db.raw(sql),
58                         db.raw(`update ticks set current_tick = ${nextTick}, last_tick_at = ${Date.now()}`)
59                 ]);
60         }
61         catch(e) {
62                 console.log(e);
63         }
64         finally {
65                 const now = new Date();
66                 const nextTickAt = 60 - now.getMinutes();
67                 console.log(`Tick scheduled for ${nextTickAt}min`);
68
69                 task.trigger({
70                         lastTickAt: +now,
71                         lastTick: nextTick
72                 }, { delay: 60000 * nextTickAt});
73         }
74
75 });