Search code examples
javascriptscreeps

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


Solution

  • 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).