Anima-t3d Anima-t3d - 5 months ago 103
Javascript Question

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 console it shows the index (0,1,2,3,...) and the buildCost remains 0

The cost and parts are described on the creep page

Answer

I've updated my solution with using constants as @Brett does. However I changed the for in loop to a for loop because of performance as seen in this StackOverflow question

for (var index = 0; index < cfg.body.length; ++index) {
  var bodypart = cfg.body[index];
    switch(bodypart){
      case MOVE:
      case CARRY:
        buildCost += 50;
        break;
      case WORK:
        buildCost += 100;
        break;
      case ATTACK:
        buildCost += 80;
        break;
      case RANGED_ATTACK:
        buildCost += 150;
        break;
      case HEAL:
        buildCost += 250;
        break;
      case TOUGH:
        buildCost += 10;
        break;
      case CLAIM:
        buildCost += 600;
        break;
    }
  console.log(bodypart.toUpperCase()+" costs "+buildCost);
}

I also want to note that you should not use this loop each time you build a creep, you better hardcode the value. However it might be handy in case such value does not exist or you need to double check.