使用python写一段脚本,可以实现桌面放烟花的效果
时间: 2024-03-09 12:49:35 浏览: 31
好的,以下是使用 Python 实现桌面放烟花的脚本:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置屏幕大小和标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Desktop Fireworks")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义烟花粒子类
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.image = pygame.Surface((2, 2))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vx = random.randint(-8, 8)
self.vy = random.randint(-8, 8)
self.gravity = 0.2
def update(self):
self.vx *= 0.95
self.vy *= 0.95
self.vy += self.gravity
self.rect.x += self.vx
self.rect.y += self.vy
if self.rect.y > screen.get_height():
self.kill()
# 定义烟花类
class Firework(pygame.sprite.Sprite):
def __init__(self, x, y, colors):
super().__init__()
self.particles = pygame.sprite.Group()
self.color = random.choice(colors)
self.exploded = False
self.explode_time = random.randint(50, 70)
for i in range(50):
particle = Particle(x, y, self.color)
self.particles.add(particle)
def update(self):
if not self.exploded:
self.particles.update()
if self.particles.sprites()[0].vy >= 0:
self.exploded = True
self.explode()
else:
self.explode_time -= 1
if self.explode_time <= 0:
self.kill()
def draw(self, surface):
self.particles.draw(surface)
def explode(self):
for p in self.particles:
vx = p.rect.x - self.rect.x
vy = p.rect.y - self.rect.y
p.vx = vx / 10
p.vy = vy / 10
if random.randint(0, 1) == 0:
p.vx *= -1
if random.randint(0, 1) == 0:
p.vy *= -1
# 定义烟花管理类
class FireworkManager:
def __init__(self):
self.fireworks = pygame.sprite.Group()
self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
self.counter = 0
def update(self):
self.fireworks.update()
if self.counter % 10 == 0:
x = random.randint(0, screen.get_width())
y = screen.get_height() - 10
firework = Firework(x, y, self.colors)
self.fireworks.add(firework)
self.counter += 1
def draw(self, surface):
surface.fill(BLACK)
self.fireworks.draw(surface)
# 创建烟花管理器
firework_manager = FireworkManager()
# 游戏循环
clock = pygame.time.Clock()
done = False
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 更新和绘制烟花
firework_manager.update()
firework_manager.draw(screen)
# 更新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
运行上述代码,将会在桌面上看到炫酷的烟花效果。注意,因为 Pygame 是基于窗口的,所以在 Windows 系统上需要将窗口最小化或隐藏,才能在桌面上看到效果。