用c语言编写一个放烟花程序
时间: 2023-10-22 22:09:31 浏览: 69
以下是一个简单的 C 语言程序,可以在命令行中输出一个烟花效果:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define WIDTH 80
#define HEIGHT 25
void set_color(int color_code) {
printf("\033[%dm", color_code);
}
void clear_screen() {
printf("\033[2J");
}
void move_cursor(int x, int y) {
printf("\033[%d;%dH", y, x);
}
void explode() {
int colors[] = {31, 32, 33, 34, 35, 36, 37};
int x, y, color;
for (int i = 0; i < 50; i++) {
x = rand() % (2 * WIDTH) - WIDTH;
y = rand() % (2 * HEIGHT) - HEIGHT;
color = colors[rand() % 7];
move_cursor(WIDTH + x, HEIGHT + y);
set_color(color);
printf("*");
fflush(stdout);
usleep(100000);
}
}
int main() {
srand(time(NULL));
clear_screen();
printf("Press Enter to start...");
getchar();
while (1) {
explode();
}
return 0;
}
```
该程序使用 ANSI 转义序列来控制终端输出,因此只能在支持 ANSI 转义序列的终端中运行,例如 Linux 终端或 Windows PowerShell。
程序首先定义了几个辅助函数,包括设置文本颜色、清空屏幕、移动光标等操作。然后程序定义了 `explode()` 函数,该函数会在屏幕上随机输出 50 个彩色星号,模拟烟花爆炸的效果。
最后程序在 `main()` 函数中调用 `explode()` 函数以播放烟花效果,并且等待用户按下 Enter 键才开始。用户可以按 Ctrl+C 组合键来中断程序运行。
注意:烟花是危险物品,请勿在现实生活中尝试制作或放烟花。本程序仅用于教学和娱乐用途。