Peasant protection python


#1

Hello :smile:

I’ve got a problem with my code in this level (peasant protection, language: python)

loop:
        enemy = self.findNearestEnemy()
        distance = self.distanceTo(enemy.pos)
         if distance < 10:
            self.attack(enemy) 

 else:
        item = self.findNearestItem()
        if item:
            distance = self.distanceTo(item.pos)
            distance(39, 40)          

What is wrong ? (self.moveXY(40, 37) doesn’t work…
Can you help me please ?
Thanks :smile:


#2

Hi, fixed you indentations.

Indentations save lifes

and in this case, your indentations are completly messed up.

loop:
    enemy = self.findNearestEnemy()
    distance = self.distanceTo(enemy.pos)
    if distance < 10:
        self.attack(enemy) 
    else:
        item = self.findNearestItem()
        if item:
            distance = self.distanceTo(item.pos)
            distance(39, 40)

So far so good. To get the position to an item, you can simply use self.distanceTo(item). To get the distance to a position, there is (as far as I know) no function. So you have to calculate it manually.

posX = self.pos.x
posY = self.pos.y

pointX = 39
pointY = 40

# c = Math.sqrt( [x2-x1]^2 + [y2-y1]^2 ) 
distanceToPoint = Math.sqrt( (pointX - posX)*(pointX - posX) + (pointY - posY)*(pointY - posY) )

Edit: Sadly the code-block is not wide enough to show the distanceToPoint in one line. Please remeber this.


#3

Actually, you can use distanceTo on a position like this:

d = self.distanceTo({"x": 39, "y": 40})  # Python
var d = this.distanceTo({x: 39, y: 40})  # JavaScript

#4

I am trying your code J_F_B_M, but when I type it in, my peasant always dies before i attack all. What do I do? :pensive:


#5

My code is just a correctly intended version of the original posters code. It does not work the way it is provided.


#6

your code didn’t work


#7

Of course it didn’t. Read one post above yours: