<html> <head> <title>贪吃蛇</title> <style> #box{ //背景 width:900px; height:500px; position:relative; background:yellow; } </style> </head> <body> <div id = 'box'></div> <script> var foods = false //食物是否被吃 var a = document.getElementById('box') function Snake(){ this.bod = [{x:4,y:0},{x:3,y:0},{x:2,y:0},{x:1,y:0}] //身子 this.way = 'right' //方向 this.init = function(){ //初始化身体 for(var i=0;i<this.bod.length;i++){ var s = document.createElement('div') s.style.width = 20 + 'px' s.style.height = 20 + 'px' s.style.position = 'absolute' s.style.background = 'red' s.style.left = this.bod[i].x*20 + 'px' s.style.top = this.bod[i].y*20 + 'px' this.bod[i].f = s a.appendChild(s) } } this.move = function(){ //移动身体 for(var i=this.bod.length-1;i>0;i--){ this.bod[i].x = this.bod[i-1].x this.bod[i].y = this.bod[i-1].y } switch(this.way) { case 'right': this.bod[0].x += 1 break case 'left': this.bod[0].x -= 1 break case 'down': this.bod[0].y += 1 break case 'up': this.bod[0].y -= 1 break } for(var j=0;j<this.bod.length;j++){ //吃掉食物 if(this.bod[j].f != null){ a.removeChild(this.bod[j].f) } } this.init() if( (this.bod[0].x*20) >900 || this.bod[0].x<0 ){ //出界 alert("你出界了") clearInterval(ii); } if( (this.bod[0].y*20)>500 || this.bod[0].y<0){ alert("你出界了") clearInterval(ii); } for(var o=4;o<this.bod.length;o++){ //自己吃自己 if(this.bod[o].f != null){ if(this.bod[0].x==this.bod[o].x&&this.bod[0].y==this.bod[o].y){ clearInterval(ii); alert("大聪明,你怎么能吃自己呢"); } } } } } function food(){ //食物 this.init = function(){ this.x = Math.floor(Math.random()*45)*20 this.y = Math.floor(Math.random()*25)*20 var t = document.createElement('div') this.node = t t.style.width = 20 + 'px' t.style.height = 20 + 'px' t.style.left = this.x + 'px' t.style.top = this.y + 'px' t.style.position = 'absolute'; t.style.background = 'blue'; a.appendChild(t) } this.init() } function c(){ //食物被吃,增加蛇身 if((aa.bod[0].x*20) == ds.x&&(aa.bod[0].y*20) == ds.y){ if(ds.node != null){ a.removeChild(ds.node); aa.bod.push({x:null,y:null,f:null}); ds.init(); } } } var c_s = setInterval('c()',1) var ds = new food() var aa = new Snake() var ii = setInterval('aa.move()',200) document.onkeydown = k function k(e){ //鼠标事件 var e = event || window.event switch(e.keyCode){ case 38: if(aa.way){ aa.way = 'up' } break case 40: if(aa.way){ aa.way = 'down' } break case 37: if(aa.way){ aa.way = 'left' } break case 39: if(aa.way){ aa.way = 'right' } break } } </script> </body> </html>