粒子光效圣诞树python
时间: 2023-12-08 09:39:43 浏览: 724
很高兴为您解答。下面是一个使用Python和Pygame库绘制粒子光效圣诞树的示例代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Particle Christmas Tree")
# 定义颜色
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义粒子类
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([4, 4])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.change_x = random.randrange(-3, 4)
self.change_y = random.randrange(-3, 4)
self.life = 60
def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y
self.life -= 1
if self.life == 0:
self.kill()
# 定义粒子组
all_sprites_list = pygame.sprite.Group()
# 定义主循环
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 绘制圣诞树
screen.fill(GREEN)
pygame.draw.rect(screen, BROWN, [375, 500, 50, 100])
pygame.draw.polygon(screen, GREEN, [[275, 500], [475, 500], [375, 350]])
pygame.draw.polygon(screen, GREEN, [[250, 450], [500, 450], [375, 300]])
pygame.draw.polygon(screen, GREEN, [[225, 400], [525, 400], [375, 250]])
# 生成粒子
if random.randrange(0, 10) == 0:
particle = Particle(375, 250)
all_sprites_list.add(particle)
# 更新粒子
all_sprites_list.update()
# 绘制粒子
all_sprites_list.draw(screen)
# 更新屏幕
pygame.display.flip()
clock.tick(60)
# 退出Pygame
pygame.quit()
```
阅读全文