hi guys,
i’m really struggling with these loops. just when i think i’ve got them down i somehow create a infinite loop. could someone take a look at what i’ve done and explain what i’ve done wrong please.
the hero just stands there and only a few soldiers are summoned.
many thanks.
# Summon some soldiers, then direct them to your base.
# Each soldier costs 20 gold.
while hero.gold > hero.costOf("soldier"):
hero.summon("soldier")
soldiers = hero.findFriends()
soldierIndex = 0
# Add a while loop to command all the soldiers.
while soldierIndex < len(soldiers):
soldier = soldiers[soldierIndex]
hero.command(soldier, "move", {"x": 50, "y": 40})
soldierIndex += 1
# Go join your comrades!
hero.move({"x":50, "y" : 40})
only problem is that if i change the while to an if he only summons one soldier.
with the followig code though, he summons all the soldiers, heads towards the X but it times out?
# Summon some soldiers, then direct them to your base.
# Each soldier costs 20 gold.
while hero.gold > hero.costOf("soldier"):
hero.summon("soldier")
soldiers = hero.findFriends()
soldierIndex = 0
# Add a while loop to command all the soldiers.
while soldierIndex < len(soldiers):
soldier = soldiers[soldierIndex]
hero.command(soldier, "move", {"x": 50, "y": 40})
soldierIndex += 1
# Go join your comrades!
hero.move({"x":50, "y" : 40})
I didn’t notice you had move. Move will make your hero go to the spot, but only for a short period, If you have in in a loop, it will run as long as the loop is true. Not the case with moveXy, it makes you move to the spot at once.
Sorry if I’m causing more confusion, but I think that’s because you used hero.move(). If you use hero.move() outside a loop it doesn’t work.
Even if you put it inside a loop it doesn’t always work.
It didn’t work when you put it in second loop because the condition was only true for a short amount of time (soldierIndex < len(soldiers). You can command soldiers once and they keep moving to wherever you commanded them to go until you tell them to stop. With hero.move() however, you only moved while you were commanding the soldiers to move (which doesn’t take very long), so you only moved half the distance that the soldiers did.
To solve this you could use hero.moveXY() as you have done, or you could do something like:
while hero.pos.x < 50:
hero.move()…
Outside the second loop.
Danny
thanks @Deadpool198 ,
I get it now, makes complete sense.
And yes, i think that using while hero.pos.x < 50 #or whatever number it is would have been the best idea.