Mad maxer- help needed

Here’s my code. My hero keeps heading for the flying enemy but then turns back to attack the decoys. What’s wrong with it?

# Attack the enemy that's farthest away first.

while True:
    farthest = None
    maxDistance = 0
    enemyIndex = 0
    enemies = hero.findEnemies()

    # Look at all the enemies to figure out which one is farthest away.
    while enemyIndex < len(enemies):
        target = enemies[enemyIndex]
        enemyIndex += 1

        # Is this enemy farther than the farthest we've seen so far?
        distance = hero.distanceTo(target)
        if distance > maxDistance:
            maxDistance = distance
            farthest = target

    if farthest and farthest.health > 0:
        # Take out the farthest enemy!
        # Keep attacking the enemy while its health is greater than 0.
        hero.attack(farthest) 
        pass

1 Like

Hello mouse, and welcome to the CodeCombat discourse!
Your code looked fine, so I tried running it, and it looks like it worked. You should try running again and see if it works.

Hi mouse,

Welcome to the forum!

I haven’t tried running your code, but I notice that you use an if statement here:

    if farthest and farthest.health > 0:
        # Take out the farthest enemy!

but the comment says:

        # Keep attacking the enemy **while** its health is greater than 0.

Does that make sense?

Jenny

Welcome Mouse!
@jka2706, it does seem like “while” would mean you should use “if”.
Because you only attack while/if the enemy’s health is greater than 0.

I don’t want to add to the confusion, but I think you should use and if statement to check for farthest and that it’s alive. Then, inside the if statement, you can use a while loop to attack the enemy until it’s health < 0.
Danny

1 Like