How to extend the creep class in screeps

4.1k Views Asked by At

I am having a hard time trying to figure out how to extend the creep class to add my own functions in the new javascript mmo game, Screeps -> www.screeps.com

2

There are 2 best solutions below

3
On BEST ANSWER

I dunno how to do that, but I created a wrapper class like this one:

You created a function for calling memory, and try to use it s property. See below: var _ = require("lodash");

function MyCreep(creep){
    this.creep = creep;
    this.memoryProp = creep.memory;
}

MyCreep.prototype.memoryFunc = function(){
    return this.creep.memory;
};

MyCreep.prototype.moveTo = function(target){
    this.creep.moveTo(target);
}

MyCreep.prototype.myFunction = function(target){
    //TODO something
}

So when I need to deal with creep, I do:

var myCreeps = [];
for (var creep in Game.creeps){
    creep.memory.role = "hello memory";
    var myCreep = new MyCreep(Game.creeps[creep]);
    myCreeps.push(myCreep);      ;
    console.log("original creep memory: "+creep.memory.role);
    console.log("my creep memory func: "+myCreep.memoryFunc().role);
    console.log("my creep memory prop: "+myCreep.memoryProp.role);
}

or

var myCreeps = [];
_.forEach(Game.creeps, function(creep){
    var myCreep = new MyCreep(creep);
    myCreeps.push(myCreep);
});

and then deal with myCreeps, locally stored.

1
On

A bit of an old thread, and I am not sure if Screeps has changed since the initial query was posted, but here are my thoughts...

Why have a wrapper class?? why not extend the original / game provided Creep class ?

e.g.

Creep.prototype.myFunction = function(target){
         // my logic
       }

Make sure to check out the screeps inheritance structure.. (Google the screeps API and check out the 'Prototypes' section on the landing page)

This can save a lot of duplicate code, for example one declaration of an inherited function in the 'Structure' prototype may save a seperate declaration for each individual Structure sub class protocols.