Mẫu fractal lặp lại ở quy mô nhỏ tạo nên cấu trúc lớn. Python vẽ cây fractal bằng pygame hoặc turtle.
Dùng module pygame
Định nghĩa màn hình, độ sâu đệ quy. Hàm drawTree vẽ nhánh, gọi đệ quy hai nhánh con với góc lệch ±25 độ.
Ví dụ
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()) Đầu ra

Dùng Turtle
Rùa vẽ nhánh, quay phải/trái, lùi lại, đệ quy giảm độ dài.
Ví dụ
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() Đầu ra
