Question

I am very new to programming (using Python 3). I want to know how one would stop a turtle from moving when it reaches a certain point, when using keypresses. I have managed to do it but it only works once or couple of times because the x coordinate of the turtle changes when I've moved it around for a bit, e.g instead of 40.00 the turtle will then land on -40.0001 or -39.9996.

import turtle
wn = turtle.Screen()
a = turtle.Turtle()

def up():
    a.setheading(90)
    if a.pos() != (40.00, 80.00):
        a.forward(20)
    else:
        False

def left():
    a.setheading(180)
    a.forward(20)

def right():
    a.setheading(0)
    a.forward(20)

def down():
    a.setheading(270)
    a.forward(20)

wn.onkey(up, "Up")
wn.onkey(left, "Left")
wn.onkey(right, "Right")
wn.onkey(down, "Down")


wn.listen()
wn.mainloop()

For now I just want stop the turtle at (-40.00, 80.00) while moving up. I will appreciate any help I can get, thanks.

Était-ce utile?

La solution

Don't check the pos directly, instead check if a.distance(40.0, 80.0) < 1.0 or some small threshold.

Alternative: after you move the turtle or before you check its position, you can round the returned coordinates so that they snap to exact numbers.

>>> round(40.01)
40.0
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top