欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用C语言编写炫酷烟花效果的代码

最编程 2024-02-03 11:50:44
...
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define WIDTH 60 #define HEIGHT 20 // 烟花结构体 typedef struct { int x; // 烟花位置的横坐标 int y; // 烟花位置的纵坐标 int vx; // 烟花运动的水平速度 int vy; // 烟花运动的竖直速度 int age; // 烟花的年龄 } Firework; // 随机数生成函数 int random_int(int min, int max) { return rand() % (max - min + 1) + min; } // 烟花绘制函数 void draw_firework(Firework f, char screen[WIDTH][HEIGHT]) { char c; switch (f.age) { case 0: c = 'o'; break; case 1: c = 'O'; break; case 2: c = '.'; break; default: c = ' '; break; } screen[f.x][f.y] = c; } // 屏幕绘制函数 void draw_screen(char screen[WIDTH][HEIGHT]) { for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { printf("%c", screen[x][y]); } printf("\n"); } } // 烟花运动函数 void move_firework(Firework* f) { f->x += f->vx; f->y += f->vy; f->vy += 1; f->age++; } // 烟花爆炸函数 void explode_firework(Firework f, char screen[WIDTH][HEIGHT]) { for (int i = 0; i < 100; i++) { Firework p; p.x = f.x; p.y = f.y; p.vx = random_int(-6, 6); p.vy = random_int(-12, -6); p.age = 0; draw_firework(p, screen); } } int main() { srand(time(NULL)); char screen[WIDTH][HEIGHT] = {0}; while (1) { Firework f; f.x = random_int(10, WIDTH - 10); f.y = HEIGHT - 1; f.vx = random_int(-2, 2); f.vy = -random_int(8, 12); f.age = 0; while (f.age < 3) { draw_screen(screen); move_firework(&f); draw_firework(f, screen); if (f.y >= HEIGHT || f.x < 0 || f.x >= WIDTH) { break; } usleep(50000); system("clear"); } explode_firework(f, screen); draw_screen(screen); usleep(50000); system("clear"); } return 0; }

推荐阅读