动态粒子代码

代码

import pygame
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Dynamic Particle Effect")

# 定义颜色
BLACK = (0, 0, 0)

# 粒子类
class Particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        # 随机速度
        self.vx = random.uniform(-3, 3)
        self.vy = random.uniform(-3, 3)
        # 粒子大小
        self.size = random.randint(2, 5)
        # 粒子透明度
        self.alpha = 255
        # 颜色
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    def update(self):
        # 更新粒子位置
        self.x += self.vx
        self.y += self.vy
        # 降低透明度
        self.alpha -= 5
        if self.alpha < 0:
            self.alpha = 0

    def draw(self, surface):
        # 创建一个带有透明度的表面
        s = pygame.Surface((self.size * 2, self.size * 2), pygame.SRCALPHA)
        pygame.draw.circle(s, (*self.color, self.alpha), (self.size, self.size), self.size)
        surface.blit(s, (int(self.x - self.size), int(self.y - self.size)))

# 粒子列表
particles = []

# 主循环
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 每帧添加新粒子
    for _ in range(5):
        particles.append(Particle(width // 2, height // 2))

    # 更新和绘制粒子
    screen.fill(BLACK)
    for particle in particles[:]:
        particle.update()
        if particle.alpha > 0:
            particle.draw(screen)
        else:
            particles.remove(particle)

    # 更新显示
    pygame.display.flip()
    # 控制帧率
    clock.tick(60)

# 退出pygame
pygame.quit()

演示效果

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