Files
screeps/creeps.js
2022-04-15 14:27:00 +02:00

92 lines
2.8 KiB
JavaScript

/* ###################################################################
# An inherited creep class and a module to expose it to the loop. #
###################################################################*/
const roles = require("roles");
module.exports = {
configure: function () {
// Replaces the creep class by the MyCreep class which changes the type of all Creep objects as well.
Creep.prototype = MyCreep.prototype;
setConstants();
// configure all creeps (in case new memory requirements).
for (const name in Game.creeps) {
Game.creeps[name].configure();
}
},
// All creeps execute their roles every tick.
execute: function () {
for (const name in Game.creeps) {
Game.creeps[name].execute();
}
}
};
class MyCreep extends Creep {
configure() {
}
execute() {
switch (this.memory.role) {
case roles.ROLE_HARVESTER: roles.harvest(this);
break;
case roles.ROLE_MINER:
if (this.goTo(this.memory.container_id)) {
this.harvestSource();
}
break;
case roles.ROLE_SUPPLIER: roles.supply(this);
break;
case roles.ROLE_BUILDER: roles.build(this);
break;
case roles.ROLE_UPGRADER: roles.upgrade(this);
break;
case roles.ROLE_DEFENDER: roles.defend(this);
break;
case roles.ROLE_RESERVER: roles.reserve(this);
break;
case roles.ROLE_RESERVED_HARVESTER: roles.harvest_reserved(this);
break;
}
}
// Moves to the object with given id. Returns true if arrived.
goTo(id) {
const target = Game.getObjectById(id)
if (target != null) {
if (this.pos.isEqualTo(target.pos)) return true;
this.moveTo(target);
} else {
console.log(this.name + " can't find object with id: " + id);
}
return false;
}
// harvests set or closest source, moves to it if to far and return true if fully loaded.
harvestSource() {
if (this.memory.source_id == undefined) {
this.memory.source_id = this.pos.findClosestByPath(FIND_SOURCES).id;
}
const result = this.harvest(Game.getObjectById(this.memory.source_id));
if (result == ERR_NOT_IN_RANGE) this.goTo(this.memory.source_id);
return this.store.getFreeCapacity(RESOURCE_ENERGY) == 0;
}
}
function setConstants() {
global.HARVESTER = 0;
global.MINER = 1;
global.SUPPLIER = 2;
global.BUILDER = 3;
global.UPGRADER = 4;
global.DEFENDER = 5;
global.RESERVER = 6;
global.RESERVED_HARVESTER = 7;
}