python粒子光效圣诞树python粒子光效圣诞树
时间: 2023-12-18 09:29:50 浏览: 336
基于Python实现的圣诞树趣味特效
以下是一个使用Python实现的粒子光效圣诞树的示例代码:
```python
import random
import time
# 定义颜色常量
COLORS = ['\033[91m', '\033[92m', '\033[93m', '\033[94m', '\033[95m', '\033[96m']
# 定义粒子类
class Particle:
def __init__(self, x, y, speed, angle):
self.x = x
self.y = y
self.speed = speed
self.angle = angle
self.color = random.choice(COLORS)
def move(self):
self.x += self.speed * math.cos(self.angle)
self.y -= self.speed * math.sin(self.angle)
self.speed -= 0.1
def __str__(self):
return f'{self.color}●\033[0m'
# 定义绘制函数
def draw_tree(height):
particles = []
for i in range(height):
row = ''
for j in range(height - i - 1):
row += ' '
for j in range(i * 2 + 1):
if i == height - 1:
row += '★'
else:
particle = Particle(i, j - i, random.uniform(0.5, 2), random.uniform(0, math.pi * 2))
particles.append(particle)
row += str(particle)
print(row)
return particles
# 定义更新函数
def update(particles):
for particle in particles:
particle.move()
particles = [p for p in particles if p.speed > 0]
time.sleep(0.1)
return particles
# 主函数
def main():
height = 10
particles = draw_tree(height)
while particles:
particles = update(particles)
if __name__ == '__main__':
main()
```
运行上述代码,即可在终端中看到粒子光效圣诞树的效果。
阅读全文