龙空技术网

C语言实现烟花程序 #include #inclu...

傲雪熊猫 88

前言:

此刻小伙伴们对“c语言烟花程序”大概比较关切,你们都需要分析一些“c语言烟花程序”的相关内容。那么小编也在网上收集了一些关于“c语言烟花程序””的相关资讯,希望同学们能喜欢,朋友们快快来了解一下吧!

C语言实现烟花程序

 

#include

#include

#include

#include

#define WIDTH 80

#define HEIGHT 20

typedef struct {

int x;

int y;

int color;

} Firework;

Firework fireworks[WIDTH * HEIGHT];

int count = 0;

void init() {

srand(time(NULL));

for (int i = 0; i < WIDTH; i++) {

for (int j = 0; j < HEIGHT; j++) {

Firework f;

f.x = i;

f.y = j;

f.color = rand() % 7 + 1; // 1~7种颜色

fireworks[count++] = f;

}

}

}

void draw() {

system("clear"); // 清屏

for (int i = 0; i < count; i++) {

printf("\033[48;2;%d;%d;%dm ", fireworks[i].color, fireworks[i].color, fireworks[i].color); // 设置光标位置并打印相应颜色

printf(" "); // 在该位置画两个空格作为烟花的形状

printf("\033[0m"); // 恢复默认属性(如颜色等)

}

}

void explode(Firework f) {

int nearby[4][2] = {{-1, -1}, {0, -1}, {1, -1}, {1, 0}}; // 上、右、下、左四个方向,步长为1的偏移量

for (int i = 0; i < 4; i++) {

int nx = f.x + nearby[i][0];

int ny = f.y + nearby[i][1];

if (nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT && fireworks[nx + ny * WIDTH].color == 0) { // 如果该位置合法且颜色为0(即未被访问过)

fireworks[nx + ny * WIDTH].color = fireworks[f.x + f.y * WIDTH].color; // 设置该位置的颜色为当前烟花的颜色

explode(fireworks[nx + ny * WIDTH]); // 递归在该位置爆炸,产生新的烟花效果

}

}

}

void update() {

for (int i = 0; i < count; i++) { // 将所有烟花的颜色设为0,表示需要重新绘制该位置的烟花效果

fireworks[i].color = 0;

}

for (int i = 0; i < count; i++) { // 从上到下,从左到右遍历每一个烟花,让它们爆炸并更新颜色,产生烟花效果

explode(fireworks[i]);

}

}

int main() {

init(); // 初始化所有烟花的位置和颜色

while (1) { // 无限循环,产生连续的烟花效果

draw(); // 在终端上画出当前所有的烟花效果,清屏并刷新屏幕显示效果

update(); // 更新所有烟花的颜色,产生新的烟花效果,并递归地更新相邻位置的烟花颜色(爆炸效果)

usleep(50000); // 延时50ms,控制动画速度,使得烟花效果更加逼真和流畅自然,也可以根据需要调整延时时间来改变动画速度。如果想要更快的动画速度,可以减小这个值;如果想要更慢的动画速度,可以增大这个值。

标签: #c语言烟花程序 #c语言烟花程序是什么 #c语言烟花视频 #c语言实现烟花 #c语言编写烟花