Search code examples
javascriptscreeps

Screeps get all creeps with specific memory (role)


I'm trying to figure out how to get every creep with a specific memory or role like harvester in a variable... I can't seem to figure it out.

I already tried:

module.exports = function(){

    for(var i in Game.creeps){
        if(i.memory == 'Harvester'){
            var Harvesters = Game.creeps[i];

            if(Harvesters.index < 3){
                Game.spawns.Spawn1.createCreep([Game.WORK, Game.CARRY, Game.MOVE],'Harvester'+ Harvesters.length, 'Harvester');
            }
        }
    }
}

But this obviously wouldn't work...


Solution

  • You can create another array from the creeps with harvester role:

    var harvesters = [];
    for(var i in Game.creeps) {
        if(Game.creeps[i].memory== 'harvester') {
        harvesters.push(Game.creeps[i]);
    }
    
    if(harvesters.length < 3){
        Game.spawns.Spawn1.createCreep([Game.WORK, Game.CARRY, Game.MOVE], null, 'Harvester');
    }
    

    Or using lodash:

    var harvesters = _.filter(Game.creeps, {memory: 'harvester'});
    
    if(_.size(harvesters) < 3){
        Game.spawns.Spawn1.createCreep([Game.WORK, Game.CARRY, Game.MOVE], null, 'Harvester');
    }