用python代码绘制一个会开花的圣诞树
时间: 2023-12-21 10:46:35 浏览: 69
好的,以下是Python代码实现:
```
from turtle import *
import random
# 设置画板和画笔的参数
bgcolor("#E2D8B7")
t = Turtle()
t.speed(10)
t.penup()
t.left(90)
t.goto(0, 0)
t.pendown()
# 画树干
t.color("#886A08")
t.pensize(10)
t.goto(0, -150)
t.penup()
# 设置圣诞树的信息
colors = ["red", "yellow", "white", "blue", "green", "orange", "purple", "pink"]
lengths = [10,15,20,25,30,35,40,45,50,55,60]
startX = random.randint(-200,200)
startY = random.randint(-100,-50)
numOfBranches = random.randint(5,10)
# 画圆形装饰物
def drawCircle(x, y, size):
t.penup()
t.goto(x, y)
t.pendown()
t.color(random.choice(colors))
t.begin_fill()
t.circle(size)
t.end_fill()
# 画三角形树枝
def drawTriangle(x, y, size):
t.penup()
t.goto(x, y)
t.pendown()
t.color("green")
t.begin_fill()
t.setheading(0)
t.forward(size)
t.right(120)
t.forward(size)
t.right(120)
t.forward(size)
t.right(120)
t.end_fill()
# 随机生成布置位置以及装饰品数量等
for i in range(numOfBranches):
t.color("brown")
branchX = random.randint(startX-100, startX+100)
branchY = random.randint(startY-50, startY)
t.penup()
t.goto(branchX, branchY)
t.setheading(270)
t.pendown()
t.forward(random.randint(40,60))
# 画三角形树枝
for j in range(6):
drawTriangle(branchX, branchY + (j*10), lengths[random.randint(0,len(lengths)-1)])
# 布置圆形装饰物
for k in range(10):
drawCircle(branchX + random.randint(-30, 30), branchY + random.randint(-30, 30), random.randint(5,20))
# 达到最后的效果后等待3秒,然后退出绘图
done()
```
运行这段代码将会出现一个随机生成的圣诞树,树上的圆形装饰物和三角形树枝都是随机生成的,每次运行都会不同。
阅读全文