Level: Rich Forager

Little confused about creating a nested loop for this level…

Right now my hero executes the inner loop (else if (enemy)) , but does not go back to the initial loop (loop { var enemy…})

How can I get this to "jump"back to the original loop? Thanks!

loop {
var enemy = this.findNearest(this.findEnemies());
var flag = this.findFlag();
var item = this.findNearest(this.findItems());

if (flag) {
    // How do we get fx and fy from the flag's pos?
        var pos = flag.pos;
        var fX = pos.x;
        var fY = pos.y;
        this.pickUpFlag(flag);
            }
else if (item)
        {
        pos = item.pos;
        var itemX = pos.x;
        var itemY = pos.y;
        this.moveXY(itemX, itemY);
        }
else if (enemy)
loop {
    if (this.isReady("cleave")) {
         this.cleave(enemy);
        }
    else if (this.isReady("shield")){
        this.shield();
            }
     }

}

What you have created is a infinite loop, If you put a loop inside another loop it will never do it again.

For example if I did :

loop:
    self.eat("Chicken")
    self.dance("Like Nobody's Watching")
    loop:
        self.moveXY(BathroomX, BathroomY)
        self.use("Toilet")

The Loop would go to eat chicken, then dance, but then when it goes into the 2nd loop it will start to loop going to bathroom and using the toilet.

Basically if you put a loop in a loop then the code will be stuck inside the second loop because you are looping commands inside of a loop. Therefore the loop will never end (as you would know) so it would get stuck inside the 2nd loop.

(not sure if this made sense to you… Hopefully I helped…)

1 Like

The basic loop construct never ends, so you cannot do nested loops using only the loop command. I’m sure very soon they will introduce true loop structure for us. (Though I’m pretty sure you can already use it if you know it.)

You can. If you use javascript loops you should be able to “break;” out of the loop. I’m not sure if you can break out of the loop construct provided by codecombat, however, I have never tried.

Well for now inside of code combat there are no possible ways to break from a loop ATM. Hopefully soon.

Hey thanks for all the replies! ItalicUniform, your eat/dance–>bathroom loop was hilarious, but it helped me understand that concept perfectly. I think for now I’m going to simplify and use another else statement.

Actually, break statements do work in the simple loop, too. About halfway through the desert world, we’re going to get into all that stuff.

1 Like

Yippe! Can’t wait for it!

Make sure you bought great armor from the item shop! 400 health recommended.

loop:
flag = self.findFlag()
enemy = self.findNearestEnemy()
item = self.findNearestItem()

if flag:
    self.pickUpFlag(flag)
    
elif enemy:
   self.attack(enemy)
    
elif item:
    self.findNearestItem()