<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>贪吃蛇</title>
<style>
#mydiv{border:5px solid #708090;width:520px;margin:170px;}
table{margin:10px;border-collapse:collapse;border-spacing:0;background-color:#EAEAEA}
td{width:10px;height:10px;border:1px solid black;}
</style><script type="text/javascript" language="javascript">//行和列
var rows=20;//y
var cols=40;//x
var start=0;//状态//创建地图
function map()
{
mydiv = document.getElementById("mydiv");// 获取div
mytable = document.createElement("table");// 创建<table>元素 for(j = 0; j < rows; j++)
{
row = document.createElement("tr");
for(i = 0; i < cols; i++)
{
cell = document.createElement("td");
row.appendChild(cell);
}
mytable.appendChild(row);
}
mydiv.appendChild(mytable);

//创建数组“0”标记为空地
map=new Array();
for(y=0;y<rows;y++)
{
map[y]=new Array();
for(x=0;x<cols;x++)
{
map[y][x]='0';
}
}

//初始化蛇的随机坐标
snake_y=parseInt(Math.random()*rows);
snake_x=parseInt(Math.random()*cols);
//蛇的当前坐标
sx=snake_y;
sy=snake_x;
//标记“s”为蛇的位置
map[sx][sy]='s';


//调用食物方法
food();
snake();
}//创建食物
function food()
{
//初始化食物的随机坐标
food_y=parseInt(Math.random()*rows);
food_x=parseInt(Math.random()*cols);

//判断是否是空地
if(map[food_y][food_x]=='0')
{
//标记“f”为食物的位置
map[food_y][food_x]='f';

//忽略节点间的空文本
x=document.getElementById('mydiv').childNodes;
for(i=0;i<x.length;i++)
{
if(x[i].nodeType==1)
getNode=x[i];
}
//得到列的集合
food_cells=getNode.rows[food_y].cells;
//显示食物颜色
food_cells[food_x].style.background="blue";
}else
{
//否则重新创建
food();
}
}//创建蛇
function snake()
{
//得到列的集合
food_cells=getNode.rows[sx].cells;
//显示食物颜色
food_cells[sy].style.background="red";
//得到列的集合
food_cells=getNode.rows[temp_sx].cells;
//显示食物颜色
food_cells[temp_sy].style.background="";
}//键盘监听
document.onkeydown=keydown;
function keydown()
{
key=event.keyCode;
switch(key)
{
case 37: //左
dir(-1,0);
break;
case 38: //上
dir(0,-1);
break;
case 39: //右
dir(1,0);
break;
case 40: //下
dir(0,1);
break;
}
return false;
}//判断方向
function dir(x,y)
{
gox=x;
goy=y;
if(start==0)
{
start=1;
move();//主移动
}
}//主移动
function move()
{
//保存蛇的当前坐标
temp_sx=sx;
temp_sy=sy;

sx+=goy;
sy+=gox;

//判断边界
if(sy<0||sy==cols||sx<0||sx==rows)
{
mydiv.style.borderColor="red";
move1();
}else
{
snakefront=map[sx][sy];
if(snakefront=='0')//如果蛇前面是空地
move2();
else
{
if(snakefront=='f')
move3();
else
move1();

}
}
}//重新开始
function move1()
{
flag=confirm("GAME OVER,重新开始?");
if(flag)
{
window.location.reload();
}
}//蛇前是空地时
var times=200;
function move2()
{
map[temp_sx][temp_sy]='0';
map[sx][sy]='s';
snake();
setTimeout('move()',times);
}//增加蛇长,删除食物
function move3()
{
map[food_y][food_x]='0';
snake();
food();
setTimeout('move()',times);
}
</script>
</head>
<body onload="map()">
<div id="mydiv">
</div>
</body>
</html>碰到食物的时候,如何增长蛇身啊?
SCRIPT5009: “temp_sx”未定义行101 字符2

解决方案 »

  1.   

    嗯,一年后我估计才有水平帮你解决这个问题Mark
      

  2.   

    我也做了一个比较简单的贪吃蛇,用数组保存蛇,吃到食物就给数组添加一个,用个变量保存方向,左右转改变一下方向就行了,调头就用数组的reverse函数,还比较方便.http://www.cctvjs.net/snake/<!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>贪吃蛇 by freewind</title>
    <style type="text/css">
    html, body{ margin:0px; padding:0px; font-size:12px; font-family:"Courier New";}
    #snake{ width:550px; height:400px; margin:50px auto; overflow:hidden;}
    #game{ float:left; width:402px; height:302px; border:1px solid #004578;}
    #game table{ width:401px; height:301px; border-collapse:collapse; }
    #game table td{ width:9px; height:9px; line-height:9px; font-size:2px; overflow:hidden; border:1px solid #fff;}
    #game .bg{ background:#0a0;}
    #game .food{ background:#c00;}
    #info{ float:right; width:128px; line-height:35px;}
    #info input{ margin-top:10px; margin-bottom:10px;}
    </style>
    <script type="text/javascript">
    var $ = function(id){
    return typeof id == "string" ? document.getElementById(id) : id;
    }
    var Snake = {
    init : function(){
    var self = this;
    $("start").onclick = function(){
    self.start();
    this.blur();
    };
    $("pause").onclick = function(){
    self.pause();
    this.blur();
    };
    document.onkeydown = function(event){ 
    self.control(event) 
    };
    this.maxRow = 30;
    this.maxCol = 40;
    },
    initHtml : function(){
    $("game").innerHTML = "<table cellpadding='0' cellspacing='0' border='0'>" + new Array(31).join("<tr>"+new Array(41).join("<td>&nbsp;</td>")+"</tr>") + "</table>";
    this.table = $("game").getElementsByTagName("table")[0];
    $("score").innerHTML = 0;
    $("pause").value = "暂停";
    },
    start : function(){
    var self = this;
    this.initHtml();
    this.food = [];
    this.dir = 39;
    this.data = [[15,21],[15,20],[15,19],[15,18]];
    this.status = 1;
    this.speed = 200;
    this.score = 0;

    this.stop();
    this.timerID = setInterval(function(){self.timer();}, this.speed);
    this.next();
    this.draw();
    },
    pause : function(){
    var self = this;
    if(this.status == 1){
    this.stop();
    this.status = 2;
    $("pause").value = "继续";
    }else if(this.status == 2){
    this.timerID = setInterval(function(){self.timer();}, this.speed);
    this.status = 1;
    $("pause").value = "暂停";
    }
    },
    stop : function(){
    clearInterval(this.timerID);
    },
    setCss : function(row, col, css){
    this.table.rows[row].cells[col].className = css;
    },
    getCss : function(row, col){
    return this.table.rows[row].cells[col].className;
    },
    timer : function(){
    var d = this.data, self = this;
    var first = [d[0][0], d[0][1]];
    switch(this.dir){
    case 37: //left
    first[1] = first[1] - 1 < 0 ? this.maxCol-1 : first[1] - 1; break;
    case 39: //right
    first[1] = first[1] + 1 >= this.maxCol ? 0 : first[1] + 1;  break;
    case 38: //up
    first[0] = first[0] - 1 < 0 ? this.maxRow-1 : first[0] - 1; break;
    case 40: //down
    first[0] = first[0] + 1 >= this.maxRow ? 0 : first[0] + 1;  break;
    }
    var css = this.getCss(first[0], first[1]);
    if(css == "bg"){
    this.gameOver();
    return;
    }
    if(css == "food"){
    this.next();
    this.score += 100;
    this.speed = this.speed > 50 ? this.speed - 10 : 50;
    clearInterval(this.timerID);
    this.timerID = setInterval(function(){self.timer();}, this.speed);
    $("score").innerHTML = this.score;
    }else{
    var last = d.pop();
    this.setCss(last[0], last[1], "");
    }
    this.setCss(first[0], first[1], "bg");
    d.unshift(first);
    },
    control : function(event){
    var keyCode = event ? event.keyCode : window.event.keyCode;
    if(this.status == 1 && keyCode >= 37 && keyCode <= 40){
    if(Math.abs(keyCode - this.dir) == 2){
    this.data = this.data.reverse();
    }
    this.dir = keyCode;
    }
    },
    next : function(){
    var d = this.data;
    while(true){
    var row = parseInt(Math.random() * this.maxRow),
    col = parseInt(Math.random() * this.maxCol),
    isFound = false;
    for(var i = 0; i < d.length; i++){
    if(d[i][0] == row && d[i][1] == col){
    isFound = true;
    break;
    }
    }
    if(!isFound){
    break;
    }
    }
    this.food = [row, col];
    this.setCss(row, col, "food");
    },
    draw : function(){
    for(var i = 0, d = this.data; i < d.length; i++){
    this.setCss(d[i][0], d[i][1], "bg");;
    }
    },
    gameOver : function(){
    this.stop();
    this.status = 0;
    alert("game over");
    },
    dispose : function(){
    this.stop();
    document.onkeydown = $("start").onclick = $("pause").onclick = null;
    }
    };
    window.onload = function(){
    Snake.init();
    };
    window.onunload = function(){
    Snake.dispose();
    };
    </script>
    </head>
    <body>
    <div id="snake">
         <div id="game"></div>
            <div id="info">
                <div>分数:<span id="score">0</span></div>
                <div><input type="button" value="开始" id="start" /></div>
                <div><input type="button" value="暂停" id="pause" /></div>
            </div>
        </div>
    </body>
    </html>