运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12
往期链接:
Python项目实战
P156–L系统分形树
技术栈:随机+规则实现的分形艺术
import turtle
import random
def apply_rules(axiom):
rules = {
'F': 'F[+F]F[-F]F',
'+': '+',
'-': '-',
'[': '[',
']': ']'
}
return ''.join(rules.get(char, char) for char in axiom)
def generate_l_system(axiom, iterations):
current = axiom
for _ in range(iterations):
current = apply_rules(current)
return current
def draw_l_system(t, instructions, angle, length):
stack = []
for command in instructions:
if command == 'F':
t.forward(length)
elif command == '+':
t.right(angle)
elif command == '-':
t.left(angle)
elif command == '[':
stack.append((t.position(), t.heading(), t.pensize()))
t.color(random_color())
t.pensize(t.pensize() + 1)
elif command == ']':
position, heading, pensize = stack.pop()
t.penup()
t.setposition(position)
t.setheading(heading)
t.pensize(pensize)
t.pendown()
def