
 下面是一个用python编写的简单烟花特效代码,使用了pygame库来实现图形显示。请确保你已经安装了pygame库,如果没有安装,可以使用pip install pygame来安装70个python的练手项目。
import pygame
import random
# 初始化pygame
pygame.init()
# 屏幕大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 烟花粒子类
class particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
        self.size = 5
        self.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.05
    def draw(self):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.size))
particles = []
running = true
while running:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            running = false
    x, 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 pygame
import sys
import random
pygame.init()
# 设置屏幕尺寸和标题
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("fireworks")
# 定义颜色
white = (255, 255, 255)
# 定义烟花粒子类
class particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        self.radius = 2
        self.dx = random.randint(-5, 5)
        self.dy = random.randint(-5, 5)
    def move(self):
        self.x += self.dx
        self.y += self.dy
    def 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)
 
             我要评论
我要评论 
                                             
                                             
                                            
发表评论