8160e9ae03bf4446299e0726988db0d37acff826
[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         gold = gold + population * 2, 
16         bushels = round(
17                 max(
18                         bushels - (
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         population = max(
31                 min(
32                         population + round(coalesce(bushels/bushels, 0) * population*0.08),
33                         farms * 70
34                 ),
35                 population
36         )`;
37
38         try {
39                 await Promise.all([
40                         db.raw(sql),
41                         db.raw(`update ticks set current_tick = ${nextTick}, last_tick_at = ${Date.now()}`)
42                 ]);
43         }
44         catch(e) {
45                 console.log(e);
46         }
47         finally {
48                 const now = new Date();
49                 const nextTickAt = 60 - now.getMinutes();
50                 console.log(`Tick scheduled for ${nextTickAt}min`);
51
52                 task.trigger({
53                         lastTickAt: +now,
54                         lastTick: nextTick
55                 }, { delay: 60000 * nextTickAt});
56         }
57
58 });