3d粒子圣诞树代码用python
时间: 2023-12-21 12:32:30 浏览: 466
以下是一个用Python绘制3D粒子圣诞树的代码示例:
```python
import pygame
from pygame.locals import *
from random import randint
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("3D粒子圣诞树")
# 定义颜色
GREEN = (0, 255, 0)
BROWN = (139, 69, 19)
WHITE = (255, 255, 255)
# 定义圣诞树参数
tree_width = 200
tree_height = 400
tree_x = 400
tree_y = 500
# 定义粒子参数
num_particles = 100
particles = []
# 创建粒子类
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((2, 2))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed_x = randint(-1, 1)
self.speed_y = randint(-3, 0)
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
if self.rect.y < 0:
self.rect.y = 600
self.speed_y = randint(-3, 0)
# 创建粒子群
for _ in range(num_particles):
particle = Particle(tree_x + randint(-tree_width//2, tree_width//2), tree_y - tree_height)
particles.append(particle)
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
# 绘制背景
screen.fill((0, 0, 0))
# 绘制圣诞树
pygame.draw.rect(screen, BROWN, (tree_x - tree_width//2, tree_y, tree_width, tree_height))
pygame.draw.polygon(screen, GREEN, [(tree_x - tree_width//2 - 50, tree_y), (tree_x + tree_width//2 + 50, tree_y), (tree_x, tree_y - 200)])
# 更新和绘制粒子
for particle in particles:
particle.update()
screen.blit(particle.image, particle.rect)
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
阅读全文