用python写一段150行的代码,要求画出一棵动态有颜色的圣诞树,使用定义函数,if条件判断,for循环
时间: 2024-04-08 14:32:53 浏览: 50
当然,下面是一种实现动态有颜色的圣诞树的Python代码,使用了定义函数、if条件判断和for循环。请注意,代码中可能包含一些调用其他函数或模块的部分,这些部分需要根据你的具体需求进行补充。
```python
import turtle
import random
def draw_tree(size, level):
if level <= 0:
return
else:
colors = ["green", "dark green", "forest green", "lime green"]
turtle.color(random.choice(colors))
turtle.forward(size)
turtle.left(45)
draw_tree(size * 0.6, level - 1)
turtle.right(90)
draw_tree(size * 0.6, level - 1)
turtle.left(45)
turtle.backward(size)
def draw_star(size):
turtle.color('yellow')
turtle.begin_fill()
for _ in range(5):
turtle.forward(size)
turtle.right(144)
turtle.end_fill()
def draw_baubles(x, y, colors):
turtle.penup()
turtle.goto(x, y)
for i in range(5):
turtle.pendown()
turtle.color(random.choice(colors))
turtle.circle(10)
turtle.penup()
turtle.forward(30)
def draw_gift(x, y, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(color)
turtle.begin_fill()
for _ in range(4):
turtle.forward(50)
turtle.right(90)
turtle.end_fill()
def draw_christmas_tree():
screen = turtle.Screen()
screen.bgcolor("black")
turtle.speed(0)
turtle.penup()
turtle.goto(0, -200)
turtle.pendown()
turtle.color("brown")
turtle.begin_fill()
turtle.forward(20)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.forward(20)
turtle.end_fill()
draw_tree(100, 5)
draw_star(30)
bauble_colors = ["red", "blue", "gold", "purple", "silver"]
draw_baubles(-100, 100, bauble_colors)
draw_baubles(-80, 150, bauble_colors)
draw_baubles(-60, 200, bauble_colors)
draw_gift(-50, -150, "red")
draw_gift(100, -100, "green")
draw_gift(-150, -50, "blue")
turtle.hideturtle()
turtle.done()
draw_christmas_tree()
```
这段代码使用了turtle库来进行绘图,绘制了一个动态有颜色的圣诞树,包括树干、树枝、星星、彩球和礼物。代码中使用了定义函数(draw_tree、draw_star、draw_baubles、draw_gift和draw_christmas_tree)、if条件判断和for循环来实现不同的绘制功能。你可以根据需要调整代码中的绘制位置、颜色和尺寸等参数。
阅读全文