while True:
# Collect gold.
item = hero.findNearestItem()
hero.moveXY(item.pos.x, item.pos.y)
# If you have enough gold, summon a soldier.
if hero.gold > hero.costOf("soldier"):
hero.summon("soldier")
soldiers = hero.findFriends()
soldierIndex = 0
# Add a while loop to command all the soldiers.
soldier = soldiers[soldierIndex]
while soldierIndex < len(soldiers):
hero.command(soldiers[soldierIndex], "attack", enemy)
soldierIndex +=1
# Use a for-loop to command each soldier.
# For loops have two parts: "for X in Y"
# Y is the array to loop over.
# The loop will run once for each item in Y, with X set to the current item.
for friend in hero.findFriends():
if friend.type == "soldier":
enemy = friend.findNearestEnemy()
# If there's an enemy, command her to attack.
# Otherwise, move her to the right side of the map.
There are several issues here that need to be addressed.
First, you should be using hero.move method, not moveXY. This is because when you use moveXY, the code will not do anything else or even look at the rest of the code until the hero arrives at its destination. The move method differs in that it the hero will take a single step towards the designated destination and then see what else the code can be doing. When you have other things going on in your code, it’s best to use the move method so that your hero can command and summon troops while moving towards the item postition.
Second, you should always check to see if an item exists before moving to it. If there’s ever a split second where there are no items on the screen, the code will fail. There should always be an if item: before the move command.
Third, the structure for this is incorrect:
soldiers = hero.findFriends()
soldierIndex = 0
# Add a while loop to command all the soldiers.
It needs to be tabbed back so that it’s not inside your if hero.gold > hero.costOf("soldier"): statement.
Fourth, you aren’t really incrementing an array so this type of while loop isn’t such a great choice for what you’re trying to do. You would be much better off with just a for loop here, as stated in the comments/directions. Then command each single friend in the friends array.