为什么乌龟不回到原来的位置?

  • 本文关键字:回到原来 位置 python
  • 更新时间 :
  • 英文 :


我尝试代替opos = turtle.pos(), opos = turtle.heading()并更改while条件以对应,但它不起作用。

oPos = turtle.pos()
turtle.color(random_color())
turtle.circle(100)
turtle.setheading(turtle.heading() + 10)
while turtle.pos() != oPos:
turtle.color(random_color())
turtle.circle(100)
turtle.setheading(turtle.heading() + 10)

如果您尝试打印turtle.pos()的值,您将看到(-0.00, -0.00),那么这里发生了什么?

计算机使用浮点数来表示数字,如果进行大量的顺序运算,就会产生一些错误,这就是为什么使用相等来比较浮点数从来都不是一个好主意。

因此,考虑到这一点,我建议您创建一个函数来计算两点之间的距离:
def distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** (1 / 2)

然后,更改条件以测试距离是否太小,而不是完全为零,如:

while distance(turtle.pos(), oPos) > 1e-10:

这已经可以工作了,当海龟到达初始位置时就会停止。

每转一圈,乌龟就会回到原来的位置。所以你的while循环永远不会进入;初始位置和瞬时位置总是相同的。请看这个例子。在其中,只有初始圆,因为while out条件立即满足。

如果你想用标题10来做很多圆,那么你可能会寻找这样的东西。

import turtle
t = turtle.Turtle()
t.speed(0)
orig_heading = t.heading() - 10
while t.heading() != orig_heading:
t.circle(100)
t.setheading(t.heading() + 10)

在这里循环,直到标题返回到原来的位置。

最新更新