用c++代码写个动态烟花
时间: 2023-08-26 14:07:47 浏览: 81
好的,以下是一份c代码,可以实现动态烟花效果:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>
#define PI 3.14159
#define MAX_PARTICLES 50
#define RESOLUTION 50
struct particle {
float xPos;
float yPos;
float xVel;
float yVel;
int r;
int g;
int b;
int lifespan;
int size;
};
typedef struct particle Particle;
void resetParticle(Particle *p, float xPos, float yPos) {
p->xPos = xPos;
p->yPos = yPos;
float angle = (rand() % 360) * PI / 180;
float speed = (rand() % 15) + 5;
p->xVel = cos(angle) * speed;
p->yVel = sin(angle) * speed;
p->r = rand() % 256;
p->g = rand() % 256;
p->b = rand() % 256;
p->lifespan = rand() % 50 + 50;
p->size = rand() % 10 + 5;
}
void explode(Particle *particles, int x, int y) {
for (int i = 0; i < MAX_PARTICLES; i++) {
particles[i].lifespan = 0;
resetParticle(&particles[i], x, y);
}
}
void draw(Particle *particles, HDC hdc) {
for (int i = 0; i < MAX_PARTICLES; i++) {
if (particles[i].lifespan > 0) {
HBRUSH brush = CreateSolidBrush(RGB(particles[i].r, particles[i].g, particles[i].b));
SelectObject(hdc, brush);
Ellipse(hdc, particles[i].xPos - particles[i].size / 2, particles[i].yPos - particles[i].size / 2, particles[i].xPos + particles[i].size / 2, particles[i].yPos + particles[i].size / 2);
DeleteObject(brush);
}
}
}
void update(Particle *particles) {
for (int i = 0; i < MAX_PARTICLES; i++) {
if (particles[i].lifespan > 0) {
particles[i].xPos += particles[i].xVel;
particles[i].yPos += particles[i].yVel;
particles[i].yVel += 0.1;
particles[i].lifespan--;
}
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
Particle particles[MAX_PARTICLES];
int mouseX = 0, mouseY = 0;
HWND hwnd;
MSG msg;
WNDCLASS wc = { 0 };
wc.lpszClassName = "Dynamic Fireworks";
wc.lpfnWndProc = DefWindowProc;
RegisterClass(&wc);
hwnd = CreateWindow(wc.lpszClassName, "Dynamic Fireworks", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, RESOLUTION * 10, RESOLUTION * 10, NULL, NULL, hInstance, NULL);
HDC hdc = GetDC(hwnd);
ShowWindow(hwnd, nCmdShow);
srand(time(NULL));
while (GetMessage(&msg, NULL, 0, 0)) {
if (msg.message == WM_MOUSEMOVE) {
mouseX = LOWORD(msg.lParam);
mouseY = HIWORD(msg.lParam);
}
if (msg.message == WM_LBUTTONDOWN) {
explode(particles, mouseX, mouseY);
}
for (int i = 0; i < RESOLUTION; i++) {
for (int j = 0; j < RESOLUTION; j++) {
int x = i * 10 + 5;
int y = j * 10 + 5;
int distance = sqrt(pow(x - mouseX, 2) + pow(y - mouseY, 2));
if (distance < 50) {
int index = j * RESOLUTION + i;
if (particles[index].lifespan == 0) {
resetParticle(&particles[index], x, y);
}
}
}
}
update(particles);
draw(particles, hdc);
Sleep(16);
InvalidateRect(hwnd, NULL, FALSE);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ReleaseDC(hwnd, hdc);
return msg.wParam;
}
```
通过在窗口中使用一个像素的方格来划分区域,当鼠标移动到一个方格上时,就会在该方格中心生成一个烟花。烟花由多个粒子组成,每个粒子有一个随机生成的初始速度,并且随着时间的推移,逐渐减速并消失。在烟花爆炸的瞬间,会在该位置生成一定数量的粒子,并赋予它们一个随机的速度,从而实现粒子爆炸的效果。