swap tick from delayed job to repeatable
[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   const start = Date.now();
13
14         // +population*1.1 is where we take into account farms for bonus food production
15         let sql = `update cities set 
16         credits = credits + population * 2, 
17         food = round(
18                 max(
19                         food - (
20                                 (soldiers*0.5)+
21                                 (population*0.25)+
22                                 (attackers*0.75)+
23                                 (defenders*0.75)+
24                                 (sp_attackers * 1.3)+
25                                 (sp_defenders * 1.3)
26                         ),
27                         0
28                 )
29                  + farms * 50
30         ),
31   energy = min(
32     max(
33       energy - (
34         farms * 4 + 
35         barracks * 6 + 
36         special_attacker_trainer * 10 + 
37         special_defender_trainer * 8 + 
38         homes * 1 + 
39         warehouses * 3 + 
40         solar_panels * 1 +
41         accumulators * 10 +
42         mining_facilities * 8 + 
43         ore_refinery * 4
44       ),
45       0
46     ) + solar_panels * 125,
47     accumulators * 150
48   ),
49   alloys = min(
50     (alloys + mining_facilities * 20),
51     ore_refinery * 75
52   ),
53         population = min(
54                 (population + round(population * 0.08)),
55                 homes * 25
56         )`;
57
58         try {
59                 await Promise.all([
60                         db.raw(sql),
61                         db.raw(`update ticks set current_tick = ${nextTick}, last_tick_at = ${Date.now()}`)
62                 ]);
63         }
64         catch(e) {
65                 console.log(e);
66         }
67         finally {
68     console.log('Tick complete', Date.now() - start);
69         }
70 });