簡介分形樹被稱為可以通過遞歸對稱分支創建的樹。
長度為 1 的樹幹分裂成長度為 r 的兩個分支,每個分支它與桶的方向形成一個角度 q。這兩個分支都分為長度為 r * r 的兩個分支,每個分支與其父分支的方向成 q 角。以這種方式繼續無限數量的分支,一棵樹是分支及其限制點的集合,稱為分支提示。
理論說得夠多了,現在讓我們嘗試在 Python 中實現。為此,我們需要兩個 Python 庫 Pygame 用於 GUI 或 GUI 和 math, 這是 Python 中的一個內置庫,將用於數學調整。
要安裝 Pygame
pip install pygame
那麼如何繼續,強烈建議你了解一點侏儒和分形。
首先創建樹幹,然後開始為每個樹幹創建分支,假設分支大小為0.9 *(莖長),然後再次將分支視為莖,重複該過程。
# 導入python庫
import
pygame, math
# 初始化 cue 所有導入的 Pygame 模塊
pygame. init ()
# 創建一個新的表面和窗口。
surface_height,surface_width
=
800
code> ,
600
# 表面變量
main_surface
=
pygame.display.set_mode ((surface_height, surface_width))
# 窗口標題
pygame.display.set_caption (
"Fractal_Tree_pythonengineering"
)
def
draw_tree (order, theta, sz, pos n, heading, color
=
(
0
,
0
0
), depth
=
0
):
相對樹幹與整棵樹的比例
trunk_ratio
=
0.29
#桶長
trunk
=
sz
*
trunk_ratio
delta_x
=
trunk
*
math.cos(標題)
delta_y
=
trunk
*
math.sin (heading)
(u, v)
=
posn
newpos
=
(u
+
delta_x, v
+
delta_y)
pygame.draw.line (main_surface, color , posn, newpos)
if
order >
0
:
#再畫一層子樹
# 接下來六行 - 簡單的 hack
# 遞歸的兩個主要部分是不同的
# 顏色。在這裡撥弄以將顏色更改為另一個
# 深度,或者當深度為偶數或奇數時等。
if
depth
=
=
0
:
<代碼類="plain "> color1 =
(
255
,
0
,
0
)
color2
=
(
0
,
0
,
255
)
else
:
color1
=
color
color2
=
color
# 遞歸調用繪製兩個子樹
newsz
=
sz
*
(
1
-
trunk_ratio)
draw_tree (order
-
1
, theta, newsz, newpos, heading
-
theta, color1, depth
+
1
)
draw_tree (order
-
1
, theta, newsz, newpos, heading
+
theta, color2, depth
+
1
)
def
main():
theta
=
0
while
True
:
# 更新角
theta
+
=
0.01
# 這個小部分讓我們畫東西
#屏幕上的所有內容
main_surface.fill ((
255
,
255
,
0
))
draw_tree (
9
, theta, surface_height
*
0.9
, (surface_width
/
/
2
, surface_width
-
50
),
-
math.pi
/
2
)
pygame.display.flip ()
#調用main函數
main()
pygame.quit()
退出:
% MINIF YHTMLc707a572199fb7b4b8a82374bf37b87213%