Mountain Mercenaries (Stuck)

I am stuck on Mountain Mercenaries.There are just too many enemy units for my soldiers to handle, and soldiers aren’t attacking until they get attacked. How do I fix my code?

while True:
    # Move to the nearest coin.
    # Use move instead of moveXY so you can command constantly.
    coins = self.findItems()
    coinIndex = 0
    coin = coins[coinIndex]
    if coin:
        self.move(coin.pos)

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

Its because your only ordering one soldier to attack which is the first one in the array.

while soldierIndex < len(soldiers):
            hero.command(soldier, "attack", enemy) # Does not change the soldiers Index
            soldierIndex += 1

Try

if enemy:
        # Loop over all your soldiers and order them to attack.
        
        soldiers = hero.findFriends()
        soldierIndex = 0
                                                           #Moved Line
        
        # Use the 'attack' command to make your soldiers attack.
        while soldierIndex < len(soldiers):
            soldier = soldiers[soldierIndex]              # To here
            hero.command(soldier, "attack", enemy)
            soldierIndex += 1
2 Likes

I am also having trouble with this level. My soldiers just get overpowered by the ogres. Here is my code:

while True:
    # Move to the nearest coin.
    # Use move instead of moveXY so you can command constantly.
    coins = hero.findItems()
    coinIndex = 0
    coin = coins[coinIndex]
    if coin:
        hero.move({"x": coin.pos.x, "y": coin.pos.y})
    # If you have funds for a soldier, summon one.
    if hero.gold > hero.costOf("soldier"):
        hero.summon("soldier")
    enemy = hero.findNearest(hero.findEnemies())
    if enemy:
        soldiers = hero.findFriends()
        soldierIndex = 0
        # Use the 'attack' command to make your soldiers attack.
        while soldierIndex < len(soldiers):
            soldier = soldiers[soldierIndex]
            hero.command(soldier, "attack", enemy)
            soldierIndex += 1

Simplify that to this:

coin=hero.findNearestItem()
if coin:
    hero.move(coin.pos)

Also, I prefer you start using for loops instead of while loops. They make handling arrays easier.

Thanks for the help!