How may I pick up coins when resting from the battle?

Hello guys, I’ve been playing the 0 level of Sarven Siege and my intended strategy has been the following: to focus only on the defense of the inferior tower, attacking enemies when they get too close to it (part 1) and picking up coins when there are not close enemies (part 2). I tried both parts separately and they both worked, however when I tried to put both parts together, Part 1 stops working and I only pick up coins, anyone knows what is happening?

#PART 1
loop:
enemies = self.findEnemies()
enemindex = 0

while enemindex < len(enemies):
    enemy = enemies[enemindex]    
    
    if enemy and enemy.pos.x > 66 and enemy.pos.y < 36:    
        enemindex = enemindex + 1
        if self.isReady("bash"):
            self.bash(enemy)
        if self.isReady("cleave"):
            self.cleave(enemy)
        else:
            self.attack(enemy)
    else:
        enemindex = enemindex + 1

#PART 2
index = 0
items = self.findItems()
while index < len(items):
coin = items[index]
if coin and coin.value > 1 and coin.pos.y < 40:
self.moveXY(coin.pos.x, coin.pos.y)
index = index + 1
if self.gold > 15:
self.moveXY(84, 22)
else:
index = index + 1

After the hero starts picking up coins, he will continue so long as there are coins in the array items. Could this be the problem? Might it be better to pick up only one coin in Part 2?

That makes sense, but would there be any way to make him pick coins until a new enemy appears? That is what I was trying to do, or in any case, how could I make him just pick a limited amount of coins and then loop it all over again (from part 1)?

What if he just picked up the nearest coin before checking again for enemies? It would do the task quite accurately and be easy to program.

Right, that is so much simpler tha using while, just tried it and worked :ok_hand: