-
最近在苦学JS,突然发现自己对小游戏开发还蛮感兴趣的,继上一篇Flappybird现在又来打砖块啦~~~Flappybird链接
-
敲完代码回头看其实也不难,但还是花了我一上午时间(是我太菜了!!!),话不多说,先上图看看效果吧~
-
这是游戏界面,大框架三部分,打砖块部分(最重要!!!)、游戏信息部分、按钮部分
-
游戏过程界面,开始后小球运动,左右键可以控制挡板移动,小球击打到砖块反弹并且砖块消失,右边记录游戏得分和挡板打球次数
-
这是游戏结束界面,当小球没有击中挡板落地后,Game Over!
下面开始上代码了~~~主要解决打砖块部分:砖块设计、挡板移动、小球碰撞
- 砖块设计:这部分比较好理解,我是在body中写了一大堆“li”,暂时没想到别的办法,首先是砖块的颜色随机变换,主要靠上面这个函数实现;砖块要一个个紧挨着摆开,设置它的left和top;最后换行
//随机数函数
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
//初始化 砖块摆放、颜色、换行
BlockBreak.prototype.init = function() {
for (var i = 0; i < this.list.length; i++) {
this.list[i].style.backgroundColor = "rgb(" + rand(0, 255) + "," + rand(0, 255) + "," + rand(0, 255) + ")";
var x = this.leftInit * this.list[0].offsetWidth;
var y = this.topInit;
this.list[i].style.left = x + "px";
this.list[i].style.top = y + "px";
this.leftInit++;
//换行
if ((i + 1) % 10 == 0) {
this.leftInit = 0;
this.topInit += this.list[0].offsetHeight;
}
}
}
- 挡板运动:两个if语句即可解决挡板运动(37向左,39向右),这里设置每次移动15px,但要保证挡板不能移出去,向左挡板的left不能小于0,向右挡板的右边缘不能出box
if (e.keyCode == 37) {
that.board.style.left = that.board.offsetLeft - 15 + "px";
if (that.board.offsetLeft <= 0) {
that.board.style.left = 0;
}
}
if (e.keyCode == 39) {
that.board.style.left = that.board.offsetLeft + 15 + "px";
if (that.board.offsetLeft >= (that.box.offsetWidth - that.board.offsetWidth)) {
that.board.style.left = that.box.offsetWidth - that.board.offsetWidth + "px";
}
}
3.小球碰撞:这里总共有四个碰撞问题需要解决:和砖块碰、和挡板碰、和边框上+左右两边碰、和边框底边碰(Game Over!)
- 和砖块碰撞:检测小球是否与砖块发生碰撞,如果发生碰撞则砖块display设置为none,得分+1,小球反弹
for (var i = 0; i < that.list.length; i++) {
if (that.ball.offsetTop <= (that.list[i].offsetTop + that.list[i].offsetHeight)) {
if (that.ball.offsetLeft >= that.list[i].offsetLeft) {
if (that.ball.offsetLeft <= (that.list[i].offsetLeft + that.list[i].offsetWidth)) {
that.list[i].style.display = "none";
that.fy *= -1;
score++;
$("score").innerHTML = "得分:" + score;
}
}
}
}
- 和挡板碰撞:和砖块碰撞同理,就不解释啦~
if ((that.ball.offsetTop + that.ball.offsetHeight) >= that.board.offsetTop) {
if ((that.ball.offsetLeft + that.ball.offsetWidth) >= that.board.offsetLeft) {
if (that.ball.offsetLeft <= (that.board.offsetLeft + that.board.offsetWidth)) {
that.fy *= -1;
times++;
$("times").innerHTML = "挡板打球" + times + "次";
}
}
}
- 上+左右边框碰撞:不要忽略上边框的碰撞,一旦砖块没了,小球会和上边框产生碰撞,此时设置反弹就可,左右两边同理
//和上边框碰撞
if (that.ball.offsetTop <= 0) {
that.fy *= -1;
}
//和左右两边框
if (that.ball.offsetLeft <= that.box.offsetLeft || that.ball.offsetLeft >= (that.box.offsetWidth - that.ball.offsetWidth)) {
that.fx *= -1;
}
- 底边框:一旦小球和底边框接触,游戏结束,显示(Game Over),取消定时器
if (that.ball.offsetTop >= (that.box.offsetHeight - that.ball.offsetHeight - 2)) {
$("end").style.display = "block";
clearInterval(timer);
$("res").innerHTML = "游戏结束了!";
}
到这儿主要工作已经做完啦~~~
大家如果有优化和改进的方法可以一块交流一下~