Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

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


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?

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

    # If you have funds for a soldier, summon one.
    if > self.costOf("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

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.


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


what do you mean by update the soldier variable


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


So serg, how do I update it?


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.

1 Like