python新年烟花
时间: 2024-01-02 18:22:54 浏览: 126
新年快乐! python实现绚烂的烟花绽放效果
5星 · 资源好评率100%
以下是使用Python制作新年烟花的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("New Year Fireworks")
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, screen_width)
self.y = screen_height
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.randint(1, 5)
def move(self):
self.y -= self.speed
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, int(self.y)), 3)
# 创建烟花列表
fireworks = []
# 游戏主循环
running = True
while running:
screen.fill((0, 0, 0)) # 清空屏幕
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
fireworks.append(Firework())
if event.key == pygame.K_2:
for i in range(10):
fireworks.append(Firework())
for firework in fireworks:
firework.move()
firework.draw()
pygame.display.flip() # 更新屏幕显示
# 退出游戏
pygame.quit()
```
运行以上代码,按下键盘的1键会生成一个新的烟花,按下2键会同时生成10个烟花。烟花会从屏幕底部向上移动,并以随机颜色绘制在屏幕上。
阅读全文