Skip to content

Auto spawning creeps

Warren Earle edited this page Jun 22, 2016 · 6 revisions

Until now, we have created new creeps directly in the console. It’s not a good idea to do it constantly since the very idea of Screeps is making your colony control itself. You will do well if you teach your spawn to produce creeps in the room on its own.

This is a rather complicated topic and many players spend months perfecting and refining their auto-spawning code. But let’s try at least something simple and master some basic principles to start with.

You will have to create new creeps when old ones die from age or some other reasons. Since there are no events in the game to report death of a particular creep, the easiest way is to just count the number of required creeps, and if it becomes less than a defined value, to start spawning.

There are several ways to count the number of creeps of the required type. One of them is filtering Game.creeps with the help of the _.filter function and using the role in their memory. Let’s try to do that and bring the number of creeps into the console.

Add the output of the number of creeps with the role harvester into the console.

var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');

module.exports.loop = function () {

    var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
    console.log('Harvesters: ' + harvesters.length);

    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        if(creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep);
    }
}
}

Let’s say we want to have at least two harvesters at any time. The easiest way to achieve this is to run StructureSpawn.createCreep each time we discover it’s less than this number. You may not define its name (if will be given automatically in this case), but don’t forget to define the needed role.

Add the logic for StructureSpawn.createCreep in your main module.

var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');

module.exports.loop = function () {

var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
console.log('Harvesters: ' + harvesters.length);

if(harvesters.length < 2) {
    var newName = Game.spawns.Spawn1.createCreep([WORK,CARRY,MOVE], undefined, {role: 'harvester'});
    console.log('Spawning new harvester: ' + newName);
}

for(var name in Game.creeps) {
    var creep = Game.creeps[name];
    if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep);
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep);
    }
}
}

Clone this wiki locally