繁体   English   中英

使用乌龟图形和递归绘制锯齿状的山曲线

[英]drawing a jagged mountain curve using turtle-graphics and recursion

我正在尝试为作业分配创建一个函数,该函数使用乌龟和递归绘制锯齿状的山形曲线。 该函数称为jaggedMountain(x,y,c,t) ,其中x x,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次,并且超过了递归深度。 我已经为此花了很长时间,有什么建议吗?

最初,我发现您的代码有两个问题。 第一个是:

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

乌龟徘徊在浮点平面上,它们完全相等的几率很小。 您最好执行以下操作:

def distance(x1, y1, x2, y2):
    return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5

...

    if distance(x1, y1, x, y) < 1.0:

第二个问题是jaggedCurve()不会绘制任何内容,也不返回任何可用于绘制的内容。 您需要在某个地方实际移动海龟以绘制一些东西。

最后,尽管很难确定没有c的值,但即使上述更改,我的猜测仍然是您无法获得想要的。 祝好运。

非常有趣的问题!

我的解决方案是制作一个递归函数,该函数在给定两个端点的情况下绘制山峰曲线。 随机选取位于两个端点之间的ax坐标值,并在给定最大可能斜率的情况下计算可能y坐标的范围,并随机选取此范围之间的ay值并递归执行。 当端点足够近时,只需画出它们之间的线即可。 这是代码:

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))

我知道这是3个月前发布的,但希望这对在决赛前5天也遇到这个可怕问题的人有所帮助! 哈!

我在这个问题上遇到的挣扎并没有意识到您只需要通过一点即可。 为了弄清楚乌龟的起点,您只需使用乌龟库中包含的.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 ()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM