Mountain mercenaries, Python -- commanding, but they don't listen


#1

My code finds coins and summons soldiers perfectly, but the commanding is on the fritz. If I put a self.say(“test”) below my command-to-attack line, it runs, so it’s apparently noticing the enemies and getting down to that part of the code ( I initially thought this was a problem with detecting enemies), but my guys appear to be not listening to me. Where am I going wrong?

loop:
    # Move to the nearest coin.
    # Use move instead of moveXY so you can command constantly.
    coin = self.findNearest(self.findItems())
    self.move(coin.pos)

    # If you have funds for a soldier, summon one.
    if self.gold > self.costOf("soldier"):
        self.summon("soldier")
        
    enemy = self.findNearest(self.findEnemies()) 
    if enemy:
        # Loop over all your soldiers and order them to attack.
        soldiers = self.findFriends()
        soldierIndex = 0
        soldier = soldiers[soldierIndex]
        while soldierIndex < len(soldiers):
            
            # Use the 'attack' command to make your soldiers attack.
            self.command(soldier, "attack", enemy)
            soldierIndex = soldierIndex+1

#2

You’ll need to update the soldier variable within the while loop. Right now it seems you are only commanding the first soldier in the array.


#3

Ah-ha! Thank you, that’s done it.


#4

what do you mean by update the soldier variable


#5

Look at where the soldier = soldiers[soldierIndex] is. It is only being updated once inside the while-true loop


#6

So serg, how do I update it?


#7

To update variable “soldier”, make sure you put soldier = soldiers[soldierIndex] inside the while loop.

That way, every time the code loops, soldier will reassigned to the next object in the array, or the next soldier.

If you do not do that, the code will use the old “soldier”, or the first soldier in the array.

Instead of looping through the array and commanding all the soldiers to attack, you only command one soldier to attack.