Simplify my Blackwoods ambush code in Python

This code is working but I was wondering if there is a smarter way to do it.
Thank you in advance

working code :

def checkAndAttack(x, y):
hero.moveXY(24,42)   
enemy = hero.findNearestEnemy()   
if enemy:
    hero.attack(enemy)

hero.moveXY(27,61)   
enemy = hero.findNearestEnemy()   
if enemy:
    hero.attack(enemy)

hero.moveXY(42,50)   
enemy = hero.findNearestEnemy()   
if enemy:
    hero.attack(enemy)
    
hero.moveXY(39,24)   
enemy = hero.findNearestEnemy()   
if enemy:
    hero.attack(enemy)

hero.moveXY(55,29)   
enemy = hero.findNearestEnemy()   
if enemy:
    hero.attack(enemy)

checkAndAttack(24, 42)
checkAndAttack(27, 60)
checkAndAttack(42, 51)
checkAndAttack(39, 24)
checkAndAttack(55, 29)

Why this code (below) does not makes the hero attack and just makes him to move ?

def checkAndAttack(x, y):
    hero.moveXY(x, y)
enemy = hero.findNearestEnemy()
if enemy:
    hero.attack(enemy)

checkAndAttack(24, 42)
checkAndAttack(27, 60)
checkAndAttack(42, 51)
checkAndAttack(39, 24)
checkAndAttack(55, 29)

Thank you again
Eliot

i canot help if its in phiton

i need it in java script

Because you call “attack” only once :wink: Be careful with indents in Python. You function should be like this:

def checkAndAttack(x, y):
    hero.moveXY(x, y)
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)

See? Just additional indents and now attack block is inside the function.

1 Like

thank you a lot. You were right, it was the form !