使用乌龟图形和递归绘制一个锯齿形山脉曲线

2024-09-19 23:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为作业创建一个函数,它使用海龟和递归绘制锯齿形的山形曲线。这个函数叫做jaggedMountain(x,y,c,t),其中xx,y是结束坐标,c是复杂度常数,t是海龟对象。我试图创造一个这样的形象: mountain curve

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次,并且超过了递归深度。我已经为这个挠头好长时间了,有什么建议吗?在


Tags: 函数作业常数绘制复杂度曲线海龟x1
3条回答

很有趣的问题!在

我的解决方案是创建一个递归函数,在给定两个端点的情况下绘制一条山形曲线。随机选取一个位于两个端点之间的x坐标值,在给定最大可能坡度的情况下计算可能y坐标的范围,并在该范围内随机选取一个y值并递归执行。当终点足够近时,只需在它们之间划一条线。代码如下:

MAX_SLOPE = 45
MIN_SLOPE = -45
MIN_HEIGHT = 0
def dist_squared(P1,P2):
    return (P1[0]-P2[0])**2 + (P1[1]-P2[1])**2

def mountain(P1,P2):
    if dist_squared(P1,P2) < 1:
        turtle.goto(P2)
        return
    x1,y1 = P1
    x2,y2 = P2
    x3 = random.uniform(x1,x2)
    y3_max = min((x3-x1)*math.tan(math.radians(MAX_SLOPE)) + y1, (x2-x3)*math.tan(-math.radians(MIN_SLOPE)) + y2)
    y3_min = max((x3-x1)*math.tan(math.radians(MIN_SLOPE)) + y1, (x2-x3)*math.tan(-math.radians(MAX_SLOPE)) + y2)
    y3_min = max(y3_min, MIN_HEIGHT)
    y3 = random.uniform(y3_min,y3_max)
    P3 = (x3, y3)
    mountain(P1,P3)
    mountain(P3,P2)
    return

turtle.up()
turtle.goto(-400,0)
turtle.down()
mountain((-400,0),(400,0))

最初,我看到您的代码有两个问题。首先是:

if (x1,y1) == (x,y):

海龟在浮点数平面上游荡,它们完全相等的几率很小。你最好做些类似的事情:

^{pr2}$

第二个问题是jaggedCurve()绘制nothing也不会返回任何可用于绘制的内容。你需要把乌龟移到某个地方,让它画出来。在

最后,虽然很难确定没有c的值,但我的猜测是,即使进行了上述更改,也不会得到您想要的结果。祝你好运。在

我知道这是3个月前发布的,但希望这对在期末考试前5天也被分配了这个可怕问题的人有所帮助!哈!在

我与这个问题的斗争是没有意识到你只需要通过一个点。要获得海龟的起点,只需使用turtle库中包含的.xcor()和.ycor()。在

import turtle
import random

def mountain (x, y, complexity, turtleName):
    if complexity == 0:
        turtleName.setposition(x, y)
    else: 
        x1 = (turtleName.xcor() + x)/2
        y1 = (turtleName.ycor() + y)/2
        y1 = y1 + (random.uniform(0, complexity) - 0.5) * (turtleName.xcor() - x)
        complexity = complexity - 1
        mountain(x1, y1, complexity, turtleName)
        mountain(x, y, complexity, turtleName)


def main ():
    #Gets input for first coordinate pair, splits, and assigns to variables
    coordinate = str(input("Enter the coordinate pair, separated by a comma: "))
    x, y = coordinate.split(',')
    x = int(x)
    y = int(y)

    complexity = int(input("Enter the complexity: "))
    while complexity < 0:
        complexity = int(input("Input must be positive. Enter the complexity: "))

    Bob = turtle.Turtle()
    mountain(x, y, complexity, Bob)

main ()

相关问题 更多 >