import type { Building, Production } from "./types"; import type { VillageState } from "./village"; function _reduceResources(acc: Production, item: Production): Production { return { wood: acc.wood + item.wood, stone: acc.stone + item.stone, iron: acc.iron + item.iron, food: acc.food + item.food, }; } export function getEmptyResources(): Production { return { wood: 0, stone: 0, iron: 0, food: 0, }; } export function getProduction(villageState: VillageState): Production { return villageState.buildings .filter(b => b.behavior.production && b.level > 0) .map(b => { if (b.behavior.production) { return b.behavior.production(villageState, b); } }) .reduce(_reduceResources, getEmptyResources()); } export function getStorage(villageState: VillageState): Production { return villageState.buildings .filter(b => b.behavior.storage && b.level > 0) .map(b => { if (b.behavior.storage) { return b.behavior.storage(villageState, b); } }) .reduce(_reduceResources, getEmptyResources()); } export function getBuilding(V: VillageState, buildingId: number): Building { const building = V.buildings.find(b => b.id === buildingId); if (!building) { throw new Error(`Cannot find building with id "${buildingId}"`); } return building; } export function getKeysAsNumbers(dict: Object): Array { return Object.keys(dict).map(i => parseInt(i)).sort((a, b) => a - b); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @since 0.1.0 * @category Array * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * shuffle([1, 2, 3, 4]) * // => [4, 1, 3, 2] */ export function shuffle(array: Array): Array { const length = array.length; if (!length) { return []; } let index = -1; const lastIndex = length - 1; const result = [ ...array ]; while (++index < length) { const rand = index + Math.floor(Math.random() * (lastIndex - index + 1)); [ result[rand], result[index] ] = [ result[index], result[rand] ]; } return result; } export function enqueueBuilding(V: VillageState, building: Building) { const ongoingUpgrades = V.queue.filter(q => q.id === building.id); const level = building.level + 1 + ongoingUpgrades.length; const remainingTime = 1000 * level; V.queue.push({ id: building.id, remainingTime, }); }