Search code examples
javascriptscreeps

Screeps: calculate build cost of body


When playing the game screeps.com I want to calculate the cost of building the required body. See my attempt below, where cfg.body is the bodypart array, e.g. [Game.ATTACK, Game.MOVE, Game.WORK, Game.CARRY, Game.MOVE]:

var buildCost = 0;

for(var bodypart in cfg.body){
  switch(bodypart){
    case "MOVE":
    case "CARRY":
       buildCost+=50;
       break;
    case "WORK":
       buildCost+=20;
       break;
    case "HEAL":
       buildCost+=200;
       break;
    case "TOUGH":
       buildCost+=20;
       break;
    case "ATTACK":
       buildCost+=80;
       break;
    case "RANGED_ATTACK":
       buildCost+=150;
       break;
  }
  console.log(bodypart + " costs " + buildCost);
}

When printing bodypart to the console it shows the indexes (0, 1, 2, 3, ...) and the buildCost remains 0.

The cost and parts are described on the Screeps page.


Solution

  • Maybe the BODYPART_COST constant wasn't available before, but with that you can do this:

    function bodyCost (body) {
        return body.reduce(function (cost, part) {
            return cost + BODYPART_COST[part];
        }, 0);
    }