import pygame
import random
import math
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
screen = pygame.display.set_mode((800, 650))
pygame.display.set_caption("Heart Particle Effect")
# 定义颜色
# BLUE = (0, 162, 232)
BLUE = (250, 127, 142)
BLACK = (0, 0, 0)
# 粒子类
class Particle:
def __init__(self, x, y):
self.origin_x = x
self.origin_y = y
self.x = random.uniform(0, 800)
self.y = random.uniform(0, 600)
self.size = random.uniform(2, 5)
self.color = BLUE
self.speed_x = random.uniform(-0.5, 0.5)
self.speed_y = random.uniform(-0.5, 0.5)
self.lifetime = random.randint(400, 500)
self.pause_time = 0.1
self.paused = False
self.aggregating = True
def update(self):
if self.paused:
self.pause_time -= 1/60
if self.pause_time <= 0:
self.paused = False
self.aggregating = False
elif self.aggregating:
self.x += (self.origin_x - self.x) * 0.05
self.y += (self.origin_y - self.y) * 0.05
distance = math.sqrt((self.origin_x - self.x) ** 2 + (self.origin_y - self.y) ** 2)
if distance < 2:
self.paused = True
self.pause_time = 0.1
else:
self.x += self.speed_x
self.y += self.speed_y
self.lifetime -= 1
if self.lifetime <= 0:
self.__init__(self.origin_x, self.origin_y)
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), int(self.size))
# 根据心形方程生成粒子
def generate_heart_particles(num_particles):
particles = []
for _ in range(num_particles):
t = random.uniform(0, 2 * math.pi)
x = 16 * math.sin(t) ** 3 * 20 + 400
y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)) * 20 + 300
particles.append(Particle(x, y))
return particles
particles = generate_heart_particles(400)
clock = pygame.time.Clock()
# 主循环
running = True
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for particle in particles:
particle.update()
particle.draw(screen)
pygame.display.flip()
clock.tick(60) # 控制帧率为60帧每秒
pygame.quit()