List creeps and filter



  • Hello everybody!
    I am new to the game and haven't done much JavaScript. But I am enjoying it a lot and am using the forum and StackExchange to slowly work my way forward. Today I encountered one problem that I think was worth asking abut here:

    I use two calls to list certain creeps, but I get very different behaviour of the resulting (arrays?)

    Game.spawns.Spawn1.room.find(FIND_CREEPS, {filter: function(object) {return object.memory.role == 'Harvester'}});
    //Returns all Harvesters in the room, as expected. Individual elements of the result can be passed to creeps as commands

    or

    _(Game.creeps).filter({ memory: { role: 'Harvester' }});
    //Returns all my Harvesters in the world, as expected. But individual elements are not recognized by commands to other creeps.
    Can anyone tell me what's going on here?
    Thanks a lot in advance!


  • It was pointed out to me that this would not work this way. Instead, I am now iterating over all my creeps to find the roles I want:

    function GetCreepsByRole(role){
    var CreepList = [];
    for (var creepname in Game.creeps){
    if (Game.creeps[creepname].memory.role == role){
    CreepList.push(Game.creeps[creepname]);
    }
    }
    return CreepList
    }


  • I've ran into this exact same problem today, with this code:

    var drops = _(this.memory).filter(function(node) {
    return node.amount - node.capacity > 0;
    }).map(function (node) {
    return Game.getObjectById(node.id);
    });

    If you're chaining lodash method calls, they will get wrapped in a lodash object and you need to call value() as the last method in the chain to execute it and unwrap the result. The proper block looks like this:

    var drops = _(this.memory).filter(function(node) {
    return node.amount - node.capacity > 0;
    }).map(function (node) {
    return Game.getObjectById(node.id);
    }).value();

    You can read more about this here.

     

    In other words, you last method call should look like this:

    _(Game.creeps).filter({ memory: { role: 'Harvester' }}).value();


  • The first search looks through the Spawn1's room and returns all creeps (yours and others) with a memory.role set to 'Harvester'.

    The second search looks through all creeps stored in Game.creeps (regardless of if they are in the same room or not, and only returns your creeps) and returns anything with a found memory.role == 'Harvester' similar to before.

     

    Most likely you'll only notice that as soon as a creep leaves your spawn room they will vanish from the first search but not the second.  I haven't messed with filter though so this assumes it returns anything at all.