将一只乌龟移到另一只乌龟

Moving one turtle to another

我正在编写一个需要一只乌龟移动到另一只乌龟的程序。然而简单:

turtle.goto(other_turtle.pos())

其中 turtle 和 other_turtle 是两个已经定义的海龟

这不起作用,因为它说 other_turtle.pos() 是一种方法,并且未定义方法和浮点数之间的减法。所以我继续尝试将 other_turtle.pos() 更改为 float(other_turtle.pos())。然后错误地说你不能浮动一个方法。

我的问题:是否可以这样做,或者由于 python 海龟本身的限制不可能?

代码:

def turtle_clone(clone_nmb):
    return [turtle.Turtle() for i in range(clone_nmb)]

def straight_curve(turtle,number_of_arms,number_of_points,colors):
    turtles = turtle_clone(2)
    turtles[0].hideturtle()
    turtles[1].hideturtle()
    turtles[0].color(colors[0])
    turtles[1].color(colors[0])
    pos = 0
    for i in range(number_of_arms):
        turtles[0].setheading(pos)
        turtles[0].forward(5)
        turtles[1].setheading(pos+(360/number_of_arms))
        turtles[1].forward(5*number_of_points)
        turtles[1].right(180)
        for i in range(number_of_points):
            turtles[0]
            turtle.penup()
            turtle.goto(turtles[0].xcor,turtles[0].ycor)
            turtle.pendown()
            turtle.goto(turtles[1].xcor,turtles[1].ycor)
            turtles[0].forward(5)
            turtles[1].forward(5)
        pos += 360/number_of_arms
        turtles[0].goto(0,0)

错误信息:

Traceback (most recent call last):
  File "C:\Users\gularson\Documents\Garrett\Messing Around\turtle_functions.py", line 97, in <module>
    straight_curve(turt,5,30,["white"])
  File "C:\Users\gularson\Documents\Garrett\Messing Around\turtle_functions.py", line 87, in straight_curve
    turtle.goto(turtles[0].xcor,turtles[0].ycor)
  File "C:\Users\gularson\Documents\Garrett\Python\lib\turtle.py", line 1776, in goto
    self._goto(Vec2D(x, y))
  File "C:\Users\gularson\Documents\Garrett\Python\lib\turtle.py", line 3165, in _goto
    diff = (end-start)
  File "C:\Users\gularson\Documents\Garrett\Python\lib\turtle.py", line 262, in __sub__
    return Vec2D(self[0]-other[0], self[1]-other[1])
TypeError: unsupported operand type(s) for -: 'method' and 'float'

表达式:

turtle.goto(other_turtle.pos())

有效。以下运行没有错误:

import turtle

other_turtle = turtle.Turtle()

turtle.goto(other_turtle.pos())

turtle.done()

当然,这不是很有趣(将 (0, 0) 处的一只乌龟移动到另一只已经位于 (0, 0) 处的乌龟之上,但它是合法的。)所以一定有其他东西让你绊倒向上。

你在代码中实际写的是:

turtle.goto(other_turtle.xcor, other_turtle.ycor)

turtle.goto(turtles[0].xcor,turtles[0].ycor)

这将导致您在传递方法 xcorycor 而不是调用它们时报告的错误。应该是:

turtle.goto(other_turtle.xcor(), other_turtle.ycor())

turtle.goto(turtles[0].xcor(), turtles[0].ycor())

或者你问的原码:

turtle.goto(other_turtle.pos())

turtle.goto(turtles[0].pos())

会很好。