[SOLVED] Conveneient Enemy

My code doesn’t work. It does everything right except for attacking at the end. Here’s my code:

for x in range(8, 73, 16):
    hero.moveXY(x, 22)
    # Peasants know whom to summon.
    peasant = hero.findNearest(hero.findFriends())
    message = peasant.message
    if message:
        # Words are seaparated by whitespaces.
        words = message.split(" ")
        # "words" is an array of words from the "message".
        # Get the last word. It's the required unit type.
        unit = words[len(words) - 1]
        # Summon the required unit type.
        hero.summon(unit)

for i in range(len(hero.built)):
    unit = hero.built[i]
    # Command the unit to defend the unit's position.
    hero.command(unit, "defend", unit.pos)
    enemy = hero.findNearestEnemy()
    
# Defend the last point yourself:
if enemy:
    hero.attack(enemy)

It might be that I need to do:

while enemy.health > 0:
    hero.attack(enemy)

Your code is almost right.
Think about where you called the line:

When will you look for the enemy? Is the enemy there at that point? Do you need to call it again?
Remember when you make a variable like enemy, it only makes it once, it’s not constantly updating it to the nearest enemy.
I hope this helps
Danny

I added hero.moveXY(71, 51) and then moved the find nearest enemy command after it and it worked.

1 Like