Library Tactician - Explaining bestTarget/mostHealth enemy (Python)


#1

Hello,

I recently passed the level Library Tactician, but I’m still confused about the bestTarget / mostHealth part.
Can someone explain me what happens when the following code is run:

    mostHealth = 0
    bestTarget = None
    enemies = hero.findEnemies()
    # Figure out which enemy has the most health, and set bestTarget to be that enemy.
    for enemy in enemies:
        if enemy.health > mostHealth:
            mostHealth = enemy.health
            bestTarget = enemy

Thanks in advance!


#2

As the function iterates through the array of enemies, mostHealth starts at zero (to start counting from) and bestTarget starts at none because it is unknown and then the variable “enemies” is defined.

For each enemy in the array of enemies: if an enemy’s health is greater than the known mostHealth (which it will be because each living enemy will have a higher health than zero): then the enemy with the highest health is assigned to mostHealth and the bestTarget becomes that enemy. As it iterates through the array of enemies, this enemy with the mostHealth can change if the current iteration comes across another enemy with higher health.

That’s as simplistic as I can describe it. I’m sure that someone will chime in if I’m wrong about any of it.


#3

Thank you! (20 characters)