For some reason my code doesn’t work. i get no error message.
My character attacks all enemies but doesn’t collect coins.
I can’t actually see anything being wrong with the code. Thats the frustrating thing.
Thanks in advance.
# Wait for ogres, defeat them and collect gold.
while True:
enemies = hero.findEnemies()
# enemyIndex is used to iterate the enemies array.
enemyIndex = 0
# While enemyIndex is less than len(enemies)
while enemyIndex < len(enemies):
# Attack the enemy at enemyIndex
enemy = enemies[enemyIndex]
hero.attack(enemy)
# Increase enemyIndex by one.
enemyIndex += 1
coins = hero.findItems()
# coinIndex is used to iterate the coins array.
coinIndex = 0
while coinIndex < len(coins):
# Get a coin from the coins array using coinIndex
coin = coins[coinIndex]
# Collect that coin.
hero.moveXY(coin.pos.x, coin.pos.y)
# Increase coinIndex by one.
coinIndex += 1
Just to clarify: this isn’t actually a bug. Let me explain.
The while true loop loops through all of the enemies one by one, and attacks them, without checking if they are alive. The enemies array is defined once before the while loop starts. It doesn’t change while the loop runs. That means that if an enemy dies during the loop (due to the thornprick, not your attack), your enemy will keep on going regardless, and will try to attack the dead enemies, because they are still on the enemies list right? It hasn’t updated since the very start of the loop. How could you fix this? How could you refresh the enemies array every loop so that the while loop stops running when the enemies die?
An if statement would certainly solve the problem. You could check if the enemy was alive, and if it was: attack it, and if not: increment the array as usual.
However, a simpler solution exists. As I said before, you could “refresh” the enemies array, so to speak. That would involve redefiningenemies at the end of each while loop. That means that when the while loop returns to its condition which must be true to run, it will be comparing enemyIndex with a new number, because you updated the array when the enemy died.
Both solutions would work well.