JavaScript实现贪吃蛇

这个 很简单 没有添加 边界判断和首尾相连判断


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
    <script type="text/javascript">
    <!--
	function ab2(){
	  var x=new Array();
	  x[0]=34;
	  x.push(45); //尾端添加
	  x.unshift(99);  //头部添加
	  //x.pop();    //尾部删除
	 // x.shift();	//头部删除
	 x.sort();
	  alert(x);
	}
	//定义对象
	function ab3(){
	     var ob={x:3,y:6};
	     alert(ob.x);
	}
	var sks=new Array();
	//var sk1={x:60,y:90};
	//var sk2={x:80,y:90};
	var sk3={x:100,y:90};
	//sks[2]=sk1;
	//sks[1]=sk2;
	sks[0]=sk3;
	var d=3;//右
	var newHead;//新蛇头
	var ax;var ay;
	function ab(){
	    clear();
	    paint();
	    changeHead();
	    eat();
	}
	//画蛇
	function paint(){
	     for(var i=0;i<sks.length;i++){
	    var sk=document.createElement("<div id='k"+i+"'style='background-color:red;width:20px;height:20px;position:absolute;top:"+sks[i].y+"px;left:"+sks[i].x+"px'></div>");
	    document.body.appendChild(sk);
	    }
	}
	//删除蛇
	function clear(){
	     for(var i=0;i<sks.length;i++){
	       var k=document.getElementById("k"+i);
	       if(k){
	        document.body.removeChild(k);
	       }
	     }
	}
	//创建苹果
	 function createApple(){
	     ax=Math.floor(Math.random()*500);
	     ay=Math.floor(Math.random()*500);
	    var sk=document.createElement("<div id='ap'  style='background-color:#339900;width:20px;height:10px;position:absolute;top:"+ay+"px;left:"+ax+"px'></div>");
	    document.body.appendChild(sk);
	 }
	 //吃掉
	 function eat(){
	    if(newHead.x<ax&&newHead.x>ax-20&&newHead.y<ay&&newHead.y>ay-20){
	       var ap=document.getElementById("ap");
	       document.body.removeChild(ap);
	       sks.unshift(newHead);
	       createApple();
	    }  else{
	     sks.unshift(newHead);
	     sks.pop();
	    }
	 }

	//按键

	function change(){
	  var key=event.keyCode;
	  switch(key){
	    case 37:
	      d=1;
	      break;
	    case 38:
	      d=2;
	      break;
	    case 39:
	      d=3;
	      break;
	    case 40:
	      d=4;
	      break;
	  }
	}
     //新蛇头
     function changeHead(){
         var head=sks[0];
	 var hx=head.x;
	 var hy=head.y;
         switch(d){
	   case 1 :
	     hx=hx-5;
	     break;
	   case 2 :
	     hy=hy-5;
	     break;
	   case 3 :
	     hx=hx+5;
	     break;
	   case 4 :
	     hy=hy+5;
	     break;
	 }
	 newHead={x:hx,y:hy};
     }
	function start(){
	 window.setInterval("ab()",50);
	 createApple();
	}
	document.onkeydown=change;
    //-->
    </script>
 </head>

 <body onload="start()">

 </body>
</html>


你可能感兴趣的:(JavaScript实现贪吃蛇)