用c++写一个烟花
时间: 2023-07-01 08:25:41 浏览: 56
好的,下面是一个用C++语言实现的烟花程序:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
const int SCREEN_WIDTH = 80;
const int SCREEN_HEIGHT = 25;
struct Particle {
float x;
float y;
float vx;
float vy;
float ax;
float ay;
float life;
};
void updateParticle(Particle& p, float dt) {
p.vx += p.ax * dt;
p.vy += p.ay * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
p.life -= dt;
}
void drawParticle(Particle& p) {
int ix = int(p.x * SCREEN_WIDTH);
int iy = int(p.y * SCREEN_HEIGHT);
if (ix >= 0 && ix < SCREEN_WIDTH && iy >= 0 && iy < SCREEN_HEIGHT) {
cout << "\033[" << iy << ";" << ix << "H*";
}
}
void updateExplosion(Particle* particles, int count, float dt) {
for (int i = 0; i < count; i++) {
updateParticle(particles[i], dt);
}
}
void drawExplosion(Particle* particles, int count) {
for (int i = 0; i < count; i++) {
drawParticle(particles[i]);
}
}
int main() {
srand(time(nullptr));
Particle fireworks[32];
Particle explosion[128];
float t = 0.0f;
float dt = 0.1f;
while (true) {
system("cls");
// Update and draw fireworks
for (int i = 0; i < 32; i++) {
Particle& p = fireworks[i];
updateParticle(p, dt);
drawParticle(p);
if (p.life <= 0.0f) {
// Explode
for (int j = 0; j < 128; j++) {
Particle& e = explosion[j];
e.x = p.x;
e.y = p.y;
e.vx = (rand() % 100 - 50) * 0.01f;
e.vy = (rand() % 100 - 50) * 0.01f;
e.ax = 0.0f;
e.ay = -0.1f;
e.life = 1.0f;
}
}
}
// Draw explosion and update
drawExplosion(explosion, 128);
updateExplosion(explosion, 128, dt);
// Create new fireworks
if (rand() % 100 < 5) {
Particle& p = fireworks[rand() % 32];
p.x = rand() % 100 * 0.01f;
p.y = 0.0f;
p.vx = 0.0f;
p.vy = 1.0f;
p.ax = 0.0f;
p.ay = -0.1f;
p.life = 1.0f;
}
// Wait a little bit
Sleep(50);
// Increment time
t += dt;
}
return 0;
}
```
这个程序使用了粒子系统来模拟烟花。程序使用了两个结构体,一个是表示粒子的Particle结构体,另一个是用于存储所有爆炸粒子的explosion数组。
程序使用了updateParticle()和drawParticle()函数来更新和绘制每个粒子。updateParticle()函数使用欧拉方法来更新粒子的位置和速度,而drawParticle()函数则使用控制台的光标来绘制粒子。
程序的主循环中,程序先更新和绘制所有的烟花粒子。如果一个烟花粒子已经消失了,程序就会创建一个新的爆炸粒子系统,并将每个粒子的位置设置为烟花粒子的位置。然后程序就会更新和绘制所有的爆炸粒子。
最后,程序会等待一段时间,然后重新开始循环。程序使用Sleep()函数来等待一段时间,以控制烟花的速度。
运行这个程序,您将看到一个美丽的烟花在您的控制台中绽放。