from swampy.TurtleWorld import *
world = TurtleWorld
bob = Turtle()
def polyline(t, n, length, angle):
"""Draws n line segments.
t: Turtle object
n: number of line segments
length: length of each segment
angle: degrees between segments
"""
for i in range(n):
fd(t, length)
lt(t, angle)
def polygon(t, n, length):
"""Draws a polygon with n sides.
t: Turtle
n: number of sides
length: length of each side.
"""
angle = 360.0/n
polyline(t, n, length, angle)
polygon(bob, n=7, length=70)
答案 0 :(得分:0)
您发布的代码不会产生您所描述的错误。如果我逐字地运行你的代码,我会得到:
Traceback (most recent call last):
File "foo.py", line 26, in <module>
polygon(bob, n=7, length=70)
File "foo.py", line 24, in polygon
polyline(t, n, length, angle)
File "foo.py", line 14, in polyline
fd(t, length)
File "/home/lars/tmp/runtime/lib/python2.7/site-packages/swampy/TurtleWorld.py", line 185, in fd
if self.pen and self.world.exists:
AttributeError: 'NoneType' object has no attribute 'exists'
看起来这是由于代码中的错误造成的。你有:
world = TurtleWorld
但是swampy.world.TurtleWorld.TurtleWord
是一个类,需要实例化:
world = TurtleWorld()
通过此更改,代码可以正确运行并生成:
答案 1 :(得分:0)
您已正确初始化world
并且没有正确调用类函数。为了使其工作,您需要为您的乌龟分配世界,而不仅仅是随机的某个地方,并将fd
和lt
函数称为t.fd(length)
和t.lt(angle)
。如果您不明白为什么需要这样做,您可以尝试阅读类似this
from swampy.TurtleWorld import *
bob = Turtle()
bob.world = TurtleWorld()
def polyline(t, n, length, angle):
"""Draws n line segments.
t: Turtle object
n: number of line segments
length: length of each segment
angle: degrees between segments
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def polygon(t, n, length):
"""Draws a polygon with n sides.
t: Turtle
n: number of sides
length: length of each side.
"""
angle = 360.0/n
polyline(t, n, length, angle)
polygon(bob, 7, 70)
编辑:larsks的解决方案也有效,我将复制粘贴到我的文件时更改了初始化bob
和world
的顺序,所以它对我不起作用,但他是对的。我猜我需要将TurtleWorld
分配到turle,因为我直接使用the source code for TurtleWord,其中Turtle()的初始化就像
def __init__(self, world=None):
Animal.__init__(self, world)
所以我决定使用TurtleWorld()
作为乌龟的属性,然后直接使用成员函数(fd
和lt
)更好。
答案 2 :(得分:0)
对于n问题,我做了一个raw_input,这对我有用。你可以尝试这样做。