Hold the Forest (JS) Code. Help required!


#1

Hi Guys at CodeCombat!

I am a real beginner at Coding. I am trying to solve the following level:

World 2: BackWoods Forest --> Hold the Forest

You can make out my logic looking at the extra comments I have added in the code below.

Here’s my problem: My character does’nt move even after I place any one of the Flags whether be it Green, Violet or Black.
What is wrong with my code?

  // Use flags to join the battle or retreat.
  // If you fail, press Submit again for new random enemies and try again!
  // You'll want at least 300 health, if not more.
    loop {
    var enemy = this.findNearestEnemy();
    var flag = this.findFlag();
    if(flag) {
        // If Green Flag
        if(flag.color == "Green"){
        // Find the position of the Green flag.
        var fx = flag.pos.x;
        var fy = flag.pos.y;
        // Move to Green flag
        this.pickUpFlag(flag);
        }
        // If Flag = Violet or Blue or Green,
        // Pick up the flag in the order: Violet>Black>Green
        if(flag.color == "Violet"){
        this.pickUpFlag(flag);
        }else if(flag.color == "Black"){
            this.pickUpFlag(flag);
            }
    } else if (enemy) {
       // Find enemy distance
       var distance = this.distanceTo(enemy); 
       // Retreat if distance to enemies very close to (old position of Green Flag)
       if(distance<5){
            this.moveXY(fx, fy);
            }
        // Fight with cleave.    
        // Fight!
        this.cleave(enemy);
    }
}

Please help me out!


#2

The colors are “green”, “black”, “violet” all in small letters.

Another thing: if you have a lot of actions, it is better to skip the loop once you decide on an action:

loop{
    flag=this.findFlag();
    if(flag){
        this.pickUpFlag();
        continue;
   }
   coin=this.findNearestItem();
   if (coin){
        this.move(coin.pos);
        continue;
      }
  enemy= thins.findNearestEnemy();
  // and so on
}

continue skips to the end of the loop. In this way your hero can only take one action per loop. So you test the actions following their priority order.
Like this you do not have to write a system of nested ifs. There are difficult to follow and error prone.


#3

Thanks for your reply! :slightly_smiling: I will certainly incorporate continue instead of multiple nested-if's to avoid confusion during debugging.