# Mad Maxer: While loop stuck? [Solved]

Just a note before I start this is my first post so let me know if I get something wrong.

So on the level Mad Maxer (free level in desert) I’m running a code that seems to target first enemy that isn’t a decoy, but after that nothing else runs. After looking through my code to see what runs, my while loop seems to have finished.

``````farthest = None
maxDistance = 0
enemyIndex = 0
enemies = hero.findEnemies()
while enemyIndex < len(enemies):
target = enemies[enemyIndex]
enemyIndex += 1
distance = hero.distanceTo(target)
if distance > maxDistance:
maxDistance = distance
farthest = target
if farthest:
while farthest.health > 0:
hero.attack(farthest)
``````

My variable “enemies = hero.findEnemies()” seems to finish, but putting the variable in a while-true loop outputs only runs the “hero.findEnemies()” command and i eventually get killed by the other enemies while being shoved into a corver. Thanks in advance!

Edit: I did format my code correctly right? I read a lot of other people asking for formatted code on other posts…

Hello and welcome to codecombat discourse! This is a cozy forum where you can share ideas, share fan art, get assistance for code, etc! Before you proceed, we hope that you review this topic, which shows all essentials of this board! Thanks!

i think That’s because you’re incrementing enemyIndex right after the while, so the things under that don’t run. Put the enemyIndex +=1 under the farthest = target. That’s just what I think

1 Like

And yes, your code is formatted perfectly. Great job with that!

4 Likes

Hi. Instead of `while farthest.health > 0`, you can put `if` instead of while. While and if are different, but it would seem that you would put while in because of the comments written on n the level. Try that perhaps?

1 Like

Yes he is.
20 characters

1 Like

hmmmm moving the enemyIndex += 1 and using and if loop don’t work, but they don’t show error messages. However putting a while loop around everything seems to work?..

So… It’s solved?

I guess? I do still want to know why a while true loop around everything works. I’ll keep looking

You need a while true loop around everything to continuously check the `if farthest: ` part of the code. If you’re not running that over and over again, it would only check once, instead of checking constantly.

2 Likes

FYI, click the solution button on which post helped you the most after you finish. It will close the topic after 12 hours, and edit the title with “[solved]” or something of that kind

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.