javascript编写贪吃蛇游戏
代码很简单,这里就不多BB了,小伙伴们直接看示例吧
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/> <title>无标题文档</title> </head> <body> <style> *{ margin:0; padding:0; } #wrap{ position:relative;width:400px;height:400px; border:1pxsolid#ccc; margin:10pxauto; } .snak,.snakBody{ position:absolute; width:10px;height:10px; background:#666; } .food{ position:absolute;width:10px;height:10px; background:#09F;display:block; } </style> <divid="wrap"> </div> <scriptsrc="http://ftp152341.host180.web522.com/%E6%89%93%E8%9C%9C%E8%9C%82/zepto.js"></script> <script> varSnak,Food;; Food=function(op){//op为zepto对象 varfood=$('<spanclass="food"></span>'); food.css({left:Math.floor(((op[0].clientWidth-10)*Math.random())),top:Math.floor(((op[0].clientHeight-10)*Math.random()))}) op.append(food); }; Snak=function(op){ this.obj=document.createElement('div'); this.obj.className='snak'; this.op=op; }; Snak.prototype.ev=function(){ var_this=this,code; $(window).bind('keydown',function(e){ clearInterval(_this.downTimer); code=e.keyCode; _this.downTimer=setInterval(function(){ varl=_this.obj.offsetLeft,t=_this.obj.offsetTop; switch(code){ case37: l=l-5; break; case38: t=t-5; break; case39: l=l+5; break; case40: t=t+5; break; }; if((l<0)||(t<0)||(l>400)||(t>400)){location.reload()}; _this.obj.style.left=l+'px'; _this.obj.style.top=t+'px'; varsnakB=$('.snakBody'); for(vari=snakB.length-1;i>=0;i--){ if(i==0){ snakB[0].style.left=l+'px'; snakB[0].style.top=t+'px'; }else{ snakB[i].style.left=snakB[i-1].offsetLeft+'px'; snakB[i].style.top=snakB[i-1].offsetTop+'px'; }; }; if(pz(_this.obj,$('.food')[0])){ $('.food').remove(); newFood(wrap); $('<divclass="snakBody"></div>').appendTo(wrap) }; },30); }).bind('keyup',function(e){ }); }; functionpz(obj1,obj2){ varL1=obj1.offsetLeft; varT1=obj1.offsetTop; varR1=L1+obj1.offsetWidth; varB1=T1+obj1.offsetHeight; varL2=obj2.offsetLeft; varT2=obj2.offsetTop; varR2=L2+obj2.offsetWidth; varB2=T2+obj2.offsetHeight; if(L1>=R2||T1>=B2||R1<=L2||B1<=T2){ returnfalse; } returntrue; }; varwrap=$('#wrap'),snak=newSnak(food); varfood=newFood(wrap); snak.ev(); wrap.append($('<divclass="snakBody"></div>'))[0].appendChild(snak.obj); </script> </body> </html>
以上所述就是本文的全部内容了,希望大家能够喜欢。