下面是一个简单的C语言烟花代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define WIDTH 80
#define HEIGHT 20
// 绘制烟花
void drawFirework(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
printf("*");
}
// 清空屏幕
void clearScreen() {
system("cls");
}
int main() {
srand(time(NULL)); // 初始化随机数种子
int fireworks[WIDTH][HEIGHT] = {0}; // 二维数组存储烟花位置信息
while(1) {
clearScreen();
// 随机生成烟花
int x = rand() % WIDTH;
int y = rand() % HEIGHT;
fireworks[x][y] = 1;
// 绘制烟花
for(int i = 0; i < WIDTH; i++) {
for(int j = 0; j < HEIGHT; j++) {
if(fireworks[i][j] == 1) {
drawFirework(i, j);
fireworks[i][j] = 0; // 绘制完成后将烟花位置信息清空
}
}
}
Sleep(100); // 控制烟花绘制速度
}
return 0;
}
进阶版
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#define WIDTH 80
#define HEIGHT 25
typedef struct {
float x;
float y;
float vx;
float vy;
int color;
} Particle;
void setCursorPosition(int x, int y) {
printf("\033[%d;%df", y + 1, x + 1);
fflush(stdout);
}
void clearScreen() {
printf("\033[2J");
setCursorPosition(0, 0);
}
void drawParticle(Particle* particle) {
setCursorPosition((int) particle->x, (int) particle->y);
printf("\033[48;5;%dm \033[0m", particle->color);
}
void updateParticle(Particle* particle, float dt) {
particle->x += particle->vx * dt;
particle->y += particle->vy * dt;
particle->vy += 9.8 * dt;
}
void explode(Particle* particle) {
particle->vx = (rand() % 51 - 25) / 10.0;
particle->vy = (rand() % 51 - 25) / 10.0;
particle->color = rand() % 256;
}
int main() {
srand(time(NULL));
Particle fireworks[100];
clearScreen();
for (int i = 0; i < 100; i++) {
fireworks[i].x = WIDTH / 2;
fireworks[i].y = HEIGHT - 1;
fireworks[i].vx = (rand() % 51 - 25) / 10.0;
fireworks[i].vy = -1 - rand() % 5;
fireworks[i].color = rand() % 256;
}
while (1) {
for (int i = 0; i < 100; i++) {
drawParticle(&fireworks[i]);
updateParticle(&fireworks[i], 0.1);
if (fireworks[i].y > HEIGHT || fireworks[i].x < 0 || fireworks[i].x > WIDTH) {
explode(&fireworks[i]);
fireworks[i].x = WIDTH / 2;
fireworks[i].y = HEIGHT - 1;
}
}
usleep(10000);
}
return 0;
}
这个代码使用了 ANSI 转义序列来实现在终端中绘制烟花效果。通过结构体 Particle
来表示每个粒子的位置、速度和颜色。代码首先清空屏幕,然后创建100个烟花粒子,并给它们一个随机的初始速度。之后,代码在每一帧中更新粒子的位置,并在终端中绘制粒子。当粒子超出屏幕边界时,就会重新放置到屏幕底部并触发爆炸效果(即改变速度和颜色)。
这段代码在 Linux 环境下可以直接编译运行。如果在 Windows 环境下运行,可能需要额外的库或修改一些终端控制的部分。