簡體   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