bourgade/src/update.ts

55 lines
1.7 KiB
TypeScript

import { produce } from 'immer';
import { getBuilding, getProduction, getStorage } from './utils';
import village, { type VillageState } from "./village";
import type { Production } from './types';
let lastFrame: number;
export default function update(timestamp: number) {
if (!lastFrame) {
lastFrame = timestamp;
return;
}
const delta = timestamp - lastFrame;
village.update(state => {
return produce(state, (V: VillageState) => {
// Advance building construction.
if (V.queue.length) {
V.queue[0].remainingTime -= delta;
if (V.queue[0].remainingTime <= 0) {
const building = getBuilding(V, V.queue[0].id);
building.level++;
V.queue.shift();
}
}
// Make all buildings produce and consume.
const productionPerMinute = getProduction(V);
const storage = getStorage(V);
Object.keys(productionPerMinute).forEach((key) => {
const resource = key as keyof Production;
const outputPerMinute = productionPerMinute[resource];
const outputPerMilisecond = outputPerMinute / 60.0 / 1000.0;
V.resources[resource] += outputPerMilisecond * delta;
if (V.resources[resource] > storage[resource]) {
V.resources[resource] = storage[resource];
}
else if (V.resources[resource] < 0) {
V.resources[resource] = 0;
}
});
return V;
});
});
lastFrame = timestamp;
}