<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
}
}
这样行
<div id = 'box'>
.
.
.
.
});
ds.