1.源码实现
import matplotlib.pyplot as plt
import math
# 使用Matploitlib库, 定义自己的Turtle类
class my_turtle:
# 构造方法, 自动执行
def __init__(self, A):
# 初始化实例
self.x = A[0]
self.y = A[1]
self.d = A[2]
# 获取turtle当前状态
def get_point(self):
return (self.x, self.y, self.d)
# 恢复到状态p点
def restore(self, p):
self.x = p[0]
self.y = p[1]
self.d = p[2]
# 向前一步, 画线
def forward(self, L):
# 计算下一点的坐标
x1 = self.x + L*math.cos(self.d*math.pi/180)
y1 = self.y + L*math.sin(self.d*math.pi/180)
# 两点之间画线
X = [self.x, x1]
Y = [self.y, y1]
# 绘制线段
plt.plot(X, Y, c=p_color, alpha=1)
# 设置当前状态为下一点的状态
self.x = x1
self.y = y1
# 向前一步, 不画线
def go(self, L):
x1 = self.x + L*math.cos(self.d*math.pi/180)
y1 = self.y + L*math.sin(self.d*math.pi/180)
self.x = x1
self.y = y1
# 向左转angle度
def left(self, angle):
self.d = self.d + angle
# 向右转angle度
def right(self, angle):
self.d = self.d - angle
# L系统函数, LS为图形文法结构, A为起始点, L为步长, n为迭代次数
def L_system(LS, A, L, n):
angle = LS['angle']
axiom = LS['axiom']
P = LS['P']
# 字符串重写
i = 0
new_str = axiom
# 重复迭代替换, 直到达到迭代次数
while i < n:
s = []
# 遍历字符串中的每个字符
for alpha in new_str:
k = 0
for rule in P:
origin, desti = rule.split('->')
if alpha == origin:
if desti:
s.append(desti)
k = 1
if k == 0:
s.append(alpha)
new_str = ''.join(s)
print(new_str)
i = i + 1
# 实例化生成一个my_turtle对象
t1 = my_turtle(A)
# 解释字符串, 绘图
stack = []
# 遍历字符串
for alpha in new_str:
if alpha not in plot_V:
continue
if alpha == 'F':
t1.forward(L)
elif alpha == 'f':
t1.go(L)
elif alpha == '+':
t1.left(angle)
elif alpha == '-':
t1.right(angle)
elif alpha == '[':
C = t1.get_point()
stack.append(C)
elif alpha == ']':
A = stack[-1]
del stack[-1]
t1.restore(A)
# 定义符号的图形学解释
plot_V = {'F': 'Move forward by line length drawing a line',
'f': 'Move forward by line length without drawing a line',
'+': 'Turn left by turning angle',
'-': 'Turn right by turning angle',
'[': 'push',
']': 'pop',
}
# 科赫曲线图形结构
koch = {'angle': 60,
'axiom': 'F',
'P': ['F->F+F--F']
}
# 科赫雪花图形结构,
koch_snow = {'angle': 60,
'axiom': 'F--F--F',
'P': ['F->F+F--F+F']
}
# 分形龙图形结构
dragon = {'angle': 45,
'axiom': 'FX',
'P': ['F->', 'Y->+FX--FY+', 'X->-FX++FY-']
}
if __name__ == '__main__':
# 指定背景颜色
b_color = 'white'
# 指定画笔颜色
p_color = 'black'
# 设置窗口的默认颜色
plt.rcParams['figure.facecolor'] = b_color
# 设置起始点
A = (0, 0, 0)
# 设置步长
L = 30
# 设置迭代次数
n = 10
# 调用L-system函数生成字符串并绘制图形
L_system(dragon, A, L, n)
# 设置x, y轴的单位长度相等
plt.axis('equal')
# 隐藏坐标轴
plt.axis('off')
# 保存图形为文件
plt.savefig('1.png', facecolor=b_color)
2.运行程序
$ python3 test.py
3.运行结果