效果图:(真实情况是动态的)
完整代码:
import turtle
import random
# 初始化画布
turtle.bgcolor("#001f3f") # 偏深蓝色的背景
turtle.title("下雪的画面")
turtle.speed(0)
turtle.hideturtle()
turtle.tracer(0)
# 雪花的数量
num_snowflakes = 200
snowflakes = []
# 创建雪花
for _ in range(num_snowflakes):
x = random.randint(-300, 300)
y = random.randint(0, 600)
size = random.randint(2, 6) # 随机大小
fall_speed = random.uniform(3, 6) # 增加下落速度
snowflakes.append([x, y, size, fall_speed])
def draw_snowflake(x, y, size):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.dot(size, "white") # 使用随机大小的雪花
def fall_snowflakes():
turtle.clear()
for snowflake in snowflakes:
x, y, size, fall_speed = snowflake
draw_snowflake(x, y, size)
# 更新雪花的位置
y -= fall_speed
if y < -300: # 如果雪花落到屏幕底部,重置位置
y = random.randint(600, 800)
x = random.randint(-300, 300)
size = random.randint(2, 6) # 随机大小
fall_speed = random.uniform(3, 6) # 增加下落速度
snowflake[0], snowflake[1], snowflake[2], snowflake[3] = x, y, size, fall_speed # 更新雪花位置、大小和速度
turtle.update()
turtle.ontimer(fall_snowflakes, 20) # 每20毫秒更新一次
def main():
fall_snowflakes()
turtle.done()
if __name__ == "__main__":
main()