Hello, everyone. The first code I wrote, following the instructions, was this, but it didn’t work. The hero didn’t hit. He actually froze.
// This function checks if the enemy is in your attack range.
function inAttackRange(enemy) {
var distance = hero.distanceTo(enemy);
// Almost all swords have attack range of 3.
if (distance <= 3) {
return true;
} else {
return false;
}
}
// Attack ogres only when they’re within reach.
while (true) {
// Find the nearest enemy and store it in a variable.
var enemy = hero.findNearestEnemy();
Call inAttackRange(enemy), with the enemy as the argument
and save the result in the variable canAttack.
var canAttack = inAttackRange(enemy);
If the result stored in canAttack is true, then attack!
if (canAttack) {
hero.attack(enemy);
}
}
> The enemy variable had to adapt to the if condition, so the character died without attacking because he had the enemies too close. So I deleted everything and made it simple.
while (true) {
// Find the nearest enemy and store it in a variable.
var enemy = hero.findNearestEnemy();
if (enemy) {
hero.attack(enemy);
}
Surprise! It worked! Obviously, that wasn’t what the exercise asked for. I suspected that since the enemies surrounded the hero at the beginning instead of moving around the whole scenario, that was the source of the problem and the bug. I searched YouTube and saw videos where the enemies moved around (and there my first failed code worked perfectly).