簡體   English   中英

L系統中的分形

[英]Fractals in L-system

def L(pos):
    #left turn
    global theta, d
    x1=pos[0]
    y1=pos[1]
    theta += plt.radians(60)
    return (x1+d*plt.cos(theta),
            y1+d*plt.sin(theta))

def R(pos):
    #right turn
    global theta, d
    x1=pos[0]
    y1=pos[1]
    theta -= plt.radians(120)
    return (x1+d*plt.cos(theta),
            y1+d*plt.sin(theta))

def F(pos):
    #forward
    global theta, d
    x1=pos[0]
    y1=pos[1]
    theta -= plt.radians(300)
    return (x1+d*plt.cos(theta),
            y1+d*plt.sin(theta))

#Create L-pattern
#Start pattern FLRL
#transformation pattern LRL
t1 = [R,R,R]

#transformations = [L,R,L]
#theta =  
#d=1

#F LRL L LRLR LRL L LRL 
t2 = []
iterations = 8
for i in range(iterations):
    d = d/3
    for elem in t1:
        t2.append(elem)
        for tr in transformations:
            t2.append(tr)
    t1=t2
    t2=[]
    
#plotting L-pattern
pos = (0,0)
x=[0]
y=[0]
for tr in t1:
    pos=tr(pos)
    x.append(pos[0])
    y.append(pos[1])

plt.plot(x,y)
plt.axis("scaled")
plt.show()

我想獲得 theta(angle) 作為輸入,變量 d 是每個 function 創建的長度。 我的第一個想法是有一個 def() 來獲取所有 arguments,而不是將其分成三個函數,def L、F 和 R。 這是為了不將變量設置為創建每個分形的角度。

目前還不清楚您要使用代碼完成什么。 作為一個起點,我將如何減少對三個獨立功能的需求:

def transform(pos, angle, d, direction):
    transforms = {"Right": 60, "Left": 120, "Forward": 300}
    if direction in transforms:
        theta = angle + plt.radians(transforms[direction])
        return (pos[0] +d * plt.cos(theta),
            pos[1] + d * plt.sin(theta))        
    else:
        print("Error: Invalid direction request")  

根據方向變量中提供的值“右”、“左”或“前”,它將返回轉換點的結果。

如果您試圖讓用戶輸入 theta 和距離的值,請查看輸入命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM