Skip to content

Instantly share code, notes, and snippets.

@laverdet
Created July 20, 2015 05:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save laverdet/4c2a3a59ef6af4752b0e to your computer and use it in GitHub Desktop.
Screeps Body class
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
// 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