Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

[SOLVED] Infinite Loop on 'A Fine Mint' Level

My first time getting an infinite loop error. I gather it’s something wrong with my code that is causing it, but I am at a loss.

function pickUpCoin() {
    var coin = hero.findNearestItem();
    if(coin) {
        hero.moveXY(coin.pos.x, coin.pos.y);
    }
}

// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
function attackEnemy() {
    var enemy = hero.findNearestEnemy();
    if(enemy) {
        attackEnemy();
    }
}

while(true) {
    attackEnemy();
    pickUpCoin();
}

Thanks for the help on this.

In function attackEnemy() you have

if(enemy)  attackEnemy();

Is this some kind of recursive function? This is the cause of the infinite loop.
I don’t like the default code structure. You start to attack then you give up attacking maybe without killing the enemy. Then you start collecting coins with moveXY and this is a blind restricting action, you cannot stop in the middle of moveXY to make something else. In some cases this will prevent you to complete
the level. Fist and easiest hack is to replace moveXY() with move() but this is not the best way. You continue to have a stacking of ifs and this is the cause of multiple future errors that are hard to find.

Thank you, I was confusing attackEnemy() – a function – with hero.attack(enemy) – the method? Not sure what it’s called, but that was indeed a mistake I was making.

Thanks again.