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

[Solved] Protect And Serve Help!

Hi, I was having trouble with Protect and Serve, and I’m not sure how to finish it.

# Protect the workers and animals!

# Defend these two positions:
defend = []
defend[0] = { "x": 98, "y": 28 }
defend[1] = { "x": 84, "y": 7 }
defend[2] = {"x": 96, "y":73}

soldiers = []

friends = hero.findFriends()
for index in range(len(friends)):
    friend = friends[index]
    if friend.type == "soldier":
        # Defend the workers:
        hero.command(soldier, "defend", {'x':friend.pos.x, 'y':friend.pos.y})#Error appears here

while True:
    # Use a for-loop to assign each soldier to a corresponding defend[] target
    # Use command(soldier, "defend", thang) or command(soldier, "defend", position)
    for i in range(len(defend)):
        soldier = soldiers[i]
        if soldier:
            hero.command(soldier, "defend", defend[i])
    #Pretty sure that there's something wrong with this code somehow, too.

I see a couple of issues. First, in your for index loop (as you point out), you have:

        # Defend the workers:
        hero.command(soldier, "defend", {'x':friend.pos.x, 'y':friend.pos.y})#Error appears here

Instead of actively defending, which comes later, you want to add (append) the friend to the ‘defend’ array.

Second, you’ve manually added defend[2] to the code…why?

As you’ve also pointed out, in the while True…you are intending to work through the soldiers array (iterate), but are doing so using an attribute of the defend array. You should use the soldiers array attributes instead.

Finally, if there is an enemy, kill it!

1 Like

Thanks, I changed my code, but I added the defend[2] to stop the ogres from taking that group of coins for the bonus objective. I took it out and the code worked fine, but when I tried to reinsert it, my code stopped working. Is this how I’m supposed to get the bonus objective?

Update: I told my hero to defend the position instead, and I got the bonus objective. Thank you for your help!


Well done! That was going to be my answer…the hero does it :wink: