我正在尝试为作业创建一个函数,它使用海龟和递归绘制锯齿形的山形曲线。这个函数叫做jaggedMountain(x,y,c,t)
,其中xx,y
是结束坐标,c
是复杂度常数,t
是海龟对象。我试图创造一个这样的形象:
def jaggedCurve(x,y,c,t):
t.pendown()
x1 = t.xcor() + x / 2
y1 = t.ycor() + y / 2
y1 = y + (random.uniform(0,c)-0.5) * (t.xcor() - x)
if (x1,y1) == (x,y):
return None
else:
jaggedCurve(x1,y1,c,t)
这会很快崩溃,因为基本情况从不执行,函数被调用993次,并且超过了递归深度。我已经为这个挠头好长时间了,有什么建议吗?在
很有趣的问题!在
我的解决方案是创建一个递归函数,在给定两个端点的情况下绘制一条山形曲线。随机选取一个位于两个端点之间的x坐标值,在给定最大可能坡度的情况下计算可能y坐标的范围,并在该范围内随机选取一个y值并递归执行。当终点足够近时,只需在它们之间划一条线。代码如下:
最初,我看到您的代码有两个问题。首先是:
海龟在浮点数平面上游荡,它们完全相等的几率很小。你最好做些类似的事情:
^{pr2}$第二个问题是
jaggedCurve()
绘制nothing也不会返回任何可用于绘制的内容。你需要把乌龟移到某个地方,让它画出来。在最后,虽然很难确定没有
c
的值,但我的猜测是,即使进行了上述更改,也不会得到您想要的结果。祝你好运。在我知道这是3个月前发布的,但希望这对在期末考试前5天也被分配了这个可怕问题的人有所帮助!哈!在
我与这个问题的斗争是没有意识到你只需要通过一个点。要获得海龟的起点,只需使用turtle库中包含的.xcor()和.ycor()。在
相关问题 更多 >
编程相关推荐