Jari Van Melckebeke
Jari Van Melckebeke

Reputation: 85

screeps - can't make variable in source

I am new to Screeps (love it) and I am having a hard time to create a variable for all sources in the room. I am trying to make sure only 3 creeps work on the same source, so I have following code-snippet for my harvester and my main module

Main

var sources = Game.spawns.Spawn1.room.find(FIND_SOURCES);
for (var a in sources) {
  var source = (sources[a]);
  source.memory.numPeopleAt = 0;
}
module.exports.loop = function () {
...
}

harvester

var sources = creep.room.find(FIND_SOURCES);
for (var s in sources) {
    if (creep.harvest(sources[s]) == ERR_NOT_IN_RANGE && sources[s].memory.numPeopleAt < 3) {
        creep.moveTo(sources[s]);
        sources[s].memory.numPeopleAt++;
        break;
     }
}

I know I still have to make a function that does sources[s].memory.numPeopleAtt--

Thanks in advance,

Jari Van Melckebeke

Upvotes: 2

Views: 585

Answers (2)

DanielR31D
DanielR31D

Reputation: 85

This will set source to the closest source without another harvester near it

var source = creep.pos.findClosestByPath(FIND_SOURCES, {filter: (s) => s.pos.findInRange(FIND_MY_CREEPS, 1, {filter: (c) => c.memory.role == 'harvester' && c.name != creep.name})[0] == undefined});

Edit it to fit your needs

Upvotes: 0

Adam
Adam

Reputation: 7207

Source doesn't have a memory property like Creep does. However, you can add something to the main memory object.

var sources = Game.spawns.Spawn1.room.find(FIND_SOURCES);
if (!Memory.sources) {
    Memory.sources = {};
}
_.each(sources, function(source) {
    if (!Memory.sources[source.id]) {
        Memory.sources[source.id] = { numPeopleAt: 0 };
    }
});

One thing to note is that your code will run every game tick, so you only need to initialize something if it hasn't already been initialized (that's what the if-checks are for).

Upvotes: 1

Related Questions