# Is it possible to attack the nearest archers?

#1

Hello guys, I’m new here, I’ve was playing the clash of clones level and I wanted to try something new; to attack the nearest archers. I’ve been able to attack the nearest enemies and I’ve been able to attack only the archers, but I haven’t been able to specify both. Is this possible? This is my code, which doesn’t work (attacks the archers, but in any order, not the nearest ones):

``````self.moveXY(72, 51)
enemies = self.findEnemies()
index = 0
nearest = self.findNearest(enemies)
while index < len(enemies):

enemy = enemies[index]

if enemy:
if nearest:
if enemy.type == "archer":
index = index + 1
while enemy.health > 0:
if self.isReady("cleave"):
self.cleave(enemy)
if self.isReady("bash"):
self.bash(enemy)
else:
self.attack(enemy)
else:
index = index + 1
self.moveXY(57, 46)``````
#2

You’re attacking `enemy`, not `nearest`.

Do you have glasses that grant `findByType`? If you do, you could use them to find the nearest archer instead of checking whether the nearest enemy is an archer.

#3

Hey Gundericus, thanks but it didn’t work, when I attack the nearest it says Infinite Loop. I manage to pass de level atacking archers in an order, but still wanted to know if it is possible to attack the nearest archers with those functions.

#4

I usually would create a seperate array or list of the archers then attack the nearest of those.
You will learn how to do things like that in the next level, so don’t sweat it so much.

``````archers = [enemy for enemy in enemies if enemy.type == 'archer']
self.attack(findNearest(archers))
``````

Note that if you do that a lot it will make your code run really slow…

#5

You may want to refresh `nearest` every cycle of the loop. Right now it’s outside your loop so `nearest` is only set when you start the level and it never changes in your while loop…

What is the purpose of your “i`f enemy: if nearest:`” statements? They are substantively equivalent to: `if enemy != NULL and nearest != NULL:` I’m guessing now, but I don’t think that is what you intended…

#6

Awesome, I didn’t know there was a difference between putting the nearest in or out, but that makes sense. However I put it after the while loop and results remained the same.

#7

Cool, going now to next world to learn the For function