我们先来了解自然界中的树

?我们要让树更加自然,所有我们的随机数就派上了用场!
二话不说,写代码:
import turtle as t
import random as rd
def f(x):
if x < 5:
return
t.pensize(x*0.15)
t.color('tan4')
a = rd.randrange(15,45)#左边角度
b = rd.randrange(10,50)
t.fd(x)
t.lt(a)
f(x/(1.1+rd.random()*0.6))
t.rt(a+b)
f(x/(1.2+rd.random()*0.6))
t.lt(b)
t.fd(-x)
t.tracer(5)
t.speed(0)
t.lt(90)
t.pu()
t.fd(-300)
t.pd()
f(200)
t.done()
运行效果:

?甚至,我们还能加上树叶。随机的树叶
代码:
import turtle as t
import random as rd
叶子 = ['green','spring green','lawngreen','yellow green','green4','SpringGreen1','SpringGreen2']
def f(x):
if x < 5:
color = rd.choice(叶子)
t.color(color)
t.begin_fill()
for i in range(2):
t.fd(10)
t.lt(40)
t.fd(10)
t.lt(140)
t.end_fill()
t.color('tan4')
return
t.pensize(x*0.15)
t.color('tan4')
a = rd.randrange(15,45)#左边角度
b = rd.randrange(10,50)
t.fd(x)
t.lt(a)
f(x/(1.1+rd.random()*0.6))
t.rt(a+b)
f(x/(1.2+rd.random()*0.6))
t.lt(b)
t.fd(-x)
t.tracer(5)
t.speed(0)
t.lt(90)
t.pu()
t.fd(-300)
t.pd()
f(200)
t.done()
运行效果:

?还有很多的花样树叶:
代码:
import turtle as t
import random as rd
叶子 = ['orange','tomato','red','hot pink','violet red']
def f(x):
if x < 5:
color = rd.choice(叶子)
t.color(color)
t.begin_fill()
t.lt(90)
t.circle(5)
t.rt(90)
t.end_fill()
t.color('tan4')
return
t.pensize(x*0.15)
t.color('tan4')
a = rd.randrange(15,45)#左边角度
b = rd.randrange(10,50)
t.fd(x)
t.lt(a)
f(x/(1.1+rd.random()*0.6))
t.rt(a+b)
f(x/(1.2+rd.random()*0.6))
t.lt(b)
t.fd(-x)
t.tracer(5)
t.speed(0)
t.lt(90)
t.pu()
t.fd(-300)
t.pd()
f(200)
t.done()
运行效果:

?小编还能做到三叉树:
import turtle as t
import random as ra
苹果 = ['red']
枝干 = ['red4']
树叶 = ['SpringGreen4']
def tree(n):
if n < 10:
t.begin_fill()
t.color(ra.choice(树叶))
for i in range(2):
t.fd(-8)
t.lt(40)
t.fd(-8)
t.lt(140)
t.end_fill()
t.begin_fill()
t.color(ra.choice(苹果))
t.circle(radius=5)
t.end_fill()
t.color(ra.choice(枝干))
return
else:
t.pensize(n*0.11)
t.color(ra.choice(枝干))
a = ra.randrange(15,50)
b = ra.randrange(15,60)
t.fd(n)
t.lt(a)
tree(n/(1.4+ra.random()*0.4))
t.rt((a+b)/2)
tree(n/(1.4+ra.random()*0.5))
t.rt(a+b)
tree(n/(1.4+ra.random()*0.6))
t.lt(b+(a+b)/2)
t.fd(-n)
t.tracer(10)
t.speed(0)
t.lt(90)
t.pu()
t.fd(-300)
t.pd()
tree(200)
t.update()
t.done()
运行效果:

?小编跟大家分享到这了,再见!
|