代码改变世界

简易贪吃蛇

2010-01-30 17:46  BlueDream  阅读(520)  评论(0编辑  收藏  举报

贪吃蛇的几个步骤:

1. 生成网盘表格       运用循环生成表格. 然后将表格的行列赋值到一个多维数组map[[][]]中. 便于操作

2. 生成蛇身以及位置            通过x y值决定蛇头的朝向. 比如蛇头朝右. 那么就map的y不变 在x轴增加蛇身即可body[]

3. 判断是否为蛇身               循环body蛇身 判断存不存在该元素 如果是蛇身 就返回null 然后弹出提示

4. 随机生成食物                  在map的格子里随机生成食物.但要判断是否在蛇身上 如果重合了 就重新随机

5. 判断下一个位置        取得蛇头的位置.然后根据onkeydown来分别控制x y是 +1还是-1

4. 移动蛇身                       通过链表array的push和shift来进行就可以了.

<!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> Snake </title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <base href="http://www.cnblogs.com/">
  <style>
    html,body{background:#0D0A15; color:#aaa; font-size:12px; margin:0; padding:0; overflow:hidden; }
    #snaker{float:left; margin-left:140px;}
    table{border-collapse:collapse; border:3px solid #3F7581;background:#002667; }
    td{width:22px; height:22px; overflow:hidden; font-size:5px; border:1px solid #3F7581; }
    .snake{background:#FF9900; }
    .food{background:url(images/cnblogs_com/bluedream2009/201609/o_lol.gif) no-repeat 1px 1px; }
    #count{color:red; font-size:20px; }
  </style>
 </head>
 <body>
 <div id="snaker">
    您的成绩: <span id="count">0</span>( 空格键开始与暂停 )
    <br/><br/>
    <div id="iWin"></div>
 </div>
 </body>
 <script>
 snake = {
    /*
    生成基础表格,设置方向事件,生成蛇的身体
    */
    init: function(win,x,y){
        this.win=win;this.x=x;this.y=y;
        var w=document.getElementById(win);
        this.setMap(w,x,y); //设置地图
        var $ = document.getElementById('iMap').rows;
        // 将表格行列放入多维数组(很重要的思维)
        for(var i = 0, map = []; i < $.length; i++) {
            map[i] = [];
            for(var j = 0; j < $[i].cells.length; j++) {
                map[i][j] = $[i].cells[j];
            }
        }
        this.map = map;
        document.onkeydown = function(e) {
            with(snake.ini.dir) {
                switch((window.event||e).keyCode) {
                    /* 
                    主要是这里的判断 通过设置x y方向的增减量
                    (比如向左移动 y方向不用变 x一直减少.即向左移动了.但x==1表示蛇头朝右,那么就不允许向左移动了 return)
                    */
                    case 37:    if(x==1)return; y = 0; x= -1; break;     // ← 
                    case 38:    if(y==1)return; y = -1; x = 0; break;     // ↑
                    case 39:    if(x==-1)return; y = 0; x = 1; break;     // →
                    case 40:    if(y==-1)return; y = 1; x = 0; break;     // ↓    
                    case 32: snake.ini.stop = !snake.ini.stop;
                }
            }
        };
        // 生成蛇体 开始移动
        this.setBody();this.move();
    }
    /* 生成地图 */
    ,setMap:function(win,x,y){
        for(var i = 0, html = []; i < y; i++) {
            for(var j = 0, tmp = []; j < x; j++) {
                tmp.push('<td> </td>');
            }
            html.push('<tr>' + tmp.join('') + '</tr>');
        }
        win.innerHTML = '<table cellspacing="1" cellpadding="0" id="iMap">' + html.join('') + '</table>';
    }
    /* 生成蛇的身体 */
    ,setBody:function() {
        var y = parseInt(this.map.length/2), _x = parseInt((this.map[0].length - this.ini.len) / 2);
        this.body = [];
        for(var i = 0; i < this.ini.len; i++) {
            var x = this.map[y][i + _x];
            this.body.push(x);
            x.className = this.ini.css;
        }
    }
    /* 定时移动 */
    ,move:function() {
        this.setFood();
        var o = this.getNext();
        if(o) {
            if(!this.ini.stop) {
                // 如果蛇头的位置和食物重合
                if(this.ini.food == o) {
                    this.ini.food = null;
                    document.getElementById('count').innerHTML = (++this.ini.sum) * 10;
                }else { this.body.shift().className='';} // 如果没有吃到食物 蛇尾就减少一个. 如果吃到食物就不用减少 只需添加食物到蛇头
                this.body.push(o);  // 将食物添加到蛇头
                o.className = this.ini.css;
            }
            document.title = this.ini.stop;
            setTimeout(function() { snake.move();}, snake.ini.speed);
        }else {
            alert('碰撞');
            window.location.reload();
        }
    }
    /* 探测下一个位置 */
    ,getNext:function() {
        var e = this.body[this.body.length - 1], y = e.parentNode.rowIndex, x = e.cellIndex; // 蛇头的位置
        try {
            // 主要通过onkeydown的控制来+ -蛇头的位置
            var n = this.map[y + this.ini.dir.y][x + this.ini.dir.x];
            if(this.isBody(n)) return null;
            return n;
        }catch(e) {return null; } //如果碰撞边界
    }
    /* 放置食物 */
    ,setFood:function() {
        if(this.ini.food != null) return;
        do {/* 寻找非蛇身以外的位置 */
            var y = Math.ceil(Math.random() * (this.map.length - 1));
            var x = Math.ceil(Math.random() * (this.map[0].length - 1));
            var f = this.map[y][x];
        }while(this.isBody(f));
        f.className = this.ini.fcss;
        this.ini.food = f;
    }
    /* 测试是否碰到自身 */
    ,isBody:function(x) {
        for(var i = 0, b = false; i < this.body.length; i++) {
            if(x == this.body[i]) return true;
        }
        return false;
    }
    ,ini: {dir:{x:1, y:0}, speed:180, css:'snake', fcss:'food', len:5, food:null, sum:0, stop:true }
 }

 snake.init('iWin', 20, 20);

 </script>
</html>