javascript贪吃蛇完整版(源码)

javascript贪吃蛇完整版 注释完整,面向对象


代码如下:

<html>
<head>
    <title>贪吃蛇 Snake v2.4</title>
<style>
    body{
        font-size:9pt;
    }
    table{
        border-collapse: collapse;
        border:solid #333 1px;
    }
    td{
        height: 10px;
        width: 10px;
        font-size: 0px;
    }
    .filled{
        background-color:blue;
    }
</style>
</head>
<script>
    function $(id){return document.getElementById(id);}
/**************************************************************
* javascript贪吃蛇 v2.4 <br />
* v2.4修正了蛇身颜色可以随着蛇前进而移动
**************************************************************/
    //贪吃蛇类
    var Snake = {
        tbl: null,
        /**
        * body: 蛇身,数组放蛇的每一节,
        * 数据结构{x:x0, y:y0, color:color0},
        * x,y表示坐标,color表示颜色
        **/
        body: [],
        //当前移动的方向,取值0,1,2,3, 分别表示向上,右,下,左, 按键盘方向键可以改变它
        direction: 0,
        //定时器
        timer: null,
        //速度
        speed: 250,
        //是否已经暂停
        paused: true,
        //行数
        rowCount: 30,
        //列数
        colCount: 30,
        //初始化
        init: function(){
            var colors = ['red','orange','yellow','green','blue','purple','#ccc'];
            this.tbl = $("main");
            var x = 0;
            var y = 0;
            var colorIndex = 0;
            //产生初始移动方向
            this.direction = Math.floor(Math.random()*4);
            //构造table
            for(var row=0;row<this.rowCount;row++){
                var tr=this.tbl.insertRow(-1);
                for(var col=0;col<this.colCount;col++) {
                    var td=tr.insertCell(-1);
                }
            }
            //产生20个松散节点
            for(var i=0; i<10; i++){
                x = Math.floor(Math.random()*this.colCount);
                y = Math.floor(Math.random()*this.rowCount);
                colorIndex = Math.floor(Math.random()*7);
                if(!this.isCellFilled(x,y)){
                    this.tbl.rows[y].cells[x].style.backgroundColor = colors[colorIndex];
                }
            }
            //产生蛇头
            while(true){
                x = Math.floor(Math.random()*this.colCount);
                y = Math.floor(Math.random()*this.rowCount);
                if(!this.isCellFilled(x,y)){
                    this.tbl.rows[y].cells[x].style.backgroundColor = "black";
                    this.body.push({x:x,y:y,color:'black'});
                    break;
                }
            }
            this.paused = true;
            //添加键盘事件
            document.onkeydown= function(e){
                if (!e)e=window.event;
                switch(e.keyCode | e.which | e.charCode){
                  case 13: {
                    if(Snake.paused){
                      Snake.move();
                      Snake.paused = false;
                    }
                    else{
                       //如果没有暂停,则停止移动
                      Snake.pause();
                      Snake.paused = true;
                    }
                    break;
                  }
                    case 37:{//left
                        //阻止蛇倒退走
                        if(Snake.direction==1){
                            break;
                        }
                        Snake.direction = 3;
                        break;
                    }
                    case 38:{//up
                       //快捷键在这里起作用
                      if(event.ctrlKey){
                         Snake.speedUp(-20);
                        break;
                      }
                        if(Snake.direction==2){//阻止蛇倒退走
                            break;
                        }
                        Snake.direction = 0;
                        break;
                    }
                    case 39:{//right
                        if(Snake.direction==3){//阻止蛇倒退走
                            break;
                        }
                        Snake.direction = 1;
                        break;
                    }
                    case 40:{//down
                      if(event.ctrlKey){
                         Snake.speedUp(20);
                        break;
                      }
                        if(Snake.direction==0){//阻止蛇倒退走
                            break;
                        }
                        Snake.direction = 2;
                        break;
                    }
                }
            }
        },
        //移动
        move: function(){
            this.timer = setInterval(function(){
                Snake.erase();
                Snake.moveOneStep();
                Snake.paint();
            }, this.speed);
        },
        //移动一节身体
        moveOneStep: function(){
            if(this.checkNextStep()==-1){
                clearInterval(this.timer);
                alert("Game over!/nPress Restart to continue.");
                return;
            }
            if(this.checkNextStep()==1){
                var _point = this.getNextPos();
                var _x = _point.x;
                var _y = _point.y;
                var _color = this.getColor(_x,_y);
                this.body.unshift({x:_x,y:_y,color:_color});
                //因为吃了一个食物,所以再产生一个食物
                this.generateDood();
                return;
            }
            //window.status = this.toString();
            var point = this.getNextPos();
            //保留第一节的颜色
            var color = this.body[0].color;
            //颜色向前移动
            for(var i=0; i<this.body.length-1; i++){
              this.body[i].color = this.body[i+1].color;
            }
            //蛇尾减一节, 蛇尾加一节,呈现蛇前进的效果
            this.body.pop();
            this.body.unshift({x:point.x,y:point.y,color:color});
            //window.status = this.toString();
        },
        //探寻下一步将走到什么地方
        pause: function(){
          clearInterval(Snake.timer);
          this.paint();
        },
        getNextPos: function(){
            var x = this.body[0].x;
            var y = this.body[0].y;
            var color = this.body[0].color;
            //向上
            if(this.direction==0){
                y--;
            }
            //向右
            else if(this.direction==1){
                x++;
            }
            //向下
            else if(this.direction==2){
                y++;
            }
            //向左
            else{
                x--;
            }
            //返回一个坐标
            return {x:x,y:y};
        },
        //检查将要移动到的下一步是什么
        checkNextStep: function(){
            var point = this.getNextPos();
            var x = point.x;
            var y = point.y;
            if(x<0||x>=this.colCount||y<0||y>=this.rowCount){
                return -1;//触边界,游戏结束
            }
            for(var i=0; i<this.body.length; i++){
                if(this.body[i].x==x&&this.body[i].y==y){
                    return -1;//碰到自己的身体,游戏结束
                }
            }
            if(this.isCellFilled(x,y)){
                return 1;//有东西
            }
            return 0;//空地
        },
        //擦除蛇身
        erase: function(){
            for(var i=0; i<this.body.length; i++){
                this.eraseDot(this.body[i].x, this.body[i].y);
            }
        },
        //绘制蛇身
        paint: function(){
            for(var i=0; i<this.body.length; i++){
                this.paintDot(this.body[i].x, this.body[i].y,this.body[i].color);
            }
        },
        //擦除一节
        eraseDot: function(x,y){
            this.tbl.rows[y].cells[x].style.backgroundColor = "";
        },
        paintDot: function(x,y,color){
            this.tbl.rows[y].cells[x].style.backgroundColor = color;
        },
        //得到一个坐标上的颜色
        getColor: function(x,y){
            return this.tbl.rows[y].cells[x].style.backgroundColor;
        },
        //用于调试
        toString: function(){
            var str = "";
            for(var i=0; i<this.body.length; i++){
                str += "x:" + this.body[i].x + " y:" + this.body[i].y + " color:" + this.body[i].color + " - ";
            }
            return str;
        },
        //检查一个坐标点有没有被填充
        isCellFilled: function(x,y){
            if(this.tbl.rows[y].cells[x].style.backgroundColor == ""){
                return false;
            }
            return true;
        },
        //重新开始
        restart: function(){
            if(this.timer){
                clearInterval(this.timer);
            }
            for(var i=0; i<this.rowCount;i++){
              this.tbl.deleteRow(0);
            }
            this.body = [];
            this.init();
            this.speed = 250;
        },
        //加速
        speedUp: function(time){
          if(!this.paused){
            if(this.speed+time<10||this.speed+time>2000){
              return;
            }
            this.speed +=time;
            this.pause();
            this.move();
          }
        },
        //产生食物。
        generateDood: function(){
          var colors = ['red','orange','yellow','green','blue','purple','#ccc'];
        var x = Math.floor(Math.random()*this.colCount);
            var y = Math.floor(Math.random()*this.rowCount);
            var colorIndex = Math.floor(Math.random()*7);
            if(!this.isCellFilled(x,y)){
                this.tbl.rows[y].cells[x].style.backgroundColor = colors[colorIndex];
            }
        }
    };
</script>
<body onload="Snake.init();">
/*************************************************************<br />
* javascript贪吃蛇 v2.4<br />
**************************************************************/<br />
<table id="main" border="1" cellspacing="0" cellpadding="0"></table>
<input type="button" id="btn" value="开始/暂停" />点左边按钮或按Enter开始/暂停游戏<br />
<input type="button" id="reset" value="重新开始" /><br />
<input type="button" id="upSpeed" value="加速" />点左边按钮或按Ctrl + ↑加速<br />
<input type="button" id="downSpeed" value="减速" />点左边按钮或按Ctrl + ↓减速
<script>
  $('btn').onclick = function(){
    if(Snake.paused){
      Snake.move();
      Snake.paused = false;
    }
    else{
      Snake.pause();
      Snake.paused = true;
    }
  };
  $("reset").onclick = function(){
    Snake.restart();
    this.blur();
  };
  $("upSpeed").onclick = function(){
    Snake.speedUp(-20);
  };
  $("downSpeed").onclick = function(){
    Snake.speedUp(20);
  };
</script>
</body>
</html>

(0)

相关推荐

  • javascript 贪吃蛇实现代码

    在习作的过程中尝试着贪吃蛇游戏用JS实现了.竟然成功了. 思路:使用10px*10px的div层担当"像素",然后使用40*40矩阵160个"像素"构成了游戏的界面. 下面是代码: 复制代码 代码如下: // JavaScript Document alert("键盘的方向键控制方向,空格键暂停.\nLIFE制作\nhttp://blog.csdn.net/anhulife"); // 添加基本的图形块,即160个10 * 10的层组成的二维矩阵

  • javascript 贪吃蛇(详细注释版)

    贪吃蛇 Snake v1.0 body{ } table{ border-collapse: collapse; border:solid #333 1px; } td{ height: 10px; width: 10px; font-size: 0px; } .filled{ background-color:blue; } function $(id){return document.getElementById(id);} /** * javascript贪吃蛇 v1.0 * author

  • JS写的贪吃蛇游戏(个人练习)

    JS贪吃蛇游戏,个人练习之用,放在这备份一下,   复制代码 代码如下: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS贪吃蛇-练习</t

  • js贪吃蛇游戏实现思路和源码

    本文实例为大家分享了js贪吃蛇游戏的相关代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>贪吃蛇小游戏</title> <style> *{margin:0; padding:0;} header { display: block; margin: 0 auto;

  • js编写“贪吃蛇”的小游戏

    贪吃蛇儿时的回忆,今天刚好学习到这了,就刚好做了一个,也是学习了吧,需要掌握的知识: 1.JS函数的熟练掌握, 2.JS数组的应用, 3.JS小部分AJAX的学习 4.JS中的splice.shift等一些函数的应用, 基本上就这些吧,下面提重点部分: 前端的页面,这里可自行布局,我这边提供一个我自己的布局: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org

  • 20行js代码实现的贪吃蛇小游戏

    前言 最近在csdn上看到一位大神用20行代码就写出了一个贪吃蛇的小游戏,感觉被惊艳到了,就试着读了一下这段代码,阅读过程中不断为作者写法的巧妙而叫绝,其中我发现自己对运算符优先级和一些js的技巧不是很清楚,所以看完之后决定把思路分享出来,方便和我一样的小白学习. 我对代码稍稍做了些修改,并添加了一些注释,方便理解. 示例代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="

  • javascript编写贪吃蛇游戏

    代码很简单,这里就不多BB了,小伙伴们直接看示例吧 <!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> <meta

  • 原生js实现的贪吃蛇网页版游戏完整实例

    本文实例讲述了原生js实现的贪吃蛇网页版游戏.分享给大家供大家参考.具体实现方法如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生js写的贪吃蛇网页版游戏</title> </head> <body> </body> <sc

  • javascript实现简单的贪吃蛇游戏

    javascript实现简单的贪吃蛇游戏,功能很简单,代码也很实用,就不多废话了,小伙伴们参考注释吧. <html> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8'> <title>贪吃蛇</title> <script type="text/javascript"> var map; //地图 var snake;

  • javascript 实现的多浏览器支持的贪吃蛇webgame

    写的太累了 ,写了3个小时!大家可以玩玩看 界面不美,尽管批 www.jb51.net 我们 贪吃蛇 //获取新生元素位置 var bucunzai=true;//记录新元素是不是移动 var xinkx; var xinky; //页面载入后k元素定位 function lo(){ var objectp=document.getElementById("k") objectp.style.left="250px" objectp.style.top="

随机推荐