原始问题:
帮我编一个放烟花的代码
import pygame
import random
import math
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("烟花")
clock = pygame.time.Clock()
class Particle:
def __init__(self, x, y, angle, speed, color):
self.x = x
self.y = y
self.angle = angle
self.speed = speed
self.color = color
self.life = 0
def move(self):
self.x += math.cos(self.angle) * self.speed
self.y += math.sin(self.angle) * self.speed
self.life += 1
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 2)
def create_particles(x, y, color):
particles = []
for _ in range(50):
angle = random.uniform(0, math.pi * 2)
speed = random.uniform(1, 5)
particles.append(Particle(x, y, angle, speed, color))
return particles
def main():
running = True
fireworks = []
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
fireworks.append((create_particles(x, y, color), []))
for firework in fireworks:
particles, sounds = firework[0]
for particle in particles:
particle.move()
particle.draw(screen)
if particle.life > 100:
particles.remove(particle)
if len(particles) == 0:
fireworks.remove(firework)
for sound in sounds:
sound.play()
pygame.time.delay(100)
sound.stop()
pygame.time.delay(200)
fireworks.append((create_particles(random.randint(0, WIDTH), HEIGHT, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))), [])
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
Prev:如何提高国际视野