[SOLVED]Convenient enemy (Python)

# Ogres are hiding in woods. Protect the peasants.
# The last word in the peasants' messages are a hint.
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.
for i in range(len(hero.built)):
    unit = hero.built[i]
    hero.summon("soldier")
    # Command the unit to defend the unit's position.
    hero.command(friend, "attack", target)
    nearest = hero.findNearestByType("potion")
    enemies = hero.findNearest(hero.findEnemies())
    
    # Defend the last point yourself:
    if enemy:
        hero.attack(enemy)

2 Likes

I’m not sure why you have your hero looking for potions in the second for loop, but that needs to go away. All that is needed in this loop is the assignment of the unit variable and the hero.command method.

In the if conditional of the first for loop is where you should be summoning troops. Also, you are summoning just soldiers. Look at the second comment on line 2. You need to summon different units for different columns according to what the peasant tells you in their message. To see the message from the peasant, after the if conditional, put a line hero.say(message). That may help you understand better what’s going on. You have to take the last word of the peasant message and assign it to a variable. Then, summon a unit according to that variable. That way, when you get a different seed upon submit, it will summon the correct unit. This should be in the if message conditional, not the second for loop where you currently have it.

Make these changes and if it still doesn’t work, post your changed code and we’ll work on it from there.

2 Likes

I need help with this part

# Summon the required unit type.
1 Like

If you have done as I stated above and used the hero.say(message) in the if conditional, then you can see that the unit type you’re trying to summon is the last word of the peasant’s message. So, the question is, how do you code that? Well, you’ve defined message. That’s a good start. And you’ve defined what the words in the message are. Great! So how are you going to tell the code to just look at the last word of the message to obtain the unit type?

Think of the message as an array of words. You’ve seen these arrays before. You want the last word of the message so unit is assigned to words[len(words) - 1]. We do it like this so that regardless of how long the message is, we’re always going to obtain just the last word. Once you have defined unit, just summon unit.

2 Likes

Thanks :smiley:
(20 characters)

1 Like