javascript贪吃蛇完整版(源码)


Posted in Javascript onDecember 09, 2013

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>
Javascript 相关文章推荐
javascript编程起步(第六课)
Feb 27 Javascript
cloudgamer出品ImageZoom 图片放大效果
Apr 01 Javascript
JS无法捕获滚动条上的mouse up事件的原因猜想
Mar 21 Javascript
javascript相关事件的几个概念
May 21 Javascript
js+html制作简单验证码
Feb 16 Javascript
JS实现图片点击后出现模态框效果
May 03 Javascript
Vue 2.0中生命周期与钩子函数的一些理解
May 09 Javascript
AngularJS实现的简单拖拽功能示例
Jan 02 Javascript
vue.js父子组件通信动态绑定的实例
Sep 28 Javascript
微信小程序实现文字跑马灯
May 26 Javascript
ES6 如何改变JS内置行为的代理与反射
Feb 11 Javascript
微信小程序实现人脸识别登陆的示例代码
Apr 02 Javascript
关于js内存泄露的一个好例子
Dec 09 #Javascript
JS连连看源码完美注释版(推荐)
Dec 09 #Javascript
解析Javascript中难以理解的11个问题
Dec 09 #Javascript
深入理解Javascript作用域与变量提升
Dec 09 #Javascript
Javascript全局变量var与不var的区别深入解析
Dec 09 #Javascript
jquery div拖动效果示例代码
Dec 08 #Javascript
jquery垂直公告滚动实现代码
Dec 08 #Javascript
You might like
PHP 木马攻击防御技巧
2009/06/13 PHP
php download.php实现代码 跳转到下载文件(response.redirect)
2009/08/26 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(十二)
2014/06/25 PHP
自己写的兼容低于PHP 5.5版本的array_column()函数
2014/10/24 PHP
smarty半小时快速上手入门教程
2014/10/27 PHP
详解提高使用Java反射的效率方法
2019/04/29 PHP
js解析与序列化json数据(三)json的解析探讨
2013/02/01 Javascript
在Javascript中 声明时用&quot;var&quot;与不用&quot;var&quot;的区别
2013/04/15 Javascript
Angular 应用技巧总结
2016/09/14 Javascript
基于Phantomjs生成PDF的实现方法
2016/11/07 Javascript
AngularJS动态加载模块和依赖的方法分析
2016/11/08 Javascript
基于React实现表单数据的添加和删除详解
2017/03/14 Javascript
bootstrap fileinput组件整合Springmvc上传图片到本地磁盘
2017/05/11 Javascript
Vue-cli proxyTable 解决开发环境的跨域问题详解
2017/05/18 Javascript
javaScript字符串工具类StringUtils详解
2017/12/08 Javascript
jquery+css3实现熊猫tv导航代码分享
2018/02/12 jQuery
tween.js缓动补间动画算法示例
2018/02/13 Javascript
vue-cli3.0如何使用CDN区分开发、生产、预发布环境
2018/11/22 Javascript
javascript实现支付宝滑块验证码效果
2020/07/24 Javascript
vue使用transition组件动画效果的实例代码
2021/01/28 Vue.js
Python2.x版本中cmp()方法的使用教程
2015/05/14 Python
Python多线程和队列操作实例
2015/06/21 Python
Python中使用插入排序算法的简单分析与代码示例
2016/05/04 Python
Python基础练习之用户登录实现代码分享
2017/11/08 Python
替换python字典中的key值方法
2018/07/06 Python
解决在pycharm中显示额外的 figure 窗口问题
2019/01/15 Python
Python解析json代码实例解析
2019/11/25 Python
Windows下Anaconda和PyCharm的安装与使用详解
2020/04/23 Python
分享30个新鲜的CSS3打造的精美绚丽效果(附演示下载)
2012/12/28 HTML / CSS
生产部岗位职责范文
2014/02/07 职场文书
模范教师事迹材料
2014/02/10 职场文书
《这儿真好》教学反思
2014/02/22 职场文书
2014年乡镇植树节活动方案
2014/02/28 职场文书
2014年教研员工作总结
2014/12/23 职场文书
终止合同协议书范本
2016/03/22 职场文书
kubernetes集群搭建Zabbix监控平台的详细过程
2022/07/07 Servers