energy upkeep is now 10% of build costs
[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 * 4 + 
34         barracks * 6 + 
35         special_attacker_trainer * 10 + 
36         special_defender_trainer * 8 + 
37         homes * 1 + 
38         warehouses * 3 + 
39         solar_panels * 1 +
40         accumulators * 10 +
41         mining_facilities * 8 + 
42         ore_refinery * 4
43       ),
44       0
45     ),
46     accumulators * 150
47   ),
48   alloys = min(
49     (alloys + mining_facilities * 20),
50     ore_refinery * 75
51   ),
52         population = min(
53                 (population + round(population * 0.08)),
54                 homes * 25
55         )`;
56
57         try {
58                 await Promise.all([
59                         db.raw(sql),
60                         db.raw(`update ticks set current_tick = ${nextTick}, last_tick_at = ${Date.now()}`)
61                 ]);
62         }
63         catch(e) {
64                 console.log(e);
65         }
66         finally {
67                 const now = new Date();
68                 const nextTickAt = 60 - now.getMinutes();
69                 console.log(`Tick scheduled for ${nextTickAt}min`);
70
71                 task.trigger({
72                         lastTickAt: +now,
73                         lastTick: nextTick
74                 }, { delay: 60000 * nextTickAt});
75         }
76
77 });