Question about variables, stage Seek-And-Hide

Hi everyone

Im very new to programming and im still trying to figure the Python syntax out. I recently did a “Seek-And-Hide” stage, and the stage went fine until about 30% of the stage. Then my hero would stop doing what he was supposed to do.

The problem was fixed by making a second variable which has already been written further up in my while-true loop.

Why does the same variable has to be written twice in the same loop, isn’t one time enough ?

Here is a screenshot of the code and stage:

Thank you for your help

1 Like

One time isn’t enough, as, the variable is populated with the result of the function as when it was called during runtime.

# Assume there are 2 enemies
firstEnemy = hero.findNearestEnemy()
hero.attack(firstEnemy)
hero.attack(firstEnemy)
# Enemy is dead!
hero.attack(firstEnemy) # Attacking a dead enemy, error!
# firstEnemy doesn't 'update' with the second enemy.

Instead you’d want to do:

# Assume there are 2 enemies
firstEnemy = hero.findNearestEnemy()
hero.attack(firstEnemy)
hero.attack(firstEnemy)
# Enemy is dead!
firstEnemy = hero.findNearestEnemy() # Same variable name, as variable names don't matter:
hero.attack(firstEnemy)
hero.attack(firstEnemy)
# Second enemy is dead!
3 Likes

Thanks for the reply :slight_smile:

1 Like