用python写一段程序使得能够画出一棵色彩绚丽的圣诞树
时间: 2023-10-01 07:06:40 浏览: 63
好的,我可以帮你实现。以下是代码:
```python
import turtle
import random
# 定义圣诞树绘制函数
def draw_tree(t, trunk_length, levels):
# 绘制树干
t.pensize(trunk_length / 10)
t.down()
t.color("brown")
t.forward(trunk_length)
t.right(90)
# 绘制树枝
if levels > 0:
angle = random.randint(15, 45)
t.forward(trunk_length / 2)
t.right(angle)
draw_tree(t, trunk_length * 0.6, levels - 1)
t.left(angle * 2)
draw_tree(t, trunk_length * 0.6, levels - 1)
t.right(angle)
t.backward(trunk_length / 2)
# 定义圣诞节彩灯绘制函数
def draw_light(t, x, y, color):
t.up()
t.goto(x, y)
t.down()
t.dot(20, color)
# 定义主函数
def main():
turtle.title("圣诞树")
turtle.bgcolor("black")
t = turtle.Turtle()
t.speed(0)
t.up()
t.goto(0, -300)
t.down()
t.color("green")
draw_tree(t, 200, 5)
# 绘制彩灯
colors = ["red", "orange", "yellow", "green", "blue", "purple", "pink", "white"]
for i in range(100):
x = random.randint(-500, 500)
y = random.randint(-300, 300)
color = random.choice(colors)
draw_light(t, x, y, color)
t.hideturtle()
turtle.done()
if __name__ == "__main__":
main()
```
运行程序后,你将会看到一个绚丽多彩的圣诞树!
阅读全文