使用turtle画一朵小花花
这是一朵特殊的小花花–没有闭合曲线(创造它的人是一位天才),画的时候有两个难点:
作为一名手残党,我使用python turtle, 简单的代码画一个上面看上去略简陋的小花花
1,花朵
花朵是一个阿基米德螺线,一个棒子以一端为中心按照恒定的角速度转动,一个虫子以恒定的速度从中心点向另一端爬行,小虫子的轨迹就是一个阿基米德螺线,代码如下:
"""Draws an Archimedian spiral starting at the origin.
Args:
n: how many line segments to draw
length: how long each segment is
a: how loose the initial spiral starts out (larger is looser)
b: how loosly coiled the spiral is (larger is looser)
http://en.wikipedia.org/wiki/Spiral
"""
def draw_spiral(t, n, length=2, a=0.01, b=0.0002):
theta = 0.0
t.color('pink')
t.pensize(1.5)
for i in range(n):
t.fd(length)
dtheta = 1 / (a + b * theta)
t.lt(dtheta)
theta += dthet
2,叶子
叶子是对数螺线,可以在上述代码中稍作改动:
def draw_log_spiral(t, n, length=2, a=0.01, b=0.002):
theta = 0.0
t.color('green')
t.pensize(1.5)
for i in range(n):
t.fd(length)
dtheta = 3 / (a * math.exp( b * theta))
t.lt(dtheta)
theta += dtheta
3,python turtle的使用
关于海龟绘图的介绍:点我
Think Python中使用turtle绘图:这里
turtle颜色方案:看这
4,整体代码
import turtle
import math
from turtle import *
def draw_spiral(t, n, length=2, a=0.01, b=0.0002):
"""Draws an Archimedian spiral starting at the origin.
Args:
n: how many line segments to draw
length: how long each segment is
a: how loose the initial spiral starts out (larger is looser)
b: how loosly coiled the spiral is (larger is looser)
http://en.wikipedia.org/wiki/Spiral
"""
theta = 0.0
t.color('pink')
t.pensize(1.5)
for i in range(n):
t.fd(length)
dtheta = 1 / (a + b * theta)
t.lt(dtheta)
theta += dtheta
#花朵画四圈就提前退出
if (abs(theta - 4 * 360) <= 3.0):
break;
#画出主干
def draw_line(t, len):
t.seth(360)
t.rt(90)
t.pensize(3)
t.color('sienna')
t.fd(len)
def draw_log_spiral(t, n, left = True, length=2, a=0.01, b=0.002):
theta = 2000 #从外向内画曲线
t.color('green')
t.seth(180)
t.pensize(1.5)
#左右的叶子先画一段直线--茎
if (left):
t.rt(140)
t.fd(40)
else:
t.rt(40)
t.fd(40)
t.lt(40)
for i in range(n):
t.fd(length)
dtheta = 3 / (a * math.exp( b * theta))
if (left):
t.lt(dtheta)
else:
t.rt(dtheta)
theta -= dtheta
if (theta < 1000):
break;
t = turtle.Turtle()
turtle.screensize(1000,1000,bg='beige')
t.ht()
t.speed(0)
draw_spiral(t, n=1000)
draw_line(t,100)
pos1 = t.pos()
draw_log_spiral(t, n = 1000, left=False)
t.up()
t.setpos(pos1)
t.pd()
draw_line(t,10)
draw_log_spiral(t, n = 1000)
turtle.mainloop()