下面是一个用Python编写的简单烟花特效代码,使用了Pygame库来实现图形显示。请确保你已经安装了Pygame库,如果没有安装,可以使用pip install pygame来安装。

import pygameimport random# 初始化Pygamepygame.init()# 屏幕大小width, height = 800, 600screen = pygame.display.set_mode((width, height))# 烟花粒子类class Particle:def __init__(self, x, y):self.x = xself.y = yself.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))self.size = 5self.speed = random.randint(1, 5)self.angle = random.uniform(0, 2 * 3.14159)def move(self):self.x += self.speed * 0.5 * cos(self.angle)self.y += self.speed * 0.5 * sin(self.angle)self.size -= 0.05def draw(self):pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.size))particles = []running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falsex, y = pygame.mouse.get_pos()for i in range(30):particles.append(Particle(x, y))for particle in particles:particle.move()if particle.size <= 0:particles.remove(particle)# 清屏screen.fill((0, 0, 0))# 绘制粒子for particle in particles:particle.draw()pygame.display.flip()pygame.quit()

这个代码创建了一个窗口,当你点击鼠标时,会在鼠标位置生成烟花粒子效果。这只是一个简单的示例,你可以根据需要进行扩展和改进。注意,这只是一个基础的烟花特效,实际的烟花特效通常更加复杂和精致。

代码二:

import pygameimport sysimport randompygame.init()# 设置屏幕尺寸和标题WIDTH, HEIGHT = 800, 600screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("Fireworks")# 定义颜色WHITE = (255, 255, 255)# 定义烟花粒子类class Particle:def __init__(self, x, y):self.x = xself.y = yself.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))self.radius = 2self.dx = random.randint(-5, 5)self.dy = random.randint(-5, 5)def move(self):self.x += self.dxself.y += self.dydef draw(self):pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)particles = []clock = pygame.time.Clock()while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()# 当鼠标点击时,产生新的烟花if event.type == pygame.MOUSEBUTTONDOWN:x, y = pygame.mouse.get_pos()for _ in range(100):particle = Particle(x, y)particles.append(particle)screen.fill(WHITE)# 更新和绘制烟花粒子for particle in particles:particle.move()particle.draw()# 移除已经消失的烟花粒子particles = [particle for particle in particles if particle.radius < 100]pygame.display.flip()clock.tick(60)