利用 C++面向对象的编程思想,设计并实现多束烟花上升并在一定高度绽放绽放效 果
时间: 2024-03-06 21:47:48 浏览: 17
以下是一个简单的 C++ 代码示例,用于实现多束烟花上升并在一定高度绽放绽放效果:
```c++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
const int SCREEN_WIDTH = 80;
const int SCREEN_HEIGHT = 24;
class Firework {
public:
Firework(int x, int y) : m_x(x), m_y(y), m_height(0), m_exploded(false) {}
void rise();
void explode();
bool is_exploded() { return m_exploded; }
private:
int m_x;
int m_y;
int m_height;
bool m_exploded;
};
void Firework::rise() {
if (m_height >= SCREEN_HEIGHT / 2) {
explode();
} else {
m_height++;
cout << "\033[" << m_y - m_height << ";" << m_x << "H*";
}
}
void Firework::explode() {
m_exploded = true;
static const vector<int> colors = { 31, 32, 33, 34, 35, 36, 37 };
static const vector<char> shapes = { '*', '+', '-', '=', '#' };
static const int num_particles = 50;
for (int i = 0; i < num_particles; i++) {
int color = colors[rand() % colors.size()];
char shape = shapes[rand() % shapes.size()];
int x_offset = rand() % 6 - 2;
int y_offset = rand() % 6 - 2;
int x = m_x + x_offset;
int y = m_y - m_height + y_offset;
if (x >= 0 && x < SCREEN_WIDTH && y >= 0 && y < SCREEN_HEIGHT) {
cout << "\033[" << y << ";" << x << "H\033[" << color << "m" << shape << "\033[0m";
}
}
}
int main() {
srand(time(nullptr));
vector<Firework> fireworks;
while (true) {
if (rand() % 10 == 0) {
int x = rand() % SCREEN_WIDTH;
int y = SCREEN_HEIGHT - 1;
fireworks.emplace_back(x, y);
}
for (auto& firework : fireworks) {
if (!firework.is_exploded()) {
firework.rise();
}
}
fireworks.erase(remove_if(fireworks.begin(), fireworks.end(),
[](const Firework& firework) { return firework.is_exploded(); }), fireworks.end());
Sleep(50);
}
return 0;
}
```
该代码利用了面向对象的编程思想,设计了一个 Firework 类来表示每个烟花。每个烟花具有 x、y 坐标、高度和是否已经绽放的状态。在主循环中,首先根据一定概率生成新的烟花,并将其添加到烟花向量中。然后遍历烟花向量,逐个调用 rise() 方法使其上升,在达到一定高度后调用 explode() 方法绽放烟花。在 explode() 方法中,生成一定数量的颜色、形状随机的粒子,并输出到屏幕上。最后,将已经绽放的烟花从烟花向量中移除。