I need help doing Mad Maxer in Java. My hero just goes in circles.

Here’s my code:

``````// Attack the enemy that's farthest away first.

while(true) {
var farthest = null;
var maxDistance = 0;
var enemyIndex = 0;
var enemies = hero.findEnemies();

// Look at all the enemies to figure out which one is farthest away.
while (enemyIndex < enemies.length) {
var target = enemies[enemyIndex];
enemyIndex += 1;

// Is this enemy farther than the farthest we've seen so far?
var distance = hero.distanceTo(target);
if (distance > maxDistance) {
maxDistance = distance;
farthest = target;
}
}

if (farthest) {
// Take out the farthest enemy!
// Keep attacking the enemy while its health is greater than 0.
while (enemies.health > 0) {
hero.attack(enemy);
}
}
}
``````

Why did you delete?(20)

You name the target that you need to attack farthest, not enemy, so try to fix that.
Do you need any more assistance at this level?

Wait a sec I’ll fix it and tell you

1 Like

Nope, still confused.

This is my code now:

``````// Attack the enemy that's farthest away first.

while(true) {
var farthest = null;
var maxDistance = 0;
var enemyIndex = 0;
var enemies = hero.findEnemies();

// Look at all the enemies to figure out which one is farthest away.
while (enemyIndex < enemies.length) {
var target = enemies[enemyIndex];
enemyIndex += 1;

// Is this enemy farther than the farthest we've seen so far?
var distance = hero.distanceTo(target);
if (distance > maxDistance) {
maxDistance = distance;
farthest = target;
}
}

if (farthest) {
// Take out the farthest enemy!
// Keep attacking the enemy while its health is greater than 0.
while (enemies.health > 0) {
hero.attack(farthest);
}
``````

I deleted because the suggestion I made wasn’t the problem. By the time I’d written out the problem, AnseDra had answered it!

enemies is an array, so doesn’t have a health property. Which one enemy are you trying to attack (clue it isn’t ‘farthest’)?

1 Like

What @jka2706 is trying to say is to check if the farthest’s health is bigger than 0, not the array enemies because the array do not have the health propety.
Do you need any more assistance at this level?

Thanks @AnSeDra and @jka2706!!

No problem! And congratulations for completing the level!