hffy
February 9, 2015, 9:29pm
1
Hello
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
J_F_B_M
February 10, 2015, 8:16pm
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.
nick
February 10, 2015, 11:21pm
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
1 Like
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?
My code is just a correctly intended version of the original posters code. It does not work the way it is provided.
Of course it didn’t. Read one post above yours: