Need help on Back to Back

i cant figure out what to do after the default code. (my code language is python)

Stay in the middle and defend!

loop:
enemy = self.findNearestEnemy()
if enemy:
# Either attack the enemy…
self.buildXY(“fence”, 16, 35)

else:
    # ... or move back to your defensive position.
1 Like

Explain whats going wrong.

In that level you should move standing guard in the middle of the village, until you see an enemy (which approach from left or right), at which time you will go and attack the enemy, and then return to the middle.

In your code you are trying to build a fence.

1 Like

if you use LUA.
you need an end in the loop.
and you need

else
moveXY(xx,xx)

move to your position

1 Like

im using python and i dont know what to do

1 Like

In python the code would be:

loop:
    enemy = self.findNearestEnemy()
    if enemy:
        # Either attack the enemy...
        self.attack(enemy)
    else:
        # ... or move back to your defensive position.
        self.moveXY(xx, yy)

Replace xx and yy with your x and y values that you want to return to.

1 Like

I used
– Stay in the middle and defend!

loop
enemy = self:findNearestEnemy()
if enemy then
– Either attack the enemy…
hero:attack(enemy)

else
    -- ... or move back to your defensive position.
    hero:moveXY(40, 35)
    
end

end

but it didnt work in Python!
Why?

1 Like

It looks like your code is written in the Lua programming language (or something else other than Python).

Make a backup of your code and save it in a text editor, then press the “Reload” button in the top-right of the game interface—this will reset your code to the starting code for your current programming language. Then you can adapt your solution to Python.

1 Like

I have the solution for Lua porgramming.
Spoiler:

loop
local enemy = self:findNearestEnemy()
enemy = self:findNearestEnemy()
if enemy then
enemy = self:findNearestEnemy()
self:attack(enemy)
self:attack(enemy)

else
    self:moveXY(40, 35)
    
end

end

1 Like

In case anyone is new trying this… The main issue is that the level loads with the first enemy variable not being local in the lua game at least. So it was making everything break. Once I made the enemy local it worked as it should have.

2 Likes

Good catch. I submitted a patch request for that level to fix the default code.

2 Likes

Thank you! I’m new to coding just been messing around with it the past week or so… so this one threw me through a loop (pun intended) for a long time …

2 Likes

then what is the code for python then?

As said to you in the another topic: We don’t give out solutions! It’s our number 1 rule.
Post code that you have written, tell us your problem and we’ll help you.
Post it formatted: [Essentials] How To Post/Format Your Code Correctly.
If you don’t do that then no-one will help you and we’ll just shut the topic.
Danny

1 Like