在 1966 年,Seymour Papert 和 Wally Feurzig 發明了一種專門給兒童學習編程的語言——LOGO語言,它的特色就是通過編程指揮一個小海龜(turtle)在屏幕上繪圖。
海龜繪圖(Turtle Graphics)後來被移植到各種高級語言中,Python內置了turtle庫,基本上100%複製了原始的Turtle Graphics的所有功能。
實例1
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' 海龜繪圖 '
__author__ = 'Kevin Gong'
from turtle import *
from random import *
from math import *
def drawTree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 4)
forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * 15 + 10
d = l * (random() * 0.35 + 0.6)
right(b)
drawTree(n - 1, d)
left(b + c)
drawTree(n - 1, d)
right(c)
else:
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n, n, n)
circle(2)
left(90)
pu()
backward(l)
bgcolor(0.5, 0.5, 0.5)
ht()
speed(0)
tracer(0, 0)
left(90)
pu()
backward(300)
drawTree(13, 100)
done()
效果圖
實例2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' 海龜繪圖 '
__author__ = 'Kevin Gong'
from turtle import *
from random import *
from math import *
def drawTree(n, l):
pd()
# 陰影效果
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 3)
# 畫樹枝
forward(l)
if n > 0:
# 右分支偏轉角度
b = random() * 15 + 10
# 左分支偏轉角度
c = random() * 15 + 10
# 下一個分支的長度
d = l * (random() * 0.35 + 0.6)
# 右轉一定角度,畫右分支
right(b)
drawTree(n - 1, d)
# 左轉一定角度,畫左分支
left(b + c)
drawTree(n - 1, d)
# 轉回來
right(c)
else:
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n, n * 0.8, n * 0.8)
circle(3)
left(90)
# 添加0.3倍的飄落葉子
if(random() > 0.7):
pu()
# 飄落
t = heading()
an = -40 + random()*40
setheading(an)
dis = int(800*random()*0.5 + 400*random()*0.3 + 200*random()*0.2)
forward(dis)
setheading(t)
# 畫葉子
pd()
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n*0.5+0.5, 0.4+n*0.4, 0.4+n*0.4)
circle(2)
left(90)
pu()
#返回
t = heading()
setheading(an)
backward(dis)
setheading(t)
pu()
backward(l)
bgcolor(0.5, 0.5, 0.5)
ht()
speed(0)
tracer(0, 0)
pu()
backward(100)
left(90)
pu()
backward(300)
drawTree(12, 100)
done()