python画圣诞树带灯
时间: 2023-12-21 15:32:13 浏览: 152
以下是使用Python绘制带灯的圣诞树的代码示例:
```python
import turtle
import random
# 创建画布
screen = turtle.Screen()
screen.bgcolor("black")
# 创建画笔
t = turtle.Turtle()
t.speed(0)
t.color("green")
# 定义绘制圣诞树的函数
def draw_tree(d, s):
if d <= 0:
return
t.forward(s)
t.right(120)
draw_tree(d - 1, s * 0.8)
t.right(120)
draw_tree(d - 3, s * 0.5)
t.right(120)
draw_tree(d - 3, s * 0.5)
t.right(120)
t.backward(s)
# 绘制圣诞树
draw_tree(7, 100)
# 绘制圣诞灯
for i in range(200):
a = 200 - 400 * random.random()
b = 10 - 20 * random.random()
t.up()
t.forward(b)
t.left(90)
t.forward(a)
t.down()
if random.randint(0, 1) == 0:
t.color('red')
else:
t.color('yellow')
t.circle(2)
t.up()
t.backward(a)
t.right(90)
t.backward(b)
# 隐藏画笔
t.hideturtle()
# 结束绘制
turtle.done()
```
阅读全文