我正在编写一个程序,需要一只乌龟移动到另一只乌龟。但是很简单:
turtle.goto(other_turtle.pos())
其中turtle和other_turtle是两个已定义的海龟
这不起作用,因为它说other_turtle.pos()
是一个方法,并且没有定义方法和浮点数之间的减法。然后我继续尝试将other_turtle.pos()
更改为float(other_turtle.pos())
。那就是错误地说你不能浮动一个方法。
我的问题:这可能是这样做还是由于蟒蛇本身的局限性不可能?
代码:
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'
答案 0 :(得分:0)
表达式:
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)
这会导致您报告的错误,因为您正在传递方法xcor
和ycor
而不是调用它们。应该是:
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())
本来可以。