Kithgard Brawl 2 in Javascript: findEnemies Not Working (Bug or Feature?)


#1

In Kithgard Brawl, I am not able to use “findEnemies” even though that ability is granted by the Fine Telephoto Lenses.

With the following code, the hero never says anything.

loop {
    var enemies = this.findEnemies();
    if (enemies) {
        this.say(enemies);
    }
}

The code works if I use “findNearestEnemy”, and the hero says the enemy’s name.

loop {
    var enemy = this.findNearestEnemy();
    if (enemy) {
        this.say(enemy);
    }
}

Is this a bug, or is the findEnemies method blocked for this challenge? (It worked in Kithgard Brawl 1).


#2

An array is always truthy (at least in JavaScript), regardless of how many elements it has, which is why your if condition runs. this.say works by converting the argument into a string ('' + [] becomes ''). The hero apparently doesn’t say anything when the string is empty. So when there are no enemies, the array is empty, so the string value is '', and the hero doesn’t say anything. If there were enemies your hero would say something like "Grot,Brak,Treg", etc.

Now, if there were actually enemies and your hero isn’t saying anything, that’s a problem.

You could try fixing this by checking enemies.length. 0 evaluates to false.

However, It would be nice to see something that indicates that there’s a value (especially since null and undefined cause problems when sometimes I just want to test if something is null/undefined).


#3

Good idea. I’ve changed it so that saying an empty array or object now show [] or {}.


#4

Great explanation! Thank you!