可能网上早就有几个flappy-bird的html5版本啦,到这个时候flappy-bird可能也没有之前那么火了,但是作为一个新手,自己思考,自己动手写一个flappy-bird的demo还是很有成就感的。

flappy-bird的html5版无非是通过canvas来画的,可能网上也有webgl版本的,但是我貌似没见过,如果你发现了,希望告诉我一声,咱们一起讨论讨论。之前在微博上看到有大神用60几行就写出了一个demo,这让我写完之后发现自己的demo有将近200多行的代码,瞬间让我对大神们膜拜的五体投地,当然我的代码也可以精简到几十行,不过那样写出来,不便于维护,对于新人也很难看懂。

html代码我就不写了,大家也都知道,如果你连html代码也需要的话,那你接下来也就没必要看了,还不如直接跳转到w3school.com.cn。

接下来就是重点的js了,至于css吗?你知道的css对于canvas是无效的,那我干嘛还写css呢,这不是浪费生命吗

一开始先是定义bird对象,建议用构造函数的方法,当然你也可以用工厂函数,这没什么关系的

var Bird = function (param) {
				this.x = param.x || 0;
				this.y = param.y || 0;
				this.w = param.w;
				this.h = param.h;
				this.yDir = param.yDir || 1;
				this.img = param.img;

				return this;
			}

创建一个bird的构造函数,传入参数param 并返回this,参数param是相关的配置参数。

接下来是bird的draw属性,这个属性主要是将bird给画出来

Bird.prototype.draw = function () {

				ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height, this.x, this.y, this.w, this.h);

				return this;
			};

ok,就这么简单,只是简单的调用canvas的drawImage方法

接下来就是bird的jump属性,这个属性主要是控制bird的下滑,模仿小鸟的下降

Bird.prototype.jump = function () {
				this.y += this.yDir;
				this.draw();

				return this;
			}

没错,还是这么简单,就是修改y参数,然后调用draw方法,额,其实jump方法和draw方法是可以合并的,不过为了以后的扩展或者,修改方便,我还是选择分开了。当然若是合并了,我的代码又可以少几行了。

上面就完成了bird对象的定义,没错,已经完成了,就一点代码而已。没有太多

接下来是水管对象的定义,不过我人太懒,实在是不想找水管的那个图片,所以我就偷工减料,用了几个盒子来代替水管,原理是一样的,但是视觉效果,你懂的,就比如我身边的一个女性同学说的,程序猿能有什么美感!大家将就着吧

定义盒子对象

var Box = function (x, y) {
				this.x = x || boxOption.x;
				this.y = y || boxOption.y;
				this.w = boxOption.w;
				this.h = boxOption.h;
				this.img = boxOption.img;
				this.visible = true;

				return this;
			};

是不是觉得和bird很像,不过就是多了visible属性,这个属性是控制盒子的看见与否,在游戏中的小鸟通过的的水管之间的空隙就是靠它了,

还是要定义它几个方法,不对,它只有一个方法

Box.prototype.draw = function () {

				// console.log([this.img, this.img.width, this.img.height, this.x, this.y, this.w, this.h]);
				ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height, this.x, this.y,
					this.w, this.h);

			};

有没有觉得这个方法和bird的draw方法一样,没错是一样的,其实我应该让box继承bird对象,这样我的代码有可以少几行了

好了,不谈代码行数的问题了,伤心

接下来是pipe的对象,它不过是box的一个集合

var pipe = function (posX, xDir, maxNum) {
				this.x = posX;
				this.xDir = xDir;
				var boxList = [];
				var box = new Box(0, 0);
				var boxW = box.w,
					boxH = box.h;
				var boxTmp;
				var maxNum = maxNum || Math.ceil(canvas.height / boxW);

				for (var i = 0; i < maxNum; i++) {
					boxTmp = new Box(posX, i * boxH);
					boxList.push(boxTmp);
				}

				this.obj = boxList;
				this.boxW = boxW;
				return this;
			};

this.obj这个属性就是box数组

和前面一样,pipe也有个draw属性

pipe.prototype.draw = function () {
				var box;
				for (var i = 0; i < this.obj.length; i++) {
					box = this.obj[i];
					box.x = this.x;
					if (box.visible) {
						box.draw();
					}
				}
				return this;
			};

就是将this.obj中的所有box来一次遍历输出,当然box的visible属性必须是可见的

下面的这个方法是随机隐藏两个连续的box,以便给可伶的小鸟通过,我们是仁慈的,给了两个box的高度,当然如果你要是想虐人的话,建议你只给一个高度

// 随机隐藏两个连续的箱子
			pipe.prototype.rand = function () {
				for (var i = 0; i < this.obj.length; i++) {
					this.obj[i].visible = true;
				}

				var rand = Math.floor(Math.random() *  5) + 1;
				// console.log(rand);
				this.obj[rand].visible = false;
				this.obj[rand + 1].visible = false;

				return this;
			};

最后一个属性是移动方法,这是让水管进行左右移动的

pipe.prototype.move = function () {
				this.x += this.xDir;

				// console.log(this.x, this.xDir, this.boxW);
				if (this.x < -this.boxW) {
					this.x = canvas.width;
					this.rand();
				}
				this.draw();
				return this;
			};

ok 基本这样ok了,但是我们是不是忘了什么东西啊,想起来了,我们还没有进行碰撞检测呢,如果不进行碰撞检测,那岂不是开挂了,这当然是不行的

// 碰撞函数

			function collision (bird, pipe1) {
				var birdx = bird.x,
					birdy = bird.y,
					birdw = bird.w,
					birdh = bird.h;

				var boxes = pipe1.obj;
				var box1, box2, num;
				for (var i = 0; i < boxes.length - 1; i++) {
					// 找到被隐藏的两个盒子
					if (!boxes[i].visible) {
						box1 = boxes[i];
						box2 = boxes[i + 1];
						break;
					}
				}
				var emptyx = box1.x;
				var emptyy = box1.y;
				var emptyw = box1.w;
				var emptyh = box1.h + box2.h;

				// 检测是否与上半部水管碰撞
				console.log([birdx, birdy, birdw, birdh, emptyx, 0, emptyw, box1.y, boxes[0].y]);
				var collUp = calculate(birdx, birdy, birdw, birdh, emptyx, 0, emptyw, box1.y);
				// 检测是否与下半部水管碰撞
				var collDown = calculate(birdx, birdy, birdw, birdh, emptyx, box2.y + box2.h, emptyw, canvas.height - box2.y - box2.h);
				// console.log(collUp, collDown);
				if (collUp || collDown) {
					// alert('game over');
					console.log('game over 1111');
					console.log(myReq);
					stop();
				}

				if (birdy > canvas.height - birdh) {
					console.log('game over   222');
					console.log(myReq);
					stop();
				}
			}

			// 计算碰撞函数,默认矩形碰撞
			function calculate (x1, y1, w1, h1, x2, y2, w2, h2) {
				var ax = x1 + w1 / 2,
					ay = y1 + h1 / 2,
					bx = x2 + w2 / 2,
					by = y2 + h2 / 2;
				var collX = false, collY = false;

				(Math.abs(bx - ax) < (w1 + w2) / 2) && (collX = true);
				(Math.abs(by - ay) < (h1 + h2) / 2) && (collY = true);

				return collX && collY;
			}

这样就基本ok了,接下来也只是一些,初始化而已,这个直接上代码吧

var count = 0, timeout, myReq = 0, stopped, requestId = 0;
			function render() {
				if (!stopped) {
					ctx.fillStyle = '#ccc';
					ctx.fillRect(0, 0, canvas.width, canvas.height);
					bird.jump();
					pipe1.move();
					// 检测碰撞
					collision(bird, pipe1);
					requestId = window.requestAnimationFrame(render);
					console.log(requestId);
				}
			}

			// 绑定鼠标事件
			document.onclick = function () {
				bird.y -= 25;
			}
			function start() {
	            requestId = window.requestAnimationFrame(render);
	            stopped = false;
				// console.log(requestId);

	        }

	        function stop() {
	            if (requestId) {
	                window.cancelAnimationFrame(requestId);
	            }
	            stopped = true;
	            // console.log(requestId);
	        }

	        start();

效果如下图所示

完整代码请访问我的github

https://github.com/chenkehxx/mytest/blob/master/flappy-bird/flappy-bird.html