[SOLVED]Can't get out of loop: continue not right for the job?


#1

in Bash 'em all, the following code produces a timeout:

while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.bash(enemy)
        hero.moveXY(40, 33)
        hero.wait(5)
    else:
        continue
hero.moveXY(18, 11)
hero.moveXY(64, 13)
hero.moveXY(65, 58)
hero.moveXY(15, 55)

It gets stuck on line 7 after slaying the last enemy:

I realize that the common way of doing this is by getting an array of enemies and repeating the loop len(enemies) -1 times, but I want to to understand why this above isn’t working.

They way I see it, if there is no enemy because they were all slain, the loop should be exited and code execution should shift to move commands. Right?


#2

No, continue as you said isn’t right for the job and that isn’t what it does, continue skips to the next iteration of a loop that has a finite property like a for-loop or a while something loop that will end at some point and it goes to the next iteration of it for example:

for enemy in enemies:
    if enemy.type != "brawler":
        continue
    else:
        return enemy

if you want something that can exit a while true loop which normally has no foreseeable end you need a break, It’s very simple you just need a break in the same place as the continue which will break any kind of loop.


#3

thanks, that was very helpful (and it solves the level - so here’s the first time I discovered two genuine working alternatives for solving a level!)!
So, break for getting out of the loop, continue for skipping to the next iteration.
But you said, continue would only work in a loop with finite property?
If it can be used for skipping to the next iteration, why not in a while-True loop?


#4

Technically you can skip an iteration of a while-True loop with continue, but it will just start from the beginning again and again and again because unlike a for-loop it has no end so continue will just repeat the code over and over again.
But yes you can skip it in certain circumstances for strategies but in your code that’s not relevant. Here’s an example of how a continue could be used in a while-True loop:

while True
    enemy = hero.findNearestEnemy()
    if enemy:
        continue 
    else:
        hero.say("no one here!")

So if there’s an enemy it won’t do anything until the enemy is gone and if there’s no enemy he’ll say: No one here!


#5

you could just say…

while True:
    enemy = hero.findNearestEnemy()
    if not enemy:
        hero.say("no one here!")
    hero.say("destroy the enemies!") #he won't say this until there is enemies

#6

How would you link it with the if statement (the hero wants to attack an enemy if there is one)?


#7

Sorry I don’t really understand, link what to what? Could you explain what you’re saying in more detail? thanks


#8

You could also do this:

while True:
    enemy = hero.findNearestEnemy()
    if not enemy:
        continue
    hero.attack(enemy)