Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- import math
- # constants
- WIDTH, HEIGHT = 800, 600
- FPS = 60
- BLACK, WHITE = (0, 0, 0), (255, 255, 255)
- # Initialize Pygame
- pygame.init()
- screen = pygame.display.set_mode((WIDTH, HEIGHT))
- pygame.display.set_caption("Fireworks Animation")
- clock = pygame.time.Clock()
- class Firework:
- #constructor
- def __init__(self, whistle_sound, crack_sound):
- self.x = random.randint(100, WIDTH - 100)
- self.y = HEIGHT
- self.target_y = random.randint(100, HEIGHT // 2)
- self.color = [random.randint(50, 255) for _ in range(3)]
- self.exploded = False
- self.particles = []
- self.whistle_playing = True
- # Import sounds
- self.whistle_sound = pygame.mixer.Sound("firewhistle.mp3")
- self.crack_sound = pygame.mixer.Sound("fireblast.mp3")
- # Play firewhistle sound
- self.whistle_sound.play()
- def update(self):
- if not self.exploded:
- self.y -= 5
- if self.y <= self.target_y:
- self.explode()
- else:
- for particle in self.particles:
- particle.update()
- def draw(self):
- if not self.exploded:
- pygame.draw.circle(screen, self.color, (self.x, self.y), 3)
- else:
- for particle in self.particles:
- particle.draw()
- def explode(self):
- self.exploded = True
- self.whistle_sound.stop() # Stop whistle sound when exploding
- self.crack_sound.play() # Play firecrack sound
- for _ in range(100):
- angle = random.uniform(0, 2 * math.pi)
- speed = random.uniform(2, 6)
- dx = math.cos(angle) * speed
- dy = math.sin(angle) * speed
- self.particles.append(Particle(self.x, self.y, dx, dy, self.color))
- class Particle:
- def __init__(self, x, y, dx, dy, color): #constructor
- self.x = x
- self.y = y
- self.dx = dx
- self.dy = dy
- self.lifetime = random.randint(40, 100)
- self.color = color
- self.size = random.randint(2, 4)
- def update(self):
- self.x += self.dx
- self.y += self.dy
- self.dy += 0.1 #gravityeffect
- self.lifetime -= 1
- def draw(self):
- if self.lifetime > 0:
- alpha = max(0, int((self.lifetime / 100) * 255))
- color_with_alpha = (self.color[0], self.color[1], self.color[2], alpha)
- pygame.draw.circle(screen, color_with_alpha, (int(self.x), int(self.y)), self.size)
- running = True
- fireworks = []
- while running:
- screen.fill(BLACK)
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- # Add new fireworks randomly (1/20 chance)
- if random.randint(1, 20) == 1:
- fireworks.append(Firework(firewhistle_sound, firecrack_sound))
- #draw fireworks
- for firework in fireworks:
- firework.update()
- firework.draw()
- if firework.exploded and all(p.lifetime <= 0 for p in firework.particles):
- fireworks.remove(firework)
- pygame.display.flip()
- clock.tick(FPS)
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement