使用python写一段脚本,可以实现桌面放烟花的效果
时间: 2024-03-12 22:47:07 浏览: 108
好的,下面是一个简单的Python脚本,可以在桌面上放置烟花:
```python
import pygame
import random
import time
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载烟花图像
firework_image = pygame.image.load('firework.png')
# 定义烟花的类
class Firework(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = firework_image
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.timer = 0
self.exploded = False
def update(self):
# 烟花爆炸
if self.timer >= 60 and not self.exploded:
self.explode()
self.exploded = True
# 烟花消失
if self.timer >= 120:
self.kill()
self.timer += 1
def explode(self):
# 在烟花周围生成小火花
for i in range(30):
particle = Particle(self.rect.x, self.rect.y)
all_sprites.add(particle)
particles.add(particle)
# 定义小火花的类
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((2, 2))
self.image.fill((255, 255, 255))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_x = random.randint(-10, 10) / 10
self.vel_y = random.randint(-10, 10) / 10
self.timer = 0
def update(self):
self.rect.x += self.vel_x
self.rect.y += self.vel_y
self.vel_y += 0.1
self.timer += 1
if self.timer >= 60:
self.kill()
# 创建精灵组
all_sprites = pygame.sprite.Group()
fireworks = pygame.sprite.Group()
particles = pygame.sprite.Group()
# 主循环
while True:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 随机生成烟花
if random.random() < 0.01:
x = random.randint(0, screen_width)
y = random.randint(0, screen_height)
firework = Firework(x, y)
all_sprites.add(firework)
fireworks.add(firework)
# 更新精灵组
all_sprites.update()
# 清空屏幕
screen.fill((0, 0, 0))
# 绘制精灵组
all_sprites.draw(screen)
# 更新屏幕
pygame.display.update()
# 延时一段时间
time.sleep(0.01)
```
在运行脚本之前,你需要先在同一目录下放置一张名为`firework.png`的烟花图像。运行脚本后,将会在桌面上不断生成烟花。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)