JS实现打砖块游戏
本文实例为大家分享了JS实现打砖块游戏的具体代码,供大家参考,具体内容如下
面向对象思想
#show{ width:200px; height:600px; position:absolute; left:1122px; top:50px; background-color:gray; color:blue; line-height:100px; font-size:larger; align-self:center; } #lose{ position:absolute; top:300px; left:300px; font-size:xx-large; display:none; } li{ position:absolute; list-style-type:none; background-color:#000000; width:90px; height:30px; border:1pxsolidwhite; } #box{ position:absolute; width:920px; height:600px; left:200px; top:50px; border:2pxsolidred; } #board{ position:absolute; top:590px; left:300px; width:200px; height:10px; background-color:black; } #bubble{ position:absolute; top:565px; left:360px; width:25px; height:25px; background-color:#FF0000; border-radius:50%; } window.onload=function(){ function$(id){ returndocument.getElementById(id); } functionrand(min,max){ returnMath.floor(Math.random()*(max-min+1))+min } //打砖块构造函数 functionBlockBreak(){ this.box=$('box');//容器 this.list=document.getElementsByTagName('li');//砖块 this.board=$('board');//挡板 this.ball=$('bubble');//小球 this.fx=3;//横向 this.fy=-3;//纵向 this.leftInit=0;//砖块left初始值 this.topInit=0;//砖块top初始值 } //初始化功能摆放每一个砖块的位置 BlockBreak.prototype.init=function(){ for(vari=0;i =720){ that.board.style.left=720+'px'; } } },50) } vartimes=0; varscore=0; //小球运动 BlockBreak.prototype.move=function(){ vartimer=null; varthat=this; timer=setInterval(function(){ that.ball.style.left=that.ball.offsetLeft+that.fx+'px'; that.ball.style.top=that.ball.offsetTop+that.fy+'px'; //小球四个方向反弹 if(that.ball.offsetTop<=0){ that.fy*=-1; } if(that.ball.offsetLeft<=0){ that.fx*=-1; } if(that.ball.offsetLeft>=(that.box.offsetWidth-that.ball.offsetWidth)){ that.fx*=-1; } if(that.ball.offsetTop>=(that.box.offsetHeight-that.ball.offsetHeight)){ //游戏结束 $('lose').style.display='block'; clearInterval(timer); $('res').innerHTML='游戏结束'+"
"; } //小球挡板碰撞反弹 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+'次'+'
'; } } } //小球砖块反弹 //以一个小球为基准遍历所有砖块,找到满足条件的砖块 for(vari=0;i=that.list[i].offsetLeft){ if(that.ball.offsetLeft<=that.list[i].offsetLeft+that.list[i].offsetWidth){ that.fy*=-1; that.list[i].style.display='none'; score++; $('score').innerHTML=score+'分'+'
'; } } } } },10) } varbb=newBlockBreak(); bb.init(); $('start').onclick=function(){ $('times').innerHTML=0+'次'+'
'; $('score').innerHTML=0+'分'+"
"; $('res').innerHTML="正在游戏"+"
"; bb.keydown(); bb.move(); } }游戏重要信息
当前时间:加载中...
游戏状态:加载中...
挡板打球次数:加载中...
游戏得分:加载中...