Loop breaks without being told

So, I’m new to Python and code combat. I made a combat mechanism for Kithgard Brawl that should work properly, and it does until the loop stops working…

The mechanism is as follows:

# Survive the waves of ogres.
# If you win, the level gets harder, and gives more rewards.
# If you lose, you must wait a day to re-submit.
# Each time you submit gives a new random seed.
loop :
    if self.findNearest(self.findItems()) is not None :
        potion = self.findNearest(self.findItems())
        self.moveXY(potion.pos.x, potion.pos.y)
    if(self.findNearest(self.findEnemies()) is not None) :
        if(self.isReady("cleave") and len(self.findEnemies()) > 3) :
            if self.distanceTo(self.findNearest(self.findEnemies())) > 5 :
        elif(self.isReady("bash") and self.findNearest(self.findEnemies()).health) :
        else :
    if self.findNearest(self.findEnemies()) is None :
        self.moveXY(40, 34)

In the instance it is now, the loop breaks whenever the hero picks up the potion, but that hasn’t been a problem with the code before. It could also be that it happens the second time it tries to call


because that happens immediately after. However, for either scenario, I don’t know how to fix it

You should use variables to store specific things for your code to reuse later.

Compare the following two pieces of code:

enemy = hero.findNearest(hero.findEnemies())
if(enemy.health > 10 and enemy.type == "ogre"):


if(hero.findNearest(hero.findEnemies()).health > 10 and hero.findNearest(hero.findEnemies()).type == "ogre"):

One extra line helps make the code much easier to understand and read.


if hero.findNearest(hero.findItems()) is not None:

is equivalent to:

if hero.findNearest(hero.findItems()):

because None is equivalent to False inside the conditional.

Why are you waiting 5 seconds before cleaving? 5 seconds is a long time to let a munchkin twhack at you.