Python樱花树源代码
时间: 2023-11-05 20:17:27 浏览: 79
以下是Python实现樱花树的代码。
```python
import turtle
import random
# 定义花瓣颜色列表
colorList = ['pink', 'lightPink', 'hotPink', 'deepPink', 'paleVioletRed', 'mediumVioletRed']
# 定义花朵的大小和颜色
def drawFlower(size, color):
turtle.speed(0)
turtle.penup()
turtle.forward(size)
turtle.left(90)
turtle.pendown()
turtle.color(color)
turtle.begin_fill()
turtle.circle(size/2, 180)
turtle.circle(size/4, 180)
turtle.end_fill()
turtle.right(90)
turtle.penup()
turtle.backward(size)
# 定义画樱花树的递归函数
def drawTree(branchLen):
if branchLen > 3:
# 随机设置笔的颜色和宽度
turtle.pensize(random.uniform(1, 5))
turtle.color('brown')
# 绘制主干
turtle.forward(branchLen)
turtle.right(20)
drawTree(branchLen-random.uniform(15, 25))
turtle.left(40)
drawTree(branchLen-random.uniform(15, 25))
turtle.right(20)
turtle.backward(branchLen)
# 绘制花朵
if branchLen <= 40:
flowerSize = random.uniform(5, 10)
flowerColor = random.choice(colorList)
drawFlower(flowerSize, flowerColor)
# 设置画布和画笔
turtle.Screen().setup(width=800, height=600)
turtle.Screen().bgcolor('lightBlue')
turtle.left(90)
turtle.penup()
turtle.backward(200)
turtle.pendown()
# 开始绘制樱花树
drawTree(100)
# 隐藏画笔
turtle.hideturtle()
# 点击关闭窗口
turtle.done()
```
运行代码后,会弹出一个窗口,显示绘制的樱花树。点击窗口后,程序会退出。
阅读全文