python2024新年代码
时间: 2023-12-01 18:43:07 浏览: 265
很高兴为您介绍Python 2024新年代码。以下是一个简单的示例,可以在Python中创建一个绚丽多彩的新年烟花效果:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen = pygame.display.set_mode((800, 600))
# 设置标题
pygame.display.set_caption("Python 2024新年烟花")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义烟花类
class Firework:
def __init__(self, x, y):
self.x = x
self.y = y
self.gravity = 0.1
self.lifespan = 100
self.velocity = -10
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.particles = []
for i in range(100):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
self.velocity += self.gravity
self.y += self.velocity
self.lifespan -= 1
for particle in self.particles:
particle.update()
def draw(self):
for particle in self.particles:
particle.draw()
# 定义粒子类
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.gravity = 0.1
self.lifespan = 100
self.velocity = (random.uniform(-1, 1), random.uniform(-1, 1))
def update(self):
self.velocity = (self.velocity[0], self.velocity[1] + self.gravity)
self.x += self.velocity[0]
self.y += self.velocity[1]
self.lifespan -= 1
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 2)
# 定义烟花列表
fireworks = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充背景色
screen.fill(BLACK)
# 更新和绘制烟花
for firework in fireworks:
firework.update()
firework.draw()
if firework.lifespan <= 0:
fireworks.remove(firework)
# 添加新的烟花
if random.randint(0, 100) < 5:
fireworks.append(Firework(random.randint(0, 800), 600))
# 刷新屏幕
pygame.display.flip()
# 退出pygame
pygame.quit()
```
阅读全文