Bug or bad code?


#1

So I’m stuck on the mission “leave-it-to-cleaver” which its objective is to eliminate all enemies and here’s my code so far:

 def cleaveWhenClose(target):
    if hero.distanceTo(target) < 5:
        # If cleave is ready, then cleave target
        if hero.isReady("cleave"):
            hero.cleave(target)    
        # else, just attack target!
       else:
           hero.attack(target)

loop:
    enemy = hero.findNearestEnemy()
    if enemy:
        cleaveWhenClose(enemy)

When I run this code everything runs smoothly for 2 entire “cleaveWhenClose” functions, but on the last 2 enemies is when my hero stops attacking and cleaving for no reason so I end up failing the mission since I must eliminate all enemies. Any ideas on what’s wrong with my code or is there a bug?

*edit
I added an else to the loop in order to move away from the enemy spawn point since I thought that was the problem and now it works, yay!

loop:
    enemy = hero.findNearestEnemy()
    if enemy:
        # Note that inside cleaveWhenClose, we 
        cleaveWhenClose(enemy)
    else:
        hero.moveXY(42, 43)

So it turns out there is a bug which is if your hero moves all the way to one side until it’s clipping the edge, it cannot detect an enemy that spawns on top of it. or I think that’s what’s happening.


#2

Bad Code, I’m afraid.

Well, not really bad, just one tiny missed thing.

Look at your else statement – is it an else for the first if or the second if? It should be for the second if, but because it is not tabbed to line up with the second if, it is triggering on the first.

This means you code says:

If enemy is close (< 5), then see if cleave is ready and cleave.
If enemy is not close (> 5), go attack the enemy.

So, if you move to the spawn point of the enemy, and they appear within 5 meters of you, you don’t attack because the attack only happens if the enemy is more than 5 meters away.

Add one more space in front of that else and it should work.