用c++写烟花代码
时间: 2024-01-27 17:03:31 浏览: 37
好的,以下是一个基于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
{
double x;
double y;
double vx;
double vy;
int color;
};
void setCursorPosition(int x, int y)
{
COORD position = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), position);
}
void drawPixel(int x, int y, int color)
{
setCursorPosition(x, y);
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
cout << " ";
}
int getRandom(int min, int max)
{
static bool initialized = false;
if (!initialized)
{
srand(static_cast<unsigned int>(time(nullptr)));
initialized = true;
}
return rand() % (max - min + 1) + min;
}
void createParticles(Particle particles[], int count, double x, double y, int color)
{
for (int i = 0; i < count; i++)
{
double angle = getRandom(0, 360) * 3.14159 / 180.0;
double speed = getRandom(10, 200) / 100.0;
particles[i].x = x;
particles[i].y = y;
particles[i].vx = speed * cos(angle);
particles[i].vy = speed * sin(angle);
particles[i].color = color;
}
}
void updateParticles(Particle particles[], int count, double dt, double gravity, double airResistance)
{
for (int i = 0; i < count; i++)
{
particles[i].vx *= pow(airResistance, dt);
particles[i].vy = particles[i].vy * pow(airResistance, dt) + gravity * dt;
particles[i].x += particles[i].vx * dt;
particles[i].y += particles[i].vy * dt;
}
}
void drawParticles(Particle particles[], int count)
{
for (int i = 0; i < count; i++)
{
int x = static_cast<int>(particles[i].x);
int y = static_cast<int>(particles[i].y);
if (x >= 0 && x < SCREEN_WIDTH && y >= 0 && y < SCREEN_HEIGHT)
{
drawPixel(x, y, particles[i].color);
}
}
}
int main()
{
srand(static_cast<unsigned int>(time(nullptr)));
Particle particles[1000];
double dt = 0.1;
double gravity = 9.8;
double airResistance = 0.99;
int count = 0;
while (true)
{
if (count > 0)
{
updateParticles(particles, count, dt, gravity, airResistance);
drawParticles(particles, count);
}
if (getRandom(0, 100) == 0)
{
double x = getRandom(0, SCREEN_WIDTH - 1);
double y = SCREEN_HEIGHT - 1;
int color = getRandom(8, 15);
createParticles(particles, 50, x, y, color);
count += 50;
}
Sleep(10);
}
return 0;
}
```
这个示例使用了粒子系统来模拟烟花的效果,每次随机在屏幕上某个位置生成一些粒子,然后让它们以某个速度随机移动,并且受到重力和空气阻力的影响。粒子会在屏幕上留下一条轨迹,这样就形成了烟花的效果。