【问题标题】:How to stop turtles at certain coordinates?如何在特定坐标停止海龟?
【发布时间】:2014-06-14 13:05:01
【问题描述】:

我对编程非常陌生(使用 Python 3)。我想知道当乌龟到达某个点时,使用按键时如何阻止它移动。我设法做到了,但它只能工作一次或几次,因为当我移动它一点时,乌龟的 x 坐标会发生变化,例如,乌龟将降落在 -40.0001 或 -39.9996 上,而不是 40.00。

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()

现在我只想在向上移动时将海龟停在 (-40.00, 80.00) 处。如果能得到任何帮助,我将不胜感激,谢谢。

【问题讨论】:

  • 我会计算 40,80 和当前位置之间的距离,如果它小于某个小量,而不是希望它正好是 0,则停止。
  • 谢谢...我成功了:)

标签: python coordinates turtle-graphics


【解决方案1】:

不要直接检查pos,而是检查a.distance(40.0, 80.0) < 1.0或一些小的阈值。

替代方案:在移动海龟之后或在检查它的位置之前,您可以round 返回的坐标,以便它们捕捉到精确的数字。

>>> round(40.01)
40.0

【讨论】:

  • 谢谢,这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
相关资源
最近更新 更多