学习python的海龟库时,了解到了科赫雪花,然后就进行了扩展绘制
环境:PyCharm
库:turtle random
思考绘制方法:
1、
首先是为了方便后面的颜色控制,将一片雪花分成了六份
那么容易看出这是个三阶的科赫曲线,实现方式是:
def koch(size, n):
if n == 0:
t.pencolor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
t.fd(size)
else:
for i in [0, 60, -120, 60]:
t.left(i)
koch(size / 3, n - 1)
这个是在python教程中学到的实现方式,其中n就是阶数,当到达递归出口时,就是直接画一条直线(这条直线不是size长,三阶的话,可估算为size/4/4/4,应该没错),然后再返回,就可以想象其中的绘画过程:一条直线,左转60,一条直线,左转-120(相当于右转120),一条直线,左转60,一条直线,到这时候绘制成了这样
它又相当于这个的“一条直线”
就这样绘制出来,三阶,其中的递归过程还是比较好想想的。
2、
六分之一都绘制出来了,那么剩下的基本差不多了,直接上代码了
import turtle as t #用于图像
import random #产生随机数
# 递归函数,具体过程,上面有介绍
def koch(size, n):
if n == 0:
t.pencolor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
t.fd(size)
else:
for i in [0, 60, -120, 60]:
t.left(i)
koch(size / 3, n - 1)
#稍微封装了下,颜色有点Hua
def per(n):
t.color((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# t.begin_fill()
koch(400, n)
# t.end_fill()
t.color((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
t.begin_fill()
t.left(120)
t.fd(lenth)
t.left(120)
t.fd(lenth)
t.left(120)
koch(400, n)
t.end_fill()
t.left(60)
lenth = 0
def main():
n = eval(input())
t.colormode(255) #颜色模式设置为255,其它模式有1,string,python文档有详细说明
t.speed(0) #速度快
t.setup(1600, 700) #设置开始时窗体,但没什么必要,直接最大化就好
t.pu()
t.goto(-300, -350)
t.pd()
t.pensize(5)
koch(400, n)
t.left(60)
global lenth
lenth = t.position()[0] - (-300)
# 下面六个部分就为剩下部分绘制
per(n)
per(n)
per(n)
per(n)
per(n)
per(n)
t.hideturtle()
main()
t.done()
效果:
当然,将代码里面的
# t.begin_fill()
koch(400, n)
# t.end_fill()
改为
t.begin_fill()
koch(400, n)
t.end_fill()
你会看到
那么就是这样了,下次再见(_)