python烟花代码

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

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()

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

python烟花代码_第2张图片

代码二:

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)

你可能感兴趣的:(python,python,pygame,开发语言)