21xrx.com
2025-03-28 01:01:13 Friday
文章检索 我的文章 写文章
Dev C++烟花代码分享
2023-07-08 09:16:45 深夜i     21     0
Dev C++ 烟花 代码 分享

Dev C++是一款十分优秀的C++开发环境,它支持多种编译器,并且具有简洁易懂的操作界面和丰富的代码库。今天我们要分享一个在Dev C++上编写的烟花代码。

烟花作为一种节日庆典必不可少的元素,它能够在夜空中绽放出绚烂的光彩,瞬间引起人们的注意。而通过计算机程序模拟烟花绽放的过程,不仅能够呈现出震撼人心的视觉效果,还能够启迪人们对数学、物理等科学知识的理解。

下面是一个Dev C++编写的烟花代码:

#include <graphics.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#define WIDTH 800
#define HEIGHT 600
#define MAX_PARTICLES 10000
#define VELOCITY 3
#define PI 3.14159
struct Particle
  float x;
  float y;
  float vx;
  float vy;
  float life;
;
Particle particles[MAX_PARTICLES];
void init() {
  initwindow(WIDTH, HEIGHT, "Fireworks");
  setbkcolor(BLACK);
  cleardevice();
}
void update(Particle& p) {
  p.x += p.vx;
  p.y += p.vy;
  p.vy += 0.05;
  p.life -= 0.02;
}
void draw(Particle p) {
  int radius = 5;
  setcolor(COLOR(255, 255 * p.life, 255 * p.life));
  setfillstyle(SOLID_FILL, COLOR(255, 255 * p.life, 255 * p.life));
  fillellipse(p.x - radius, p.y - radius, p.x + radius, p.y + radius);
}
void create_firework() {
  Particle firework;
  firework.x = rand() % WIDTH;
  firework.y = HEIGHT;
  firework.vx = ((float)rand() / RAND_MAX) * VELOCITY * 2 - VELOCITY;
  firework.vy = -((float)rand() / RAND_MAX) * VELOCITY * 2;
  firework.life = 1;
  for (int i = 0; i < MAX_PARTICLES; i++) {
    if (particles[i].life == 0) {
      particles[i] = firework;
      break;
    }
  }
}
void explode_firework(int index) {
  for (int i = 0; i < 50; i++) {
    Particle firework_particle;
    firework_particle.x = particles[index].x;
    firework_particle.y = particles[index].y;
    float angle = ((float)rand() / RAND_MAX) * 2 * PI;
    float speed = ((float)rand() / RAND_MAX) * VELOCITY / 2 + VELOCITY / 2;
    firework_particle.vx = speed * cos(angle);
    firework_particle.vy = speed * sin(angle);
    firework_particle.life = 1;
    for (int i = 0; i < MAX_PARTICLES; i++) {
      if (particles[i].life == 0) {
        particles[i] = firework_particle;
        break;
      }
    }
  }
  particles[index].life = 0;
}
void draw_fireworks() {
  for (int i = 0; i < MAX_PARTICLES; i++) {
    if (particles[i].life > 0) {
      draw(particles[i]);
      update(particles[i]);
      if (particles[i].life < 0.6) {
        explode_firework(i);
      }
    }
  }
}
int main() {
  init();
  srand(time(NULL));
  while (1) {
    if (rand() % 5 == 0) {
      create_firework();
    }
    draw_fireworks();
    delay(10);
  }
  getch();
  closegraph();
  return 0;
}

在这段代码中,我们使用了graphics.h库来进行绘图操作,并通过结构体数组来存储每个粒子的位置、速度和寿命等信息。在程序的主循环中,我们不断地生成新的烟花粒子,并更新和绘制所有已存在的粒子。当某个粒子的寿命距离结束时间不足60%时,我们就会将它爆炸成多个新的粒子,来模拟烟花的绽放过程。

如果您想要尝试运行这个程序,需要注意的是,您需要先下载graphics.h库,并将其添加到Dev C++的编译器中。您还需要安装WinBGIm,它是Dev C++中graphics.h库的依赖项,并且您需要在程序编译时正确链接它。

总之,通过这个Dev C++编写的烟花代码,我们不仅能够欣赏到美丽的烟花效果,还能够深入了解烟花的物理性质,进一步探索计算机程序对现实世界的模拟能力。

  
  

评论区

请求出错了