Python 中的分形樹


分形模式無處不在,在大自然中。就像蕨葉的一個小樹枝與蕨葉本身很相似。或是一顆鵝卵石經常像一座山!所以利用小模式的重複來生成大模式的這個想法就叫作分形樹。在 Python 程式設計中,也可以使用各種可用模組來生成分形樹。

使用 pygame 模組

該模組為我們提供了生成分形樹所需的功能。在這裡,我們首先定義屏幕布局大小,然後定義模式重複自身的深度。遞迴在這裡起很大作用,因為我們要重複相同的模式,直到某個深度。

示例

import pygame, math

pygame.init()
screen = pygame.display.set_mode((750, 650))
pygame.display.set_caption("Fractal Tree")
display = pygame.display.get_surface()

def drawTree(a, b, pos, deepness):
if deepness:
c = a + int(math.cos(math.radians(pos)) * deepness * 10.0)
d = b + int(math.sin(math.radians(pos)) * deepness * 10.0)
pygame.draw.line(display, (127,255,0), (a, b), (c, d), 1)
drawTree(c, d, pos - 25, deepness - 1)
drawTree(c, d, pos + 25, deepness- 1)

def process(event):
if event.type == pygame.QUIT:
exit(0)

drawTree(370, 650, -90, 10)
pygame.display.flip()
while True:
process(pygame.event.wait())

輸出

執行上面的程式碼會得到以下結果

使用 Turtle

使用 turtle 模組,我們可以遵循類似的方法。此處,turtle 程式開始繪製樹枝作為重複的模式,只需更改繪製的方向即可。我們定義功能重複自身時的角度,然後得到完整的樹。

示例

import turtle
def tree(Length,n):
   if Length > 10:
      n.forward(Length)
      n.right(25)
      tree(Length-15,n)
      n.left(50)
      tree(Length-15,n)
      n.right(25)
      n.backward(Length)

def function():
   n = turtle.Turtle()
   data = turtle.Screen()
   n.left(90)
   n.up()
   n.backward(100)
   n.down()
   n.color("green")
   tree(85,n)
   data.exitonclick()

function()

輸出

執行上面的程式碼會得到以下結果

更新於: 2020 年 1 月 2 日

770 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.