要使用Python制作煙花特效,可以使用Pygame庫來進行圖形繪制和動畫效果的實現。以下是一個簡單的例子代碼,用于繪制煙花特效:
import pygame
import random
# 初始化pygame
pygame.init()
# 設置窗口大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 定義顏色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 煙花粒子類
class Particle:
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.randint(1, 5)
def move(self):
self.y -= self.speed
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.size)
# 創建煙花粒子
def create_particles(x, y):
particle_count = 20
for _ in range(particle_count):
particle = Particle(x, y, random.randint(2, 5))
particles.append(particle)
# 主循環
running = True
particles = []
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
create_particles(mx, my)
# 清空屏幕
screen.fill(BLACK)
# 更新和繪制煙花粒子
for particle in particles:
particle.move()
particle.draw()
if particle.y <= 0:
particles.remove(particle)
# 刷新屏幕
pygame.display.flip()
clock.tick(60)
# 退出程序
pygame.quit()
運行上述代碼,你將會看到一個簡單的窗口,在鼠標點擊的位置產生煙花特效。你可以通過調整參數來改變特效的效果,例如改變粒子數量、速度、顏色等。