-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.colony.js
624 lines (564 loc) · 22.8 KB
/
data.colony.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
const remoteUtility = require("./remote.remoteUtility");
const estimateTravelTime = require("./util.estimateTravelTime");
const { getPlanData, keys } = require("./base.planningUtility");
const { roles, ROOM_SIZE, storageThresholds } = require("./constants");
const { MINER_WORK, REMOTE_MINER_WORK } = require("./spawn.spawnConstants");
const profiler = require("./debug.profiler");
const { RESERVER_COST } = require("./spawn.creepMaker");
const { MINIMUM_PICKUP_AMOUNT } = require("./constants");
const { repairThresholds } = require("./constants");
const { getSpawnTime } = require("./spawn.spawnUtility");
const {
getMissionType,
removeMission,
getAllMissions,
} = require("./mission.missionUtility");
const { MISSION_TYPES } = require("./mission.missionConstants");
class Colony {
/**
* Initializes some data for this room that is guaranteed to be persistent between ticks.
* @param {*} room
*/
constructor(room) {
this.room = room;
if (!Memory.colonies[this.room.name]) {
Memory.colonies[this.room.name] = {};
}
this.sources = this.room.find(FIND_SOURCES);
this.mineral = this.room.find(FIND_MINERALS)[0];
this.remotesNeedingRepair = [];
}
/**
* Initializes some data for this room that is not guaranteed to be persistent between ticks.
*/
initializeTickInfo() {
// Reinitialize stale objects
profiler.startSample("cache");
this.room = Game.rooms[this.room.name];
this.memory = Memory.colonies[this.room.name];
this.sources = this.sources.map((s) => Game.getObjectById(s.id));
this.mineral = Game.getObjectById(this.mineral.id);
profiler.endSample("cache");
if (!this.memory.missions) {
this.memory.missions = [];
}
// If any of our missions colonies have concluded, let's remove them as an extra safety net
const allMissions = getAllMissions();
for (const mission of this.memory.missions) {
if (!allMissions[mission]) {
this.memory.missions = this.memory.missions.filter(
(m) => m !== mission
);
}
}
// Find all creeps that this room is responsible for, not just ones in it
profiler.startSample("group creeps");
this.creeps = Object.values(Game.creeps).filter(
(c) => c.memory.home === this.room.name
);
// Dynamically intialize an array for each role
for (const role in roles) {
const propName = role + "s";
this[propName] = [];
}
// Map each role's string name found on creeps to it's code name
const roleToArrayMap = {};
Object.keys(roles).forEach((roleName) => {
roleToArrayMap[roles[roleName]] = this[roleName + "s"];
});
// Push each creep to their matching array
this.creeps.forEach((creep) => {
const array = roleToArrayMap[creep.memory.role];
if (array) {
array.push(creep);
}
});
profiler.endSample("group creeps");
profiler.startSample("finds");
this.allStructures = this.room.find(FIND_STRUCTURES);
this.structures = _.groupBy(this.allStructures, "structureType");
this.constructionSites = this.room.find(FIND_MY_CONSTRUCTION_SITES);
this.miningSites = getPlanData(
this.room.name,
keys.sourceContainerPositions
).map((container) => {
return {
pos: new RoomPosition(container.x, container.y, this.room.name),
sourceID: container.sourceID,
isReserved: true,
};
});
this.enemies = this.room.find(FIND_HOSTILE_CREEPS);
this.remoteEnemies = [];
this.invaderCores = [];
const isDecayTick = Game.time % CONTAINER_DECAY_TIME === 0 || RELOAD;
if (isDecayTick) {
this.remotesNeedingRepair = [];
}
this.remotePlans = remoteUtility.getRemotePlans(this.room.name);
this.remoteRooms = [];
if (this.remotePlans) {
// Get all rooms of our active remotes for construction site and enemy searching
const remoteRooms = new Set();
for (const remote of this.remotePlans) {
if (!remote.active) continue;
remoteRooms.add(remote.room);
// Mining sites
this.miningSites.push({
pos: new RoomPosition(
remote.container.x,
remote.container.y,
remote.container.roomName
),
sourceID: remote.source.id,
isReserved:
this.room.energyCapacityAvailable >= RESERVER_COST,
});
// Every so often, let's scan the roads of each remote to make
// sure that none of them have decayed too low
if (isDecayTick) {
for (const road of remote.roads) {
const room = Game.rooms[road.roomName];
if (!room) continue;
const roadStructure = room
.lookForAt(LOOK_STRUCTURES, road.x, road.y)
.find((s) => s.structureType === STRUCTURE_ROAD);
if (
roadStructure &&
roadStructure.hits / roadStructure.hitsMax <
repairThresholds[STRUCTURE_ROAD].min
) {
this.remotesNeedingRepair.push({
endPos: remote.container,
sourceID: remote.source.id,
});
break;
}
}
}
}
this.remoteRooms = [...remoteRooms];
for (const roomName of remoteRooms) {
const room = Game.rooms[roomName];
if (!room) continue;
// Enemies
this.remoteEnemies = this.remoteEnemies.concat(
room.find(FIND_HOSTILE_CREEPS)
);
// Construction sites
this.constructionSites = this.constructionSites.concat(
room.find(FIND_CONSTRUCTION_SITES)
);
const invaderCoreInThisRoom = room
.find(FIND_HOSTILE_STRUCTURES)
.find((s) => s.structureType === STRUCTURE_INVADER_CORE);
if (invaderCoreInThisRoom) {
this.invaderCores = this.invaderCores.concat(
invaderCoreInThisRoom
);
}
}
}
profiler.endSample("finds");
profiler.startSample("other init");
// Used for distance calculations of hauler orders
this.core = this.memory.core
? this.room.getPositionAt(this.memory.core.x, this.memory.core.y)
: this.room.getPositionAt(25, 25);
// If this colony has a spawn, let's make sure that it isn't a new colony anymore
// No need for surrogate spawns anymore
if (
getMissionType(this.room.name) === MISSION_TYPES.COLONIZE &&
this.structures[STRUCTURE_SPAWN]
) {
removeMission(this.room.name);
}
// Clear tick caches
this._spawnRequests = [];
this._pickupRequests = {};
this._dropoffRequests = {};
profiler.endSample("other init");
}
getUpgraderContainer() {
const containerPos = getPlanData(
this.room.name,
keys.upgraderContainerPos
);
if (!containerPos) {
return null;
}
return this.room
.lookForAt(LOOK_STRUCTURES, containerPos.x, containerPos.y)
.find((s) => s.structureType === STRUCTURE_CONTAINER);
}
// #region Mining
/**
* Gets the first unreserved mining site, sorting by estimated distance.
* @param {RoomPosition?} pos The position to order the sites by distance to.
* @returns An object containing some data about the mining site:
* - The position of the mining site (place to stand).
* - The ID of the source to mine.
*/
getFirstOpenMiningSite(pos = null) {
const validSites = this.miningSites;
if (pos) {
validSites.sort(
(a, b) =>
estimateTravelTime(pos, a.pos) -
estimateTravelTime(pos, b.pos)
);
}
return validSites.find((site) =>
this.canSiteHoldAdditionalMiners(site)
);
}
/**
* Determines if the given mining site can hold additional miners.
* @param {{}} site The given site.
* @returns {boolean} True if so, otherwise, false.
*/
canSiteHoldAdditionalMiners(site) {
const source = Game.getObjectById(site.sourceID);
// No view of source -> no miner there yet, so
// this must be a valid site since all sites can hold at least one miner
if (!source) return true;
// We're going to look for sites where the number of allocated miners is
// less than the amount of open spaces
// Here we'll exclude miners that will die before we arrive at the source
const allocatedMiners = this.miners.filter(
(m) =>
m.memory.miningSite &&
m.memory.miningSite.sourceID === site.sourceID &&
getSpawnTime(m.body) + m.memory.replaceTime <= m.ticksToLive
);
// First condition:
// The total number of WORK parts is less than that needed to fully mine a source
const totalWork = allocatedMiners.reduce(
(total, curr) =>
total + curr.body.filter((p) => p.type === WORK).length,
0
);
const neededWork = site.isReserved ? MINER_WORK : REMOTE_MINER_WORK;
if (totalWork >= neededWork) return false;
// Second condition:
// Fewer miners assigned than the number of open spaces next to this source
const sourcePos = source.pos;
const roomTerrain = Game.map.getRoomTerrain(site.pos.roomName);
let openSpaces = 0;
for (let x = sourcePos.x - 1; x <= sourcePos.x + 1; x++) {
for (let y = sourcePos.y - 1; y <= sourcePos.y + 1; y++) {
if (x < 1 || x > 48 || y < 1 || y > 48) {
continue;
}
if (roomTerrain.get(x, y) === TERRAIN_MASK_WALL) {
continue;
}
openSpaces++;
}
}
return allocatedMiners.length < openSpaces;
}
/**
* An array of all mineral sites in this room.
* @returns An object on mineral sites, each containing a container position and mineral ID.
*/
getMineralSites() {
const mineralSpots = [];
const mineralContainer = getPlanData(
this.room.name,
keys.mineralContainerPos
);
const mineral = Game.getObjectById(mineralContainer.mineralID);
const extractor = mineral.pos
.lookFor(LOOK_STRUCTURES)
.find((s) => s.structureType === STRUCTURE_EXTRACTOR);
if (extractor) {
mineralSpots.push({
pos: new RoomPosition(
mineralContainer.x,
mineralContainer.y,
this.room.name
),
mineralID: mineralContainer.mineralID,
extractorID: extractor.id,
});
}
return mineralSpots;
}
// #endregion
// #region Hauling
hashPickupRequest(pos, resourceType) {
return `${pos.x + pos.y * ROOM_SIZE + pos.roomName},${resourceType}`;
}
hashDropoffRequest(dropoffIDs, resourceType) {
return `${dropoffIDs.toString()}+${resourceType}`;
}
/**
* Creates a pickup request for haulers with the given parameters.
* Pickup requests under the same position and resource type will be grouped.
* @param {number} amount The amount.
* @param {ResourceConstant} resourceType The type of resource.
* @param {number} fillrate The approximate rate at which the resource will accumulate at the pickup location.
* Can be negative if resource will decay.
* @param {boolean} isSource Is this request under a source? If yes, it will only be returned
* if the energy is greater than or equal to the requesting hauler's carry capacity.
* @param {RoomPosition} pos The position of the resources to pickup.
*/
createPickupRequest(amount, resourceType, fillrate, isSource, pos) {
if (amount === 0) {
return;
}
// If a pickup request already exists for this tick at this position, let's group it
const hash = this.hashPickupRequest(pos, resourceType);
const existingRequest = this._pickupRequests[hash];
if (existingRequest && existingRequest.tick === Game.time) {
existingRequest.amount += amount;
existingRequest.fillrate += fillrate;
return;
}
// We'll assign haulers once orders are finalized
this._pickupRequests[hash] = {
requestID: hash,
tick: Game.time,
amount,
resourceType,
fillrate,
isSource,
pos,
assignedHaulers: [],
};
}
/**
* Creates a dropoff request for haulers with the given parameters.
* @param {ResourceConstant} resourceType The type of resource.
* @param {number} amount The amount.
* @param {string[]} dropoffIDs The game IDs of the structures/creeps requesting a dropoff.
* @param {boolean} isUrgent Is this request of urgent priority? Urgent requests will be considered
* before all other requests.
* Pass multiple if multiple dropoff points are acceptable (primarily for link usage).
*/
createDropoffRequest(amount, resourceType, dropoffIDs, isUrgent = false) {
if (amount === 0) {
return;
}
const hash = this.hashDropoffRequest(dropoffIDs, resourceType);
// We'll assign haulers once orders are finalized
this._dropoffRequests[hash] = {
requestID: hash,
tick: Game.time,
amount,
resourceType,
dropoffIDs,
isUrgent,
assignedHaulers: [],
};
}
/**
* Filters out any outdated requests from previous ticks. Should be called after
* all requests for this tick have been created to avoid loss of information when
* carrying over request data from the previous tick.
*/
finalizeRequests() {
if (!this.haulers) return;
// Let's figure out which haulers are assigned to which requests
const pickups = {};
const dropoffs = {};
for (const hauler of this.haulers) {
if (hauler.memory.pickup) {
pickups[hauler.memory.pickup.hash] = (
pickups[hauler.memory.pickup.hash] || []
).concat(hauler.id);
continue;
}
if (hauler.memory.dropoff) {
dropoffs[hauler.memory.dropoff.hash] = (
dropoffs[hauler.memory.dropoff.hash] || []
).concat(hauler.id);
}
}
// Let's filter out any outdated requests here
for (const hash in this._pickupRequests) {
if (this._pickupRequests[hash].tick !== Game.time) {
delete this._pickupRequests[hash];
continue;
}
// And assign haulers here
this._pickupRequests[hash].assignedHaulers = pickups[hash] || [];
}
for (const hash in this._dropoffRequests) {
if (this._dropoffRequests[hash].tick !== Game.time) {
delete this._dropoffRequests[hash];
continue;
}
// And assign haulers here
this._dropoffRequests[hash].assignedHaulers = dropoffs[hash] || [];
}
}
/**
* Returns all pickup requests, source requests will be filtered so that only ones who's amounts are
* greater than or equal to the carry capacity of the requesting creep will be returned.
* @param {Creep} creep The hauler requesting the pickup request.
* @returns {{}[]} An array of pickup requests.
*/
getPickupRequests(creep) {
const validPickups = Object.values(this._pickupRequests).filter(
(pickup) => {
if (pickup.amount < MINIMUM_PICKUP_AMOUNT) {
return false;
}
return (
!pickup.isSource ||
// Using our core as our distance since we don't want further haulers accepting the orders
// before earlier because the further ones see there as being more energy than the closer ones
pickup.amount +
pickup.fillrate *
estimateTravelTime(this.core, pickup.pos) >=
creep.store.getCapacity()
);
}
);
validPickups.forEach((pickup) => {
// Let's also figure out if this pickup point has enough haulers assigned to fill its request or not
const total = pickup.assignedHaulers.reduce((total, currID) => {
return (
total + Game.getObjectById(currID).store.getFreeCapacity()
);
}, 0);
// Note that subtracting the store amount here helps us avoid sending
// 2 haulers to go pick up a request that would normally be ignored by the second
// hauler after the first one interacted
pickup.hasEnough =
total >= pickup.amount - creep.store.getCapacity();
});
// If we have need energy delivered, let's allow energy to be taken from storage
// (only if it's above our predefined threshold for this room)
if (
this.room.storage &&
this.room.storage.store[RESOURCE_ENERGY] >
storageThresholds[this.room.controller.level]
) {
// Let's make sure we actually have dropoff requests for energy
// that aren't already able to be fulfilled
const unfilledEnergyDropoff = Object.values(
this._dropoffRequests
).find((dropoff) => {
if (dropoff.resourceType !== RESOURCE_ENERGY) return false;
const total = _.sum(
dropoff.assignedHaulers,
(h) => Game.getObjectById(h).store[dropoff.resourceType]
);
return total < dropoff.amount;
});
if (unfilledEnergyDropoff) {
validPickups.push({
amount: Math.min(
this.room.storage.store[RESOURCE_ENERGY],
creep.store.getCapacity()
),
resourceType: RESOURCE_ENERGY,
pos: this.room.storage.pos,
assignedHaulers: [],
});
}
}
return validPickups;
}
/**
* Returns all dropoff requests matching the appropriate resource type.
* @param {ResourceConstant} resourceType The type of resource.
* @returns {{}[]} An array of dropoff requests that match the resource type.
*/
getDropoffRequests(resourceType) {
// Filter for the correct request type
const validDropoffs = Object.values(this._dropoffRequests).filter(
(dropoff) => {
return dropoff.resourceType === resourceType;
}
);
// Add a few properties to each pickup request
validDropoffs.forEach((dropoff) => {
// Let's also figure out if this pickup point has enough haulers assigned to fill its request or not
const total = _.sum(
dropoff.assignedHaulers,
(h) => Game.getObjectById(h).store[dropoff.resourceType]
);
dropoff.hasEnough = total >= dropoff.amount;
});
// If we don't have any requests, let's add the storage
if (
!validDropoffs.length &&
this.room.storage &&
this.room.storage.store.getFreeCapacity()
) {
// It won't matter how much, what type, or who's assigned
// We will accept all haulers
return [
{
amount: this.room.storage.store.getFreeCapacity(),
resourceType: resourceType,
dropoffIDs: [this.room.storage.id],
assignedHaulers: [],
},
];
}
return validDropoffs;
}
/**
* Adds a hauler to the matching pickup request.
* @param {string} requestID The ID of the request.
* @param {string} haulerID The ID of the hauler to add.
*/
acceptPickupRequest(requestID, haulerID) {
const request = this._pickupRequests[requestID];
if (request) {
request.assignedHaulers.push(haulerID);
}
}
/**
* Adds a hauler to the matching dropoff request.
* @param {string} requestID The ID of the dropoff request.
* @param {string} haulerID The ID of the hauler to add.
*/
acceptDropoffRequest(requestID, haulerID) {
const request = this._dropoffRequests[requestID];
if (request) {
request.assignedHaulers.push(haulerID);
}
}
/**
* Removes a hauler from the matching pickup request, and clear its memory.
* @param {string} requestID The ID of the pickup request.
* @param {string} haulerID The ID of the hauler to remove.
*/
unassignPickup(requestID, haulerID) {
const request = this._pickupRequests[requestID];
if (request) {
request.assignedHaulers = request.assignedHaulers.filter(
(id) => id !== haulerID
);
}
}
/**
* Removes a hauler from the matching dropoff request, and clear its memory.
* @param {string} requestID The ID of the pickup request.
* @param {string} haulerID The ID of the hauler to remove.
*/
unassignDropoff(requestID, haulerID) {
const request = this._dropoffRequests[requestID];
if (request) {
request.assignedHaulers = request.assignedHaulers.filter(
(id) => id !== haulerID
);
}
}
// #endregion
// #region Spawning
addSpawnRequest(role, make, priority = 0) {
this._spawnRequests.push({ role, make, priority });
}
getSpawnRequests() {
return this._spawnRequests;
}
//# endregion
}
module.exports = Colony;