与春光共舞,独属于开发者们的春日场景是什么样的?
用python 生成了樱花树落花动态场景,居然花了我30分钟调试位置。
import turtle
import random
# 设置画布
screen = turtle.Screen()
screen.bgcolor('skyblue')
screen.title('春日场景:樱花飘落')
# 绘制草地
def draw_grass():
turtle.penup()
turtle.goto(-400, -200)
turtle.pendown()
turtle.color('lightgreen')
turtle.begin_fill()
turtle.setheading(0)
for _ in range(2):
turtle.forward(800)
turtle.left(90)
turtle.forward(300)
turtle.left(90)
turtle.end_fill()
# 绘制樱花树干
def draw_tree_trunk():
turtle.penup()
turtle.goto(-15, -200) # 树干底部起点,确保位置正确
turtle.pendown()
turtle.color('saddlebrown')
turtle.begin_fill()
turtle.setheading(90)
for _ in range(2):
turtle.forward(150) # 树干高度
turtle.right(90)
turtle.forward(30) # 树干宽度
turtle.right(90)
turtle.end_fill()
# 绘制樱花树冠
def draw_tree_crown():
turtle.penup()
turtle.goto(0, -50) # 树冠的中心与树干对齐
turtle.color('pink')
turtle.begin_fill()
turtle.circle(100) # 樱花树冠大小
turtle.end_fill()
# 绘制动态樱花花瓣飘落
def draw_falling_petals():
colors = ['lightpink', 'pink', 'hotpink']
for _ in range(50):
x = random.randint(-300, 300)
y = random.randint(-200, -50) # 花瓣落在绿地上
size = random.uniform(3, 6)
color = random.choice(colors)
draw_petal(x, y, size, color)
# 绘制单个花瓣
def draw_petal(x, y, size, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(color)
turtle.begin_fill()
turtle.circle(size)
turtle.end_fill()
# 绘制太阳
def draw_sun():
turtle.penup()
turtle.goto(250, 250)
turtle.color('gold')
turtle.begin_fill()
turtle.circle(50)
turtle.end_fill()
# 添加春日诗句
def write_poem():
turtle.penup()
turtle.goto(-350, 250) # 左上角位置
turtle.color('black')
turtle.write(
'与春光共舞,代码写诗\n'
'樱花飘落,职场如画\n'
'Python绘春,开发者心中的四月天',
align='left',
font=('Arial', 16, 'normal')
)
# 主函数:绘制春日场景
def main():
turtle.speed(0)
draw_grass()
draw_sun()
draw_tree_trunk()
draw_tree_crown()
draw_falling_petals()
write_poem()
turtle.hideturtle()
screen.mainloop()
# 调用主函数
main()
效果图
赞11
踩0