Help us help you.
You say you have trouble with the level. To get the best help possible, you should tell us what happens, and what you expect to happen with your code.
In this particular case your missing an if enemy:-check. Always check if there is an enemy before trying to attack it.
Try to solve it yourself before looking in here
You can check for an enemy like this:
loop:
enemy = self.findNearestEnemy() # Can return undefined
if enemy: # Checks if enemy != undefined
self.attack(enemy) # Causes problems when enemy == undefined
else:
self.attack("Chest")