Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to the new Store interface #212

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions src/Colony.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,6 @@ const getDefaultColonyMemory: () => ColonyMemory = () => ({
outposts : {},
});

export interface Assets {
energy: number;
power: number;
ops: number;

[resourceType: string]: number;
}

/**
* Colonies are the highest-level object other than the global Overmind. A colony groups together all rooms, structures,
* creeps, utilities, etc. which are run from a single owned room.
Expand All @@ -127,7 +119,7 @@ export class Colony {
// abandonedOutposts: AbandonedOutpost[]; // Outposts that are not currently maintained, not used for now
rooms: Room[]; // All rooms including the primary room
pos: RoomPosition;
assets: Assets;
assets: StoreContents;
// Physical colony structures and roomObjects
controller: StructureController; // These are all duplicated from room properties
spawns: StructureSpawn[]; // |
Expand Down Expand Up @@ -654,13 +646,13 @@ export class Colony {
* Summarizes the total of all resources in colony store structures, labs, and some creeps. Will always return
* 0 for an asset that it has none of (not undefined)
*/
private computeAssets(verbose = false): Assets {
private computeAssets(verbose = false): StoreContents {
// Include storage structures, lab contents, and manager carry
const assetStructures = _.compact([this.storage, this.terminal, this.factory, ...this.labs]);
const assetCreeps = [...this.getCreepsByRole(Roles.queen), ...this.getCreepsByRole(Roles.manager)];
const assetStores = _.map([...assetStructures, ...assetCreeps], thing => thing!.store);

const allAssets = mergeSum([...assetStores, ALL_ZERO_ASSETS]) as Assets;
const allAssets = mergeSum(...assetStores, ALL_ZERO_ASSETS);

if (verbose) log.debug(`${this.room.print} assets: ` + JSON.stringify(allAssets));
return allAssets;
Expand Down
4 changes: 2 additions & 2 deletions src/Overseer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ export class Overseer implements IOverseer {
}
// Place a logistics request directive for every tombstone with non-empty store that isn't on a container
for (const tombstone of colony.tombstones) {
if (_.sum(tombstone.store) > LogisticsNetwork.settings.droppedEnergyThreshold
|| _.sum(tombstone.store) > tombstone.store.energy) {
if (tombstone.store.getUsedCapacity() > LogisticsNetwork.settings.droppedEnergyThreshold
|| tombstone.store.getUsedCapacity() > tombstone.store.energy) {
if (colony.bunker && tombstone.pos.isEqualTo(colony.bunker.anchor)) continue;
colony.logisticsNetwork.requestOutput(tombstone, {resourceType: 'all'});
}
Expand Down
6 changes: 3 additions & 3 deletions src/declarations/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ type TransferrableStoreStructure =
| StructureTerminal
| StructureTower;

// interface StoreLike {
// [resourceType: string]: number
// }

type StoreContentsArray = [resourceType: ResourceConstant, amount: number][];
type StoreContents = { [resourceType in ResourceConstant]: number };
type DropContents = { [resourceType in ResourceConstant]: Resource[] };
47 changes: 13 additions & 34 deletions src/declarations/prototypes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,21 @@ interface Structure {
isWalkable: boolean;
}

interface StructureContainer {
interface StoreBase {
contents: StoreContentsArray;
}

interface _StoreLike {
energy: number;
isFull: boolean;
isEmpty: boolean;
}

interface StructureContainer extends _StoreLike {}
interface StructureExtension extends _StoreLike {}
interface StructureLink extends _StoreLike {}
interface StructureStorage extends _StoreLike {}

interface StructureController {
reservedByMe: boolean;
signedByMe: boolean;
Expand All @@ -234,46 +243,16 @@ interface StructureController {
needsReserving(reserveBuffer: number): boolean;
}

interface StructureExtension {
isFull: boolean;
isEmpty: boolean;
}

interface StructureLink {
isFull: boolean;
isEmpty: boolean;
storeCapacity: number;
}

interface StructureStorage {
energy: number;
isFull: boolean;
isEmpty: boolean;
}

interface Store {
contents: [ResourceConstant, number][];
}

interface StructureSpawn {
isFull: boolean;
isEmpty: boolean;

interface StructureSpawn extends _StoreLike {
cost(bodyArray: string[]): number;
}

interface StructureTerminal {
energy: any;
isFull: boolean;
isEmpty: boolean;
interface StructureTerminal extends _StoreLike {
isReady: boolean;
hasReceived: boolean;
}

interface StructureTower {
isFull: boolean;
isEmpty: boolean;

interface StructureTower extends _StoreLike {
// run(): void;
//
// attackNearestEnemy(): number;
Expand Down
18 changes: 9 additions & 9 deletions src/deprecated/TerminalNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
this.exceptionTerminals = {}; // populated in init()
this.assets = {}; // populated in init()
this.notifications = [];
this.averageFullness = _.sum(this.terminals, t => _.sum(t.store) / t.storeCapacity) / this.terminals.length;
this.averageFullness = _.sum(this.terminals, t => t.store.getUsedCapacity() / t.store.getCapacity()) / this.terminals.length;
}

refresh(): void {
Expand All @@ -131,13 +131,13 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
this.exceptionTerminals = {}; // populated in init()
this.assets = {}; // populated in init()
this.notifications = [];
this.averageFullness = _.sum(this.terminals, t => _.sum(t.store) / t.storeCapacity) / this.terminals.length;
this.averageFullness = _.sum(this.terminals, t => t.store.getUsedCapacity() / t.store.getCapacity()) / this.terminals.length;
}

/* Summarizes the total of all resources currently in a colony store structure */
private getAllAssets(): { [resourceType: string]: number } {
return mergeSum(_.map(this.terminals, terminal =>
(colonyOf(terminal) != undefined ? colonyOf(terminal).assets : {})));
const p = <StoreContents[]>_.map(this.terminals, terminal => (!!colonyOf(terminal) ? colonyOf(terminal).assets : {}));
return mergeSum(...p);
}

private logTransfer(resourceType: ResourceConstant, amount: number, origin: string, destination: string) {
Expand Down Expand Up @@ -174,10 +174,10 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
private remainingRoomCapacity(room: Room): number {
let remainingCapacity = 0;
if (room.storage) {
remainingCapacity += room.storage.storeCapacity - _.sum(room.storage.store);
remainingCapacity += room.storage.store.getFreeCapacity();
}
if (room.terminal) {
remainingCapacity += room.terminal.storeCapacity - _.sum(room.terminal.store);
remainingCapacity += room.terminal.store.getFreeCapacity();
}
return remainingCapacity;
}
Expand Down Expand Up @@ -362,7 +362,7 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
sendAmount = Math.floor(Math.max(sendAmount, 0));
const sendCost = Game.market.calcTransactionCost(sendAmount, sender.room.name, receiver.room.name);
sendAmount = Math.min(sendAmount, (sender.store[resourceType] || 0) - sendCost - 10,
(receiver.storeCapacity - _.sum(receiver.store)));
(receiver.store.getFreeCapacity()));

if (sendAmount < TERMINAL_MIN_SEND) {
if (verbose) log.debug(` Size too small`);
Expand Down Expand Up @@ -437,7 +437,7 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
// Terminal output state - push resources away from this colony
if (state.type == 'out' || state.type == 'in/out') {
if (terminal.cooldown == 0 && amount > targetAmount + tolerance) {
const receiver = minBy(this.terminals, t => _.sum(t.store));
const receiver = minBy(this.terminals, t => t.store.getUsedCapacity());
if (receiver) {
let sendAmount: number;
if (resource == RESOURCE_ENERGY) {
Expand All @@ -446,7 +446,7 @@ export class TerminalNetwork /*implements ITerminalNetwork*/ {
} else {
sendAmount = minMax(amount - targetAmount, TERMINAL_MIN_SEND, maxSendSize);
}
if (receiver.storeCapacity - _.sum(receiver.store) > sendAmount) {
if (receiver.store.getFreeCapacity() >= sendAmount) {
this.transfer(terminal, receiver, resource, sendAmount, 'exception state out');
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/directives/colony/poisonRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export class DirectivePoisonRoom extends Directive {
}
// Don't lock off the last position unless there's a creep with energy to build the site
const enoughEnergyToBuildFinalWall = _.any(this.overlords.roomPoisoner.roomPoisoners,
creep => creep.carry.energy >= BUILD_POWER);
creep => creep.store.energy >= BUILD_POWER);
if (this.blockPositions.length == 1 && !enoughEnergyToBuildFinalWall) {
return;
}
Expand Down
22 changes: 11 additions & 11 deletions src/directives/logistics/drop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ export class DirectiveDrop extends Directive {
static color = COLOR_GREEN;
static secondaryColor = COLOR_GREEN;

private _store: StoreDefinition;
private _drops: { [resourceType: string]: Resource[] };
private _store: StoreDefinition | undefined;
private _drops: DropContents;

memory: DirectiveDropMemory;

Expand All @@ -37,24 +37,24 @@ export class DirectiveDrop extends Directive {
return Overmind.cache.targets[this.ref];
}

private get drops(): { [resourceType: string]: Resource[] } {
private get drops(): DropContents {
if (!this.pos.isVisible) {
return {};
return {} as DropContents;
}
if (!this._drops) {
const drops = (this.pos.lookFor(LOOK_RESOURCES) || []) as Resource[];
this._drops = _.groupBy(drops, drop => drop.resourceType);
const drops = this.pos.lookFor(LOOK_RESOURCES);
this._drops = _.groupBy(drops, drop => drop.resourceType) as DropContents;
}
return this._drops;
}

get store(): { [resource: string]: number } {
get store() {
if (!this._store) {
// Merge the "storage" of drops with the store of structure
const store: { [resourceType: string]: number } = {energy: 0};
const store: StoreDefinition = { energy: 0 } as StoreDefinition;
// Merge with drops
for (const resourceType of _.keys(this.drops)) {
const totalResourceAmount = _.sum(this.drops[resourceType], drop => drop.amount);
for (const resourceType of _.keys(this.drops) as ResourceConstant[]) {
const totalResourceAmount = _.sum(this.drops[resourceType]!, drop => drop.amount);
if (store[resourceType]) {
store[resourceType] += totalResourceAmount;
} else {
Expand All @@ -80,7 +80,7 @@ export class DirectiveDrop extends Directive {

init(): void {
this.registerEnergyRequests();
this.alert(`Drop directive active - ${_.sum(this.store)}`);
this.alert(`Drop directive active - ${_.sum(this.store as StoreContents)}`);
}

run(): void {
Expand Down
24 changes: 12 additions & 12 deletions src/directives/resource/haul.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ export class DirectiveHaul extends Directive {
static color = COLOR_YELLOW;
static secondaryColor = COLOR_BLUE;

private _store: StoreDefinition;
private _drops: { [resourceType: string]: Resource[] };
private _store: StoreContents | undefined;
private _drops: DropContents;
private _finishAtTime: number;

memory: DirectiveHaulMemory;
Expand All @@ -44,13 +44,13 @@ export class DirectiveHaul extends Directive {
return Overmind.cache.targets[this.ref];
}

get drops(): { [resourceType: string]: Resource[] } {
get drops(): DropContents {
if (!this.pos.isVisible) {
return {};
return <DropContents>{};
}
if (!this._drops) {
const drops = (this.pos.lookFor(LOOK_RESOURCES) || []) as Resource[];
this._drops = _.groupBy(drops, drop => drop.resourceType);
this._drops = <DropContents>_.groupBy(drops, drop => drop.resourceType);
}
return this._drops;
}
Expand All @@ -67,30 +67,30 @@ export class DirectiveHaul extends Directive {
<StructureTerminal>this.pos.lookForStructure(STRUCTURE_TERMINAL) ||
<StructureNuker>this.pos.lookForStructure(STRUCTURE_NUKER) ||
<StructureContainer>this.pos.lookForStructure(STRUCTURE_CONTAINER) ||
<Ruin>this.pos.lookFor(LOOK_RUINS).filter(ruin => _.sum(ruin.store) > 0)[0];
<Ruin>this.pos.lookFor(LOOK_RUINS).filter(ruin => ruin.store.getUsedCapacity() > 0)[0];
}
return undefined;
}

get store(): { [resource: string]: number } {
get store(): StoreContents {
if (!this._store) {
// Merge the "storage" of drops with the store of structure
let store: { [resourceType: string]: number } = {};
let store = <StoreContents>{};
if (this.storeStructure) {
store = this.storeStructure.store;
} else {
store = {energy: 0};
store = <StoreContents>{energy: 0};
}
// Merge with drops
for (const resourceType of _.keys(this.drops)) {
const totalResourceAmount = _.sum(this.drops[resourceType], drop => drop.amount);
for (const resourceType of (_.keys(this.drops) as ResourceConstant[])) {
const totalResourceAmount = _.sum(this.drops[resourceType] as Resource[], drop => drop.amount);
if (store[resourceType]) {
store[resourceType] += totalResourceAmount;
} else {
store[resourceType] = totalResourceAmount;
}
}
this._store = store as StoreDefinition;
this._store = store;
}
// log.alert(`Haul directive ${this.print} has store of ${JSON.stringify(this._store)}`);
return this._store;
Expand Down
4 changes: 2 additions & 2 deletions src/directives/situational/stronghold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ export class DirectiveStronghold extends Directive {
const ruins = this.room.ruins;
if (containers) {
returns = returns.concat(containers.filter(container =>
container.pos.getRangeTo(this.pos) < 5 && _.sum(container.store) > 0));
container.pos.getRangeTo(this.pos) < 5 && container.store.getUsedCapacity() > 0));
}
if (ruins) {
returns = returns.concat(ruins.filter(ruin => ruin.pos.getRangeTo(this.pos) <= 3 && _.sum(ruin.store) > 0));
returns = returns.concat(ruins.filter(ruin => ruin.pos.getRangeTo(this.pos) <= 3 && ruin.store.getUsedCapacity() > 0));
}
return returns;
}
Expand Down
4 changes: 2 additions & 2 deletions src/hiveClusters/commandCenter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,13 @@ export class CommandCenter extends HiveCluster {
y = titleCoords.y + 0.25;
if (this.storage) {
Visualizer.text('Storage', {x: boxX, y: y, roomName: this.room.name});
Visualizer.barGraph(_.sum(this.storage.store) / this.storage.storeCapacity,
Visualizer.barGraph(this.storage.store.getUsedCapacity() / this.storage.store.getCapacity(),
{x: boxX + 4, y: y, roomName: this.room.name}, 5);
y += 1;
}
if (this.terminal) {
Visualizer.text('Terminal', {x: boxX, y: y, roomName: this.room.name});
Visualizer.barGraph(_.sum(this.terminal.store) / this.terminal.storeCapacity,
Visualizer.barGraph(this.terminal.store.getUsedCapacity() / this.terminal.store.getCapacity(),
{x: boxX + 4, y: y, roomName: this.room.name}, 5);
y += 1;
}
Expand Down
2 changes: 1 addition & 1 deletion src/hiveClusters/evolutionChamber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ export class EvolutionChamber extends HiveCluster {
}

const amountNeeded = this.neededBoosts[boost] + amountUnavailable;
if (amountNeeded > this.colony.assets[boost]) {
if (amountNeeded > this.colony.assets[<ResourceConstant>boost]) {
this.debug(`Requesting boost from terminal network: ${this.neededBoosts[boost]} ${boost}`);
this.terminalNetwork.requestResource(this.colony, <ResourceConstant>boost, amountNeeded);
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/hiveClusters/sporeCrawler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ export class SporeCrawler extends HiveCluster {
private registerEnergyRequests() {
// Request energy from transporters if below request threshold
for (const tower of this.towers) {
if (tower.energy < SporeCrawler.settings.requestThreshold) {
const multiplier = tower.energy < SporeCrawler.settings.criticalEnergyThreshold ? 2 : 1;
if (tower.store[RESOURCE_ENERGY] < SporeCrawler.settings.requestThreshold) {
const multiplier = tower.store[RESOURCE_ENERGY] < SporeCrawler.settings.criticalEnergyThreshold ? 2 : 1;
const dAmountdt = this.room.hostiles.length > 0 ? 10 : 0;
this.colony.logisticsNetwork.requestInput(tower, {multiplier: multiplier, dAmountdt: dAmountdt});
}
Expand Down
4 changes: 2 additions & 2 deletions src/logistics/Energetics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export class Energetics {

static lowPowerMode(colony: Colony): boolean {
if (colony.stage == ColonyStage.Adult) {
if (_.sum(colony.storage!.store) > this.settings.storage.total.cap &&
colony.terminal && _.sum(colony.terminal.store) > this.settings.terminal.total.cap) {
if (colony.storage!.store.getUsedCapacity() > this.settings.storage.total.cap &&
colony.terminal && colony.terminal.store.getUsedCapacity() > this.settings.terminal.total.cap) {
return true;
}
}
Expand Down
Loading