python烟花表白源代码
在 Python 中创建一个简单的烟花表白效果可以使用 Pygame 库。
pythonimport pygame
import sys
import random
import math
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("烟花表白")
# 定义颜色
white = (255, 255, 255)
red = (255, 0, 0)
# 定义烟花类
class Firework:
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.speed = random.uniform(1, 5)
self.angle = random.uniform(0, 2 * math.pi)
def move(self):
self.x += self.speed * math.cos(self.angle)
self.y += self.speed * math.sin(self.angle)
self.speed -= 0.1
self.radius += 0.1
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.radius))
# 主循环
fireworks = []
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(white)
# 生成烟花
if random.randint(1, 100) < 2:
fireworks.append(Firework(random.randint(100, width - 100), height))
# 更新和绘制烟花
for firework in fireworks:
firework.move()
firework.draw()
# 移除消失的烟花
fireworks = [fw for fw in fireworks if fw.radius < 50]
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
请确保你的环境中安装了 Pygame。可以使用
bashpip install pygame
运行上述代码后,窗口将打开,并且屏幕上会出现随机生成的烟花效果。
如果你想在烟花爆炸的时候显示一些特殊的信息,例如表白文字,你可以在Firework
类中添加一些属性,以在烟花达到一定半径时显示该信息。
pythonimport pygame
import sys
import random
import math
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("烟花表白")
white = (255, 255, 255)
red = (255, 0, 0)
class Firework:
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.speed = random.uniform(1, 5)
self.angle = random.uniform(0, 2 * math.pi)
self.message = "I Love You!" if random.randint(1, 10) == 1 else None
def move(self):
self.x += self.speed * math.cos(self.angle)
self.y += self.speed * math.sin(self.angle)
self.speed -= 0.1
self.radius += 0.1
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.radius))
if self.message and self.radius > 20:
font = pygame.font.Font(None, 36)
text = font.render(self.message, True, red)
text_rect = text.get_rect(center=(width // 2, height // 2))
screen.blit(text, text_rect)
fireworks = []
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(white)
if random.randint(1, 100) < 2:
fireworks.append(Firework(random.randint(100, width - 100), height))
for firework in fireworks:
firework.move()
firework.draw()
fireworks = [fw for fw in fireworks if fw.radius < 50]
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
这个例子中,当烟花的半径超过20时,将显示一个"I Love You!"的信息。你可以根据需要调整显示信息的条件和内容。希望这能满足你的需求!