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 相关文章推荐
浅谈tudou土豆网首页图片延迟加载的效果
Jun 23 Javascript
Extjs4.0设置Ext.data.Store传参的请求方式(默认为GET)
Apr 02 Javascript
js+css实现增加表单可用性之提示文字
Jun 03 Javascript
jquery控制select的text/value值为选中状态
Jun 03 Javascript
js 模式窗口(模式对话框和非模式对话框)的使用介绍
Jul 17 Javascript
jQuery动画效果图片轮播特效
Jan 12 Javascript
如何用JavaScript实现动态修改CSS样式表
May 20 Javascript
JS实现下拉菜单列表与登录注册弹窗效果
Aug 10 Javascript
使用Vue-cli 3.0搭建Vue项目的方法
Jun 07 Javascript
vue项目引入Iconfont图标库的教程图解
Oct 24 Javascript
JavaScript仿京东轮播图效果
Feb 25 Javascript
浅谈TypeScript 索引签名的理解
Oct 16 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和ACCESS写聊天室(二)
2006/10/09 PHP
destoon首页调用求购供应信息的地区名称的方法
2014/08/21 PHP
PHP查找与搜索数组元素方法总结
2015/06/12 PHP
PHP字典树(Trie树)定义与实现方法示例
2017/10/09 PHP
Ecshop 后台添加新功能栏目及管理权限设置教程
2017/11/21 PHP
PHP实现git部署的方法教程
2017/12/19 PHP
使用户点击后退按钮使效三行代码
2007/07/07 Javascript
jQuery AnythingSlider滑动效果插件
2010/02/07 Javascript
javascript实现简单的鼠标拖动效果实例
2015/04/10 Javascript
window.onload与$(document).ready()的区别分析
2015/05/30 Javascript
js实现人才网站职位选择功能的方法
2015/08/14 Javascript
JS+CSS实现的简单折叠展开多级菜单效果
2015/09/12 Javascript
概述jQuery的元素筛选
2016/11/23 Javascript
echarts设置图例颜色和地图底色的方法实例
2018/08/01 Javascript
微信小程序带动画弹窗组件使用方法详解
2018/11/27 Javascript
node(koa2) web应用模块介绍详解
2019/03/29 Javascript
超详细的5个Shell脚本实例分享(值得收藏)
2019/08/15 Javascript
Vue开发中遇到的跨域问题及解决方法
2020/02/11 Javascript
bootstrap-paginator服务器端分页使用方法详解
2020/02/13 Javascript
基于JS实现视频上传显示进度条
2020/05/12 Javascript
Vue按时间段查询数据组件使用详解
2020/08/21 Javascript
前端 javascript 实现文件下载的示例
2020/11/24 Javascript
[02:57]DOTA2亚洲邀请赛小组赛第四日 赛事回顾
2015/02/02 DOTA
python登录豆瓣并发帖的方法
2015/07/08 Python
Python标准库使用OrderedDict类的实例讲解
2019/02/14 Python
几个适合python初学者的简单小程序,看完受益匪浅!(推荐)
2019/04/16 Python
python 机器学习之支持向量机非线性回归SVR模型
2019/06/26 Python
python粘包问题及socket套接字编程详解
2019/06/29 Python
检测tensorflow是否使用gpu进行计算的方式
2020/02/03 Python
Python如何使用turtle库绘制图形
2020/02/26 Python
全球速卖通巴西站点:Aliexpress巴西
2016/08/24 全球购物
PatPat德国:妈妈的每日优惠
2019/10/02 全球购物
汽修专业自荐信
2014/07/07 职场文书
最美护士演讲稿
2014/08/27 职场文书
师德师风自我剖析材料
2014/09/27 职场文书
2016年安全月活动总结
2016/04/06 职场文书