C++实现动态放烟花

一、前言

C++实现的放烟花程序
用到了EGE图形库,没有的需要自行安装
可调项:背景图和背景音乐、粒子模糊度、亮度以及上升速度的参数。
实现的动态烟花非常好看,可以做给女朋友或者表白用hhh
自己做出来玩玩也挺有意思的

二、代码

fire.h

#pragma once
#ifndef  FIREWORKS_H_
#define FIREWORKS_H_
#define myrand(m) ((float)rand() * m / 36565)
#include <graphics.h>

struct Speed {
	double x, y;
};

struct Pos {
	double x, y;
};

struct Particle
{
	Pos pos;
	Speed speed;
};


#define GROUND 580	//地面位置
class Fireworks//烟花类			
{
private:

	static const int NUM_PARTICLE = 200;
	static const double particleSpeed;
	Particle p[NUM_PARTICLE];

	color_t color;

	int delayTime;		//延迟时间
	int riseTime;		//上升时间
	int bloomTime;		//爆炸时间

	Pos risePos;		//上升阶段位置
	Speed riseSpeed;	//上升速度

public:
	//初始化
	Fireworks();
	void init();
	//更新位置等相关属性
	void update();
	//根据属性值绘画
	void draw(PIMAGE pimg = NULL);
};

#endif // ! FIREWORKS_H_

main.cpp

在这里插入代码片
#include <time.h>
#include <graphics.h>
#include "fire.h"
#define NUM_FIREWORKS 10	//烟花数量
int main()
{
	initgraph(1080, 720, INIT_RENDERMANUAL);
	srand((unsigned)time(NULL));
	//烟花
	Fireworks* fireworks = new Fireworks[NUM_FIREWORKS];
	PIMAGE bgPimg = newimage();
	getimage(bgPimg, "夜晚.jpg");
	//先绘制一下,不然前面有空白期
	putimage(0, 0, bgPimg);
	delay_ms(0);
	//背景音乐
	MUSIC bgMusic;
	bgMusic.OpenFile("MELANCHOLY.mp3");
	bgMusic.SetVolume(1.0f);
	if (bgMusic.IsOpen()) {
		bgMusic.Play(0);
	}
	
	//图像缓存, 因为要加背景图,直接加模糊滤镜会把背景图模糊掉
	//所以另设一个图像缓存来绘制烟花并加模糊滤镜,再绘制到窗口
	PIMAGE cachePimg = newimage(800, 800);
	
	//计时用,主要用来定时检查音乐播放
	int timeCount = 0;

	for (; is_run(); delay_fps(60))
	{
		//隔1秒检查一下,如果播放完了,重新播放
		if ((++timeCount % 60 == 0) && (bgMusic.GetPlayStatus() == MUSIC_MODE_STOP)) {
			bgMusic.Play(0);
		}
		//更新位置
		for (int i = 0; i < NUM_FIREWORKS; i++) {
			fireworks[i].update();
		}
		//绘制背景
		putimage(0, 0, bgPimg);
		//绘制烟花到图像缓存中
		for (int i = 0; i < NUM_FIREWORKS; i++) {
			fireworks[i].draw(cachePimg);
		}

		//模糊滤镜,拖尾效果
		//第二个参数,模糊度,越大越模糊,粒子也就越粗
		//第三个参数,亮度,越大拖尾越长
		//可以试试一下其它参数搭配,例如以下几组:
		//0x03, 0xff
		//0x0b, 0xe0
		//0xff, 0xff
		//imagefilter_blurring(cachePimg, 0x0a, 0xff);
		//imagefilter_blurring(cachePimg, 0x03, 0xff);
		//imagefilter_blurring(cachePimg, 0x0b, 0xe0);
		//imagefilter_blurring(cachePimg, 0xff, 0xff);
		//imagefilter_blurring(cachePimg, 0x01, 0xff);
		imagefilter_blurring(cachePimg, 0x0b, 0xff);
		//缓存绘制到窗口,模式为(最终颜色 = 窗口像素颜色 Or 图像像素颜色), 这样颜色会叠加起来
		putimage(0, 0, cachePimg, SRCPAINT);
	}
	delete[] fireworks;
	delimage(bgPimg);
	delimage(cachePimg);
	bgMusic.Close();
	closegraph();
	return 0;
}

fire.cpp

#include <cmath>
#define SHOW_CONSOLE
#include "fire.h"
const double Fireworks::particleSpeed = 3.0f;
Fireworks::Fireworks()
{
	init();
}
void Fireworks::init()
{
	delayTime = rand() % 300 + 20;
	riseTime = rand() % 80 + 160;
	bloomTime = 160;

	risePos.x = rand() % 450 + 300.0f;
	risePos.y = GROUND;

	riseSpeed.y = myrand(1.0f) - 3.0f;	//上升速度,根据坐标系需要是负的
	riseSpeed.x = myrand(0.4f) - 0.2f;	//可稍微倾斜
	//随机颜色
	color = HSVtoRGB(myrand(360.0f), 1.0f, 1.0f);
	//给每一个粒子设置初始速度
	for (int i = 0; i < NUM_PARTICLE - 1; i += 2)
	{
		//为了球状散开,设初始速度大小相等
		//初始随机速度水平角度和垂直角度,因为看到是平面的,所以求x, y分速度
		double levelAngle = randomf() * 360;
		double verticalAngle = randomf() * 360;
		//速度投影到xOy平面
		double xySpeed = particleSpeed * cos(verticalAngle);

		//求x, y分速度
		p[i].speed.x = xySpeed * cos(levelAngle);
		p[i].speed.y = xySpeed * sin(levelAngle);

		//动量守恒,每对速度反向
		if (i + 1 < NUM_PARTICLE)
		{
			p[i + 1].speed.x = -p[i].speed.x;
			p[i + 1].speed.y = -p[i].speed.y;
		}
	}
}

void Fireworks::draw(PIMAGE pimg)
{
	//未开始
	if (delayTime > 0)
		return;
	//烟花上升阶段
	else if (riseTime > 0)
	 {
		setfillcolor(color, pimg);
		//画四个点,这样大一些
		bar(risePos.x, risePos.y, risePos.x + 2, risePos.y + 2, pimg);
	}
	//烟花绽放阶段
	else 
	{
		setfillcolor(color, pimg);
		for (int i = 0; i < NUM_PARTICLE; i++)
		 {
			bar(p[i].pos.x, p[i].pos.y, p[i].pos.x + 2, p[i].pos.y + 2, pimg);
		}
	}
}

//更新位置等相关属性
void Fireworks::update()
{
	if (delayTime-- > 0)
		return;
	//处于上升阶段,只更新烟花位置
	else if (riseTime > 0) 
	{
		risePos.x += riseSpeed.x;
		risePos.y += riseSpeed.y;

		//重力作用
		riseSpeed.y += 0.005;

		//上升完毕,到达爆炸阶段
		if (--riseTime <= 0) 
		{
			//设粒子初始位置为烟花当前位置
			for (int i = 0; i < NUM_PARTICLE; i++)
			 {
				p[i].pos.x = risePos.x;
				p[i].pos.y = risePos.y;
			}
		}
	}
	//烟花绽放阶段
	else if (bloomTime-- > 0)
	 {
		//粒子散开,更新粒子位置
		for (int i = 0; i < NUM_PARTICLE; i++) 
		{
			p[i].pos.x += p[i].speed.x;
			p[i].pos.y += p[i].speed.y;
			//重力作用
			p[i].speed.y += 0.005;
			//速度减慢
			p[i].speed.x *= 0.982;
			p[i].speed.y *= 0.982;
		}
	}
	else
	 {
		//烟花重新开始
		init();
	}
}

三、实现效果

由于烟花是动态的,截图出来不是很好看,但是做出来动态的烟花其实是很好看的,大家可以去试试
觉得这个烟花程序做的还不错的麻烦大家点个赞收藏下呀,对程序有其他改进想法或者遇到问题的话也可以在评论区里提出来
在这里插入图片描述

  • 46
    点赞
  • 228
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 20
    评论
``` <!DOCTYPE html> <html> <head> <title></title> </head> <style> * { padding: 0; margin: 0; } html, body { height: 100%; padding: 0; margin: 0; background: #000; } canvas { position: absolute; width: 100%; height: 100%; } .aa { position: fixed; left: 50%; bottom: 10px; color: #ccc; } </style> <body> <canvas id="pinkboard"></canvas> <script> /* * Settings */ var settings = { particles: { length: 500, // maximum amount of particles duration: 2, // particle duration in sec velocity: 100, // particle velocity in pixels/sec effect: -0.75, // play with this for a nice effect size: 30 // particle size in pixels } }; /* * RequestAnimationFrame polyfill by Erik M?ller */ (function () { var b = 0; var c = ["ms", "moz", "webkit", "o"]; for (var a = 0; a < c.length && !window.requestAnimationFrame; ++a) { window.requestAnimationFrame = window[c[a] + "RequestAnimationFrame"]; window.cancelAnimationFrame = window[c[a] + "CancelAnimationFrame"] || window[c[a] + "CancelRequestAnimationFrame"]; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function (h, e) { var d = new Date().getTime(); var f = Math.max(0, 16 - (d - b)); var g = window.setTimeout(function () { h(d + f); }, f); b = d + f; return g; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function (d) { clearTimeout(d); }; } })(); /* * Point class */ var Point = (function () { function Point(x, y) { this.x = typeof x !== "undefined" ? x : 0; this.y = typeof y !== "undefined" ? y : 0; } Point.prototype.clone = function () { return new Point(this.x, this.y); }; Point.prototype.length = function (length) { if (typeof length == "undefined") return Math.sqrt(this.x * this.x + this.y * this.y); this.normalize(); this.x *= length; this.y *= length; return this; }; Point.prototype.normalize = function () { var length = this.length(); this.x /= length; this.y /= length; return this; }; return Point; })(); /* * Particle class */ var Particle = (function () { function Particle() { this.position = new Point(); this.velocity = new Point(); this.acceleration = new Point(); this.age = 0; } Particle.prototype.initialize = function (x, y, dx, dy) { this.position.x = x; this.position.y = y; this.velocity.x = dx; this.velocity.y = dy; this.acceleration.x = dx * settings.particles.effect; this.acceleration.y = dy * settings.particles.effect; this.age = 0; }; Particle.prototype.update = function (deltaTime) { this.position.x += this.velocity.x * deltaTime; this.position.y += this.velocity.y * deltaTime; this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; this.age += deltaTime; }; Particle.prototype.draw = function (context, image) { function ease(t) { return --t * t * t + 1; } var size = image.width * ease(this.age / settings.particles.duration); context.globalAlpha = 1 - this.age / settings.particles.duration; context.drawImage( image, this.position.x - size / 2, this.position.y - size / 2, size, size ); }; return Particle; })(); /* * ParticlePool class */ var ParticlePool = (function () { var particles, firstActive = 0, firstFree = 0, duration = settings.particles.duration; function ParticlePool(length) { // create and populate particle pool particles = new Array(length); for (var i = 0; i < particles.length; i++) particles[i] = new Particle(); } ParticlePool.prototype.add = function (x, y, dx, dy) { particles[firstFree].initialize(x, y, dx, dy); // handle circular queue firstFree++; if (firstFree == particles.length) firstFree = 0; if (firstActive == firstFree) firstActive++; if (firstActive == particles.length) firstActive = 0; }; ParticlePool.prototype.update = function (deltaTime) { var i; // update active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].update(deltaTime); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].update(deltaTime); for (i = 0; i < firstFree; i++) particles[i].update(deltaTime); } // remove inactive particles while ( particles[firstActive].age >= duration && firstActive != firstFree ) { firstActive++; if (firstActive == particles.length) firstActive = 0; } }; ParticlePool.prototype.draw = function (context, image) { // draw active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].draw(context, image); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].draw(context, image); for (i = 0; i < firstFree; i++) particles[i].draw(context, image); } }; return ParticlePool; })(); /* * Putting it all together */ (function (canvas) { var context = canvas.getContext("2d"), particles = new ParticlePool(settings.particles.length), particleRate = settings.particles.length / settings.particles.duration, // particles/sec time; // get point on heart with -PI <= t <= PI function pointOnHeart(t) { return new Point( 160 * Math.pow(Math.sin(t), 3), 130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25 ); } // creating the particle image using a dummy canvas var image = (function () { var canvas = document.createElement("canvas"), context = canvas.getContext("2d"); canvas.width = settings.particles.size; canvas.height = settings.particles.size; // helper function to create the path function to(t) { var point = pointOnHeart(t); point.x = settings.particles.size / 2 + (point.x * settings.particles.size) / 350; point.y = settings.particles.size / 2 - (point.y * settings.particles.size) / 350; return point; } // create the path context.beginPath(); var t = -Math.PI; var point = to(t); context.moveTo(point.x, point.y); while (t < Math.PI) { t += 0.01; // baby steps! point = to(t); context.lineTo(point.x, point.y); } context.closePath(); // create the fill context.fillStyle = "#ea80b0"; context.fill(); // create the image var image = new Image(); image.src = canvas.toDataURL(); return image; })(); // render that thing! function render() { // next animation frame requestAnimationFrame(render); // update time var newTime = new Date().getTime() / 1000, deltaTime = newTime - (time || newTime); time = newTime; // clear canvas context.clearRect(0, 0, canvas.width, canvas.height); // create new particles var amount = particleRate * deltaTime; for (var i = 0; i < amount; i++) { var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random()); var dir = pos.clone().length(settings.particles.velocity); particles.add( canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y ); } // update and draw particles particles.update(deltaTime); particles.draw(context, image); } // handle (re-)sizing of the canvas function onResize() { canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; } window.onresize = onResize; // delay rendering bootstrap setTimeout(function () { onResize(); render(); }, 10); })(document.getElementById("pinkboard")); </script> </body> </html> ``` ![示例图片](https://devbit-static.oss-cn-beijing.aliyuncs.com/devbit-static/img/heart.png)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zlb_Rose

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值