Screeps Body class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var body = new Body([CARRY, WORK, 2, MOVE]); | |
var spawn = Game.spawns.Spawn1; | |
if (spawn.energy >= body.cost()) { | |
spawn.createCreep(body.longBody()); | |
} | |
var creep = Game.creeps.John; | |
var body = new Body(creep.body); | |
console.log(creep, 'weight ratio: ', body.weight(creep.energy)); // useful for pathing |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Descriptor of a creep body | |
function Body(body) { | |
this.body = body; | |
this._isCreep = typeof body[0] === 'object'; | |
this._cost = undefined; | |
this._weight = undefined; | |
} | |
_.assign(Body.prototype, { | |
// How much energy is needed to build this body | |
cost: function() { | |
if (this._cost !== undefined) { | |
return this._cost; | |
} | |
var mult = 1; | |
var isCreep = this._isCreep; | |
return this._cost = this.body.reduce(function(cost, desc) { | |
var part = isCreep ? desc.type : desc; | |
if (typeof part === 'number') { | |
mult = part; | |
return cost; | |
} else { | |
var tmp = cost + BODYPART_COST[part] * mult; | |
mult = 1; | |
return tmp; | |
} | |
}, 0); | |
}, | |
// Weight ratio of this creep | |
weight: function(energy) { | |
if (this._weight !== undefined) { | |
return this._weight; | |
} | |
var move = 0, len = 0; | |
var mult = 1; | |
var isCreep = this._isCreep; | |
this._weight = this.body.forEach(function(desc) { | |
var part = isCreep ? desc.type : desc; | |
if (typeof part === 'number') { | |
mult = part; | |
} else { | |
if (part === CARRY) { | |
if (energy > 0) { | |
var tmp = Math.ceil(Math.min(energy / CARRY_CAPACITY, mult)); | |
len += tmp; | |
energy -= tmp * CARRY_CAPACITY; | |
} | |
} else if (part === MOVE) { | |
move += mult; | |
} else { | |
len += mult; | |
} | |
mult = 1; | |
} | |
}); | |
return move ? Math.ceil(len / move) : undefined; | |
}, | |
// Get the long-form body of this creep | |
longBody: function() { | |
var body = []; | |
var mult = 1; | |
var isCreep = this._isCreep; | |
this.body.forEach(function(desc) { | |
var part = isCreep ? desc.type : desc; | |
if (typeof part === 'number') { | |
mult = part; | |
} else { | |
for (var ii = 0; ii < mult; ++ii) { | |
body.push(part); | |
} | |
mult = 1; | |
} | |
}); | |
return body; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment