生成python烟花代码
时间: 2023-07-10 14:18:08 浏览: 198
好的,以下是Python烟花代码:
```python
import random
import time
WIDTH = 80
HEIGHT = 25
class Particle:
def __init__(self, x, y, vx, vy, color):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.color = color
def move(self):
self.x += self.vx
self.y += self.vy
self.vy += 1
def draw(self, canvas):
canvas[self.y][self.x] = self.color
def create_firework():
x = random.randint(0, WIDTH - 1)
y = HEIGHT - 1
vx = random.randint(-2, 2)
vy = random.randint(-10, -5)
color = random.randint(1, 7)
return Particle(x, y, vx, vy, color)
def explode(particle, canvas):
particles = []
for i in range(30):
speed = random.randint(5, 20)
angle = random.uniform(0, 2 * math.pi)
vx = speed * math.sin(angle)
vy = speed * math.cos(angle)
color = random.randint(1, 7)
particles.append(Particle(particle.x, particle.y, vx, vy, color))
for i in range(20):
canvas[particle.y][particle.x] = random.randint(1, 7)
time.sleep(0.1)
canvas[particle.y][particle.x] = 0
time.sleep(0.1)
return particles
def update(canvas, particles):
for particle in particles:
particle.move()
if particle.y >= HEIGHT:
continue
particle.draw(canvas)
particles = [particle for particle in particles if particle.y < HEIGHT]
return particles
def main():
canvas = [[0 for x in range(WIDTH)] for y in range(HEIGHT)]
particles = []
while True:
if len(particles) < 10:
particles.append(create_firework())
for particle in particles:
particles += explode(particle, canvas)
particles = update(canvas, particles)
for row in canvas:
line = ''.join(str(x) for x in row)
print(line)
time.sleep(0.05)
print('\x1b[1;1H\x1b[2J')
if __name__ == '__main__':
main()
```
这个代码会生成一个基于字符的烟花动画,可以在终端中运行。希望你能喜欢!
阅读全文