用c++的类写烟花
时间: 2024-02-12 22:08:34 浏览: 23
好的,下面是一个用 C++ 类写烟花的示例代码:
```c++
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <windows.h>
using namespace std;
class Firework {
private:
int x, y, vx, vy, age, size, color;
public:
Firework(int x, int y, int vx, int vy) {
this->x = x;
this->y = y;
this->vx = vx;
this->vy = vy;
age = 0;
size = 5;
color = rand() % 7 + 9; // 随机颜色
}
void draw() {
if (age == 0) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
cout << "●" << endl; // 初始形态
} else {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
cout << "●" << endl; // 爆炸形态
for (int i = 0; i < 8; i++) {
int px = round(x + sin(i * 3.14 / 4) * age / 2);
int py = round(y + cos(i * 3.14 / 4) * age / 2);
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { short(px), short(py) });
cout << "·"; // 烟花爆炸后的效果
}
}
}
void move() {
age++; // 烟花的年龄增加
x += vx;
y += vy;
vy += 1; // 重力加速度
}
bool isDead() {
return age > size * 2; // 判断烟花是否结束
}
};
int main() {
srand(time(NULL));
Firework f(40, 20, rand() % 10 - 5, rand() % 10 - 10); // 初始位置和速度
while (!f.isDead()) {
f.draw();
f.move();
Sleep(50); // 等待 50ms
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { 0, 0 }); // 光标回到起点
}
return 0;
}
```
这个程序会在控制台中显示一个烟花,烟花会从初始位置开始上升,到达一定高度后爆炸成若干个小点,然后消失。烟花的颜色、大小、速度等参数都是随机生成的,每次运行的效果都不同。