新春烟花代码 c语言
时间: 2025-01-30 16:08:19 浏览: 44
### C语言新春烟花效果实现代码示例
为了创建一个模拟新春烟花的效果,可以采用C语言配合EasyX图形库完成此任务。该程序不仅实现了基本的烟花发射与爆炸过程,还加入了随机颜色和轨迹变化以增强视觉体验[^1]。
```c
#include <graphics.h>
#include <conio.h>
#include <time.h>
// 定义屏幕尺寸常量
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
void draw_firework(int x, int y, COLORREF color);
void explode_firework(int cx, int cy);
int main() {
srand((unsigned)time(NULL));
initgraph(SCREEN_WIDTH, SCREEN_HEIGHT); // 初始化绘图窗口
while (!kbhit()) { // 当未按下任意键时循环执行
// 随机生成烟花起始坐标
int startX = rand() % (SCREEN_WIDTH / 2) + SCREEN_WIDTH / 4;
int startY = SCREEN_HEIGHT;
// 设置初始速度向量
float velocityY = -7.0f; // 向上移动的速度分量
float gravity = 0.1f; // 加速度(重力)
// 发射阶段
while (startY >= 0 && !kbhit()) {
cleardevice();
// 绘制上升中的烟花
draw_firework(startX, startY, RGB(rand()%256,rand()%256,rand()%256));
delay(30); // 延迟一段时间
// 更新位置并应用加速度
startY += velocityY;
velocityY += gravity;
}
// 爆炸阶段
if (startY <= 0 || kbhit())
explode_firework(startX, 0);
Sleep(1000); // 每次烟花结束后暂停一秒再继续下一个
}
closegraph(); // 关闭绘图窗口
return 0;
}
void draw_firework(int x, int y, COLORREF color){
setlinecolor(color);
solidcircle(x,y,5); // 使用实心圆表示正在飞行的烟花颗粒
}
void explode_firework(int cx, int cy){
const int NUM_PARTICLES = 100;
POINT particles[NUM_PARTICLES];
for(int i=0;i<NUM_PARTICLES;++i){
particles[i].x = cx + ((float)(rand()-RAND_MAX/2)/RAND_MAX)*50;
particles[i].y = cy + ((float)(rand()-RAND_MAX/2)/RAND_MAX)*50;
}
for(int frame=0;frame<30;++frame){ // 控制爆炸持续时间
cleardevice();
for(int i=0;i<NUM_PARTICLES;++i){
setfillcolor(RGB(rand()%256,rand()%256,rand()%256));
fillcircle(particles[i].x,particles[i].y,2+(frame%5)); // 动态调整大小使粒子逐渐扩散开来
}
delay(50); // 调整延迟可改变动画流畅度
}
}
```
上述代码展示了如何运用C语言结合EasyX图形库构建一个简单的新春烟花特效程序。通过定义不同函数分别处理烟花的不同状态——发射、空中运动以及最终的爆破散开,使得整个过程更加模块化易于理解维护。此外,在`explode_firework()`方法内部采用了大量随机因素来增加每次运行时的变化性和趣味性。
阅读全文
相关推荐

















