Bookkeeper level help please! New to coding and enemy.health is throwing an error


#1

Hi! I’m new to code combat and new to coding generally so be gentle…

Currently, I am having trouble with the Bookkeeper level.
I am getting the following error on line 10:
“Fix Your Code
Try self.health
Line 10: Cannot read property ‘health’ of null.”

I can think of two possible things right now:
1- I am not defining the enemy variable properly or
2 - I need different equipment (sense stone) to sense enemy health levels and I don’t have it equipped.

Any help/ ideas would be much appreciated! Thanks in advance :slight_smile:

Here is a screenshot:

My code is below:

Fight enemies for 15 seconds.

# Keep count whenever an enemy is defeated.

while True:
    defeated = 0
    enemy = self.findNearestEnemy()
    if self.now >=15:
        break
    else:
        if enemy.health <=0:
            defeated += 1
        else:
            self.attack(enemy)
            self.attack(enemy)
# Tell Naria how many enemies you defeated.
self.moveXY(59, 33)
self.say("I've defeated "+defeated+" enemies")
# Collect coins until the clock reaches 30 seconds.
while True:
    if self.now >=30:
        break
    else:
       coin = self.findNearestItem()
       cPos = coin.pos
       cx = cPos.x
       cy = cPos.y
       self.move(cx,cy)
# Tell Naria how much gold you collected.
self.moveXY(59, 33)
self.say("I've collected "+coin+" coins")
# Fight enemies until the clock reaches 45 seconds.
while True:
    if self.now >=45:
        break
    else:
# Remember to reset the count of defeated enemies!
        defeated = 0
        self.attack(enemy)
        if enemy.health <= 0:
            defeated += 1
# Tell Naria how many enemies you defeated.
self.moveXY(59, 33)
self.say("I've defeated "+defeated+" enemies")

#2

When there’re no enemies, findNearestEnemy returns null, so you can’t read the health property. You can check if there is an enemy with

if enemy:
    #block of code

This is used in many other levels.


#3

[redacted, we do not post correct code]