写一个撒花的代码
时间: 2023-12-01 07:06:28 浏览: 24
以下是一个简单的撒花动画,带有随机颜色和位置:
```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("撒花")
# 定义颜色列表
colors = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 128, 0), (0, 0, 255), (75, 0, 130), (238, 130, 238)]
# 定义粒子类
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = random.choice(colors)
self.size = random.randint(10, 20)
self.speed = random.randint(5, 10)
def move(self):
self.y -= self.speed
if self.y < -self.size:
self.reset()
def reset(self):
self.x = random.randint(0, screen_width)
self.y = screen_height + self.size
self.color = random.choice(colors)
self.size = random.randint(10, 20)
self.speed = random.randint(5, 10)
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
# 定义粒子列表
particles = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 添加粒子
particles.append(Particle(random.randint(0, screen_width), screen_height))
# 更新粒子
for particle in particles:
particle.move()
particle.draw()
# 移除屏幕外的粒子
particles = [particle for particle in particles if particle.y > -particle.size]
# 刷新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
运行代码,窗口将会显示出一个不断撒花的动画。