Draw a Christmas tree with python's turtle library

The code is as follows (with detailed comments)

#from xx import*可直接调用xx模块中的函数,因为已经知道该函数是哪个模块中的了
#import导入模块,每次使用模块中的函数都是要定那个模块
#为避免名称冲突,一般都使用import
from turtle import *
import random
import time

n = 100.0

#设置画笔移动速度,画笔绘制的速度范围[0,10]整数,数字越大越快
speed(10)

#设置画布大小screen(canvwidth,canvheight,bg),
#若不设置值,默认参数为(400,300,None),bg为背景颜色
screensize(bg='seashell')

#设置画笔粗细
pensize(1)

#逆时针旋转90°,类似极坐标
left(90)

#向当前画笔方向移动3*n像素长度,树干出来了
forward(3*n)

#pencolor=orange,fillcolor=yellow,铅笔颜色是橙色,填充色是黄色
color("orange", "yellow")

#开始填充图形
begin_fill()

#画笔方向由当前方向逆时针旋转126°=54°+72°
left(126)

#画五角星
#循环五次
for i in range(5):
    #向当前画笔方向移动n/5像素长度
    forward(n / 5)
    
    #顺时针旋转144°=180°-36°
    right(144)
    
    #向当前画笔方向移动n/5像素长度
    forward(n / 5)
    
    #逆时针旋转72°,到此画出了一个角
    left(72)
    
#填充完成,五角星结束
end_fill()

#顺时针旋转126°=72°+54°,方向竖直向上
right(126)

#画笔颜色变为red
color("red")

#向当前画笔方向反向(即竖直向下)移动n*4.8的像素长度
#加长了树干,并覆盖掉原有颜色
backward(n * 4.8)

#颜色变为dark green,可以更好观察画笔移动情况
color("dark green")

#自定义函数,传入d和s
def tree(d, s):
    
    #如果d小于或等于0,则结束
    if d <= 0: return
    
    #向当前方向前进s像素长度
    forward(s)
    color("black")
    
    #递归调用
    tree(d - 1, s * .8)
    
    color("red")
    right(120)
    
    tree(d - 3, s * .5)
    
    color("blue")
    right(120)
    
    tree(d - 3, s * .5)
    color("green")
    right(120)
    
    backward(s)
    color("orange")

tree(15, n)
#绿色部分结束

#函数调用结束后,换成黄色
color("yellow")

#向与当前方向相反的方向移动n/2像素长度
backward(n / 2)


#调用随机模块中的函数,实现叶子飘落在地上,循环200for i in range(200):
    
    ##random.random()是指随机生成(0,1)之间的浮点数
    #水平方向a取[-200,200]
    a = 200 - 400 * random.random()
   
   
    #竖直方向b取[-10,10]
    b = 10 - 20 * random.random()
   
    up()
    forward(b)
    left(90)
    forward(a)
    down()
    
    #随机选择颜色
    ##random.randint(上限,下限),随机生成在范围之内的整数,两个参数分别表示上限和下限
    ##randint为random模块下的函数,在01之间产生随机数
    if random.randint(0, 1) == 0:
        
        #如果随机数为0,则颜色为tomato
        color('tomato')
        
    else:
        #否则颜色为wheat
        color('wheat')
    
    #每次画两个圈
    circle(2)
    
    #即penup,提起笔移动,不绘制图形,用于另起一个地方绘制
    up()
    
    backward(a)
    
    right(90)
    
    backward(b)
    #本循环的最后一个语句

#测试一下sleep函数功能,为何要sleep呢?
##print ("Start : %s" % time.ctime())
#推迟线程的运行?单位为s
time.sleep(60)
##print ("End : %s" % time.ctime())

The results of the operation are as follows
Insert picture description here

The code is found on the Internet, the comments are written by myself, and the code has been slightly changed for better observation. I don’t know the purpose of using sleep for the time being. If anyone knows about it, please let me know in the [comment area].

For reprint, please indicate the source.

Guess you like

Origin blog.csdn.net/m0_51336041/article/details/113406419