function fullHeal() {
hero.say("here");
var paladins = hero.findByType("paladin", hero.findFriends());
var p1 = paladins[0];
var p2 = paladins[1];
while (hero.health < hero.maxHealth) {
if (p1.canCast("heal") && p2.canCast("heal")) {
hero.command(p1, "cast", "heal", hero);
hero.command(p2, "cast", "heal", hero);
}
//hero.say("1");
}
}
I’ve made this function to fully heal my hero using my 2 paladins. But for some reason this function results in an infinite loop unless i uncomment the “hero.say(“1”)” part. The weird thing is the function is not even executed if i dont have the hero.say part, but still causes an infinite loop elsewhere in my code.
Try changing the ‘while’ into an ‘if’ for the function. Also try splitting the paladins, so that if p1 can cast heal then she heals, and if p2 can heal then she heals. I suspect the problem is that if one of them can’t heal then the while loops flicks around lots of times which is detected as an infinite loop.
But if i change the while into an if, then the paladins would only heal once each right? I tried splitting the paladins but that didnt change anything.
In the case where your hero is not at full health and at least one paladin is unable to heal, your while loop has no action in it, and thus will spin forever in an infinite loop. When you include the hero.say statement, instead CodeCombat blocks for a few frames every iteration as your hero says something, preventing an infinite loop. Nick comments on the exact behavior here.
How you want to solve this issue is up to you. The hero.wait command may come in handy as a replacement for an awkward hero.say.
(A side note- I’d suggest generalizing fullHeal() with a for loop over paladins so it’s able to utilize more or less than exactly two paladins. for-of loops are worth learning about)