跨年烟花源代码款python
时间: 2025-01-06 13:22:00 浏览: 11
### Python 跨年烟花效果源代码示例
为了实现更加生动和视觉吸引人的跨年烟花效果,可以使用 `turtle` 模块来绘制动画。下面是一个完整的例子,该程序不仅展示了如何创建不同颜色和样式的烟花,还实现了动态爆炸的效果。
#### 完整的Python跨年烟花代码:
```python
import turtle
import random
from time import sleep
def setup_screen():
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Happy New Year Fireworks!")
return screen
def draw_firework(t, size):
t.pendown()
color_list = ["red", "orange", "yellow", "green", "blue", "purple"]
t.color(random.choice(color_list))
for _ in range(size):
distance = random.randint(10, 30)
angle = random.uniform(-90, 90)
t.forward(distance)
t.backward(distance)
t.right(angle)
def launch_fireworks(num_fireworks=25):
fireworks = []
shapes = ['circle', 'classic', 'square', 'triangle', 'arrow']
for i in range(num_fireworks):
firework = turtle.Turtle()
firework.speed('fastest')
firework.penup()
firework.hideturtle()
firework.shape(random.choice(shapes))
# Position the firework randomly on the canvas
x_position = random.randint(-screen.window_width()//2, screen.window_width()//2)
y_position = random.randint(-screen.window_height()//2, screen.window_height()//2)
firework.goto(x_position, y_position)
fireworks.append(firework)
for f in fireworks:
f.showturtle()
draw_firework(f, random.randint(8, 15)) # Draw each firework with a different number of sparks
f.hideturtle()
if __name__ == "__main__":
screen = setup_screen()
while True:
try:
launch_fireworks()
sleep(2) # Wait before launching next set of fireworks
screen.clear() # Clear previous drawings to simulate new explosions
except KeyboardInterrupt:
break
screen.bye()
```
这段代码首先设置了屏幕背景并定义了一个用于绘制单个烟花的功能函数 `draw_firework()` 。接着,在 `launch_fireworks()` 函数中初始化多个 `Turtle` 对象作为即将爆发的烟花,并随机放置它们的位置。最后进入主循环不断发射新的烟花集合直到用户中断程序[^1]。
阅读全文