频道栏目
首页 > 程序开发 > web前端 > JavaScript > 正文
javascript 贪食蛇
2011-10-18 15:41:33           
收藏   我要投稿

我的程序用javascript与Html中的table结合,实现的简单的贪食蛇游戏,游戏的主要特点,可调整蛇移动速度,可调整蛇移动范围,碰壁、咬到身体则“Game Over!”并且有关卡加速功能。游戏并不完善,只是实现了主要的功用,有设计不合理的地方,欢迎您感大家提意见!
       实现方法:由javascript语言中的setInterval方法驱动整个游戏程序,设置“nowDirection”即蛇的当前移动方向为全局变量,由setInterval方法定时获取蛇的移动方向,由document.onkeydown()捕捉当前按键(上、下、左、右)以修改nowDirection,这样就可以用方向按键控制蛇周期时间的定向移动。蛇的行走轨迹实现个人觉的实现的还算比较简单,蛇身的每一节存在数组中,数组中的元素为蛇的坐标,移动的时候数组根据方向在数组头部加一个元素,并且将数组最后一个元素删除,这样table就可以准确的显示蛇的行走轨迹,游戏结束比较容易判断,只需根据方向判断蛇的下一个移动单元的坐标是否超出范围(碰壁),或者下一个移动单元的坐标是否存在于蛇身的数组中(咬到身体)。游戏的关卡设计一蛇身数组的长度计算,不能关卡贮蓄改变全局变量speed并且重新启动setInterval方法即可。
      主要技术点:一、蛇的移动
                      二、蛇的移动轨迹显示
                      三、周期内不能接受两次按键指令
                      四、随机生成蛇的食物
                      (大体写写,其实根本没什么技术含量!)
IE测试环境;
截图
 
源码如下:
<html>
<head>
    <title></title>
    <script language="javascript" type="text/javascript">

        var maxScope = 30;                          
        var interval;
        var nowDirection = 'left';                                
        var speed = 300;                                 
        var cellWeight = 10;
        var snakeBody = new Array();                     
        var foodStation = null;                          
        var freeCell_x = new Array();                    
        var freeCell_y = new Array();                     
        var cornerList = new Array();                   
        var cycleCount = 0;
        function $(x) {
            return document.getElementById(x);
        }
        function init() {
            _table = document.getElementById("table");
            for (var i = 0; i <= maxScope; i++) {
                var row = document.createElement("tr");
                row.id = i;
                for (var j = 0; j <= maxScope; j++) {
                    var cell = document.createElement("td");
                    cell.id = i + "_" + j;
                    cell.width = cellWeight;
                    cell.height = cellWeight;
                    row.appendChild(cell);
                }
                document.getElementById("newbody").appendChild(row);
            }
            initSnake();
            initFood();
            snakeInterval();
        }
        function snakeInterval() {
            interval = window.setInterval('snakeMove();cycleCount=0', speed);
        }
        function initSnake() {
            var x = parseInt(Math.random() * (parseInt(maxScope) - 1) + 1);
            var y = parseInt(Math.random() * (parseInt(maxScope) - 1) + 1);
            var nowHeadStation = x + "_" + y;
            snakeBody.push(nowHeadStation);
            tdState(nowHeadStation);
        }
        function initFood() {
            var allCells = new Array();
            for (var i = 0; i < maxScope + 1; i++) {
                for (var j = 0; j < maxScope + 1; j++) {
                    allCells.push(i + '_' + j);
                }
            }
            var addCellsString = allCells.join(',') + ',';
            for (var i = 0; i < snakeBody.length; i++) {
                _snakeBodyCell = snakeBody[i] + ',';
                addCellsString = addCellsString.replace(_snakeBodyCell, "");
            }
            addCellsString = addCellsString.substr(0, addCellsString.length - 1);
            var _allCells = addCellsString.split(',');
            foodStation = _allCells[parseInt(Math.random() * (_allCells.length - 1) + 0)]
            try {
                foodState(foodStation);
            } catch (e) {
                alert(foodStation);
            }
        }
        function document.onkeydown() {
            cycleCount = cycleCount + 1;
            if (cycleCount < 2) {
                switch (event.keyCode) {
                    case 37:
                        if (nowDirection != 'right') {
                            nowDirection = 'left';
                        }
                        break;
                    case 38:
                        if (nowDirection != 'down') {
                            nowDirection = 'up';
                        }
                        break;
                    case 39:
                        if (nowDirection != 'left') {
                            nowDirection = 'right';
                        }
                        break;
                    case 40:
                        if (nowDirection != 'up') {
                            nowDirection = 'down';
                        }
                        break;
                }
            }
        }
        function coordinate(i) {
            switch (i) {
                case 'x':
                    return $(snakeBody[0]).id.split('_')[0];
                case 'y':
                    return $(snakeBody[0]).id.split('_')[1];
            }
        }
        function snakeMove() {
            foodX = foodStation.split('_')[0];
            foodY = foodStation.split('_')[1];
            var _xy;
            switch (nowDirection) {
                case 'left':
                    _x = coordinate('x');
                    _y = Math.floor(coordinate('y')) - 1;
                    _xy = _y;
                    break;
                case 'right':
                    _x = coordinate('x');
                    _y = Math.floor(coordinate('y')) + 1;
                    _xy = _y;
                    break;
                case 'up':
                    _x = Math.floor(coordinate('x')) - 1;
                    _y = coordinate('y');
                    _xy = _x;
                    break;
                case 'down':
                    _x = Math.floor(coordinate('x')) + 1;
                    _y = coordinate('y');
                    _xy = _x;
                    break;
                default:
                    _x = coordinate('x');
                    _y = Math.floor(coordinate('y')) - 1;
                    _xy = _y;
            }
            if (_xy < 0 || _xy > maxScope) {
                overCoordinate();
            }
            else if (rearEnd(_x, _y)) {
                rearEndState();
            }
            else if (_x == foodX && _y == foodY) {
                snakeBody.unshift(_x + '_' + _y);
                level(snakeBody.length);
                $('score').innerHTML = snakeBody.length * 10;
                tdState(snakeBody[0]);
                initFood();
            }
            else {
                snakeBody.unshift(_x + '_' + _y);
                tdState(snakeBody[0]);
                tdStateBack(snakeBody.pop());
            }
        }
        function rearEnd(x, y) {
            var t = x + '_' + y;
            for (var i = 0; i < snakeBody.length; i++) {
                if (t == snakeBody[i]) {
                    return true;
                }
            }
            return false;
        }
        function rearEndState() {
            window.clearInterval(interval);
            alert('game over')
        }
        function overCoordinate() {
            window.clearInterval(interval);
            alert("game over");
        }
        function tdState(targetTd) {
            $(targetTd).style.background = "red";
        }
        function foodState(targetTd) {
            $(targetTd).style.background = "green";
        }
        function tdStateBack(targetTd) {
            $(targetTd).style.background = "";
        }
        function level(max) {
            switch (max) {
                case 10:
                    levelShow("Second");
                    break;
                case 20:
                    levelShow("Third");
                    break;
                case 30:
                    levelShow("Forth");
                    break;
                case 40:
                    levelShow("Fifth");
                    break;
                case 70:
                    window.clearInterval(interval);
                    alert("NB!"); window.close();
                    break;
            }
        }
        function levelShow(_show){
                    window.clearInterval(interval);
                    alert(_show);
                    speed = speed - 50;
                    snakeInterval();
        }
    </script>
</head>
<body onload="init()">
    <table id="table" align="center" bgcolor="pink">
        <tbody id="newbody">
        </tbody>
    </table>
    <table align="center">
        <tr>
            <td style="font-size: 12px">
                score:<span id="score">0</span>
            </td>
        </tr>
    </table>
</body>
</html>

 作者:杨伟明

点击复制链接 与好友分享!回本站首页
相关TAG标签 javascript 贪食蛇
上一篇:Javascript简单跑马灯
下一篇:jquery的不同写法可能造成浏览器的不兼容问题!
相关文章
图文推荐
文章
推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站