How do I make a loop work while attacking?


#1

I’m doing Ogre Encampment. I am powerful enough and can easily tank the ogres and break the chest but I want to know how I’m supposed to make my character attack when he is being attacked or search for enemies while he is attacking things that don’t die quickly.
My code

enemy = self.findNearestEnemy()

loop:
    enemy
    # Use if/else.
    if enemy:
        self.attack(enemy)
    else:
        self.attack("Chest")

Enemies aren’t immediately loaded in so he sees none and goes for the chest but then the loop doesn’t end until the chest is destroyed. It will continuously run self.attack(“Chest”) until the end. Then it will run the loop again.


#2

just a guess here. not big into python but remove the first line in your loop and add your enemy declaration inside the loop. If you don’t set the variable on every iteration of the loop it will never update with anything other than the moment the script was run.

loop:
    enemy = self.findNearestEnemy()
    if enemy:
        self.attack(enemy)
    else:
        self.attack("Chest")

#3

sorry I read your post too fast thanks for the help


#4

Greetings

I have this code but my player dies before finishing tower kills please help

If there is an enemy, attack it.

Otherwise, attack the chest!

loop:
enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
else:
self.attack(“Chest”)


#5

Make sure your code is correctly indented (that all the instructions are inside the loop).
In the future surround your code by 3 back-quotes (top-left keyboard) when posting the code on the forum:

code here

Do you have the cleave sword? If not play some other levels until you obtain it.