圣诞树粒子特效代码py
时间: 2024-12-25 21:24:49 浏览: 1
创建圣诞树粒子特效的Python代码通常涉及动画、图形库(如Pygame或PIL)以及随机数生成。下面是一个简单的示例,使用Pygame库来绘制基本的圣诞树形状并添加一些随机移动的“雪花”粒子:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 定义颜色
white = (255, 255, 255)
green = (0, 255, 0)
# 定义圣诞树形状
def draw_tree():
trunk_width = 30
trunk_height = 100
trunk_x = screen_width // 2 - trunk_width // 2
trunk_y = screen_height - trunk_height
# 画树干
pygame.draw.rect(screen, green, (trunk_x, trunk_y, trunk_width, trunk_height))
# 画树枝
branch_length = 200
branches_count = 7
for i in range(branches_count):
angle = i * (2 * 3.14 / branches_count) + random.uniform(-0.1, 0.1)
branch_top_y = trunk_y + trunk_height / 2 + branch_length * math.sin(angle)
branch_top_x = trunk_x + trunk_width / 2 + branch_length * math.cos(angle)
pygame.draw.line(screen, white, (trunk_x, trunk_y), (branch_top_x, branch_top_y), 10)
# 粒子雪花
particle_size = 5
snow_particles = []
for _ in range(100):
snow_particles.append({
'x': random.randint(0, screen_width),
'y': random.randint(-50, 0),
'dx': random.uniform(-2, 2),
'dy': random.uniform(-2, 2),
'size': particle_size,
'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
})
while True:
# 清除屏幕
screen.fill(white)
# 绘制圣诞树
draw_tree()
# 移动和绘制粒子
for particle in snow_particles:
particle['y'] += particle['dy']
if particle['y'] > screen_height:
particle.pop('y')
pygame.draw.circle(screen, particle['color'], (int(particle['x']), int(particle['y'])), particle['size'])
# 更新显示
pygame.display.flip()
# 检查事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
阅读全文