JavaScript面向对象实现贪吃蛇游戏

 更新时间:2022年04月15日 17:15:14   作者:ljs_coding  
这篇文章主要为大家详细介绍了JavaScript面向对象实现贪吃蛇游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了面向对象的贪吃蛇实现代码,供大家参考,具体内容如下

1 工具对象(Tools.js)

因为要随机生成食物,所以先将生成min-max范围内随机整数的方法提取出来。randomNum属性就是生成的随机数。

function Tools(min,max){
    min = Math.ceil(min);
    max = Math.floor(max);
    this.randomNum=Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值

}

2 食物对象(Food.js)

//为避免命名冲突,使用自调用函数
(function(){
    var foodDivs=[];
  //1 定义食物对象
  function Food(options){
      options=options||{};//封装属性的对象
      this.backgroundColor=options.backgroundColor||'green';
      this.width=options.width||20;
      this.height=options.height||20;
      this.x=options.x||0;
      this.y=options.y||0;
  }
  //2 渲染到map上
  Food.prototype.render=function(map){

      removeFood();
      var div=document.createElement('div');
      this.x=new Tools(0,map.offsetWidth/this.width-1).randomNum;
      this.y=new Tools(0,map.offsetHeight/this.height-1).randomNum;
      div.style.width=this.width+'px';
      div.style.height=this.height+'px';
      div.style.backgroundColor=this.backgroundColor;
      div.style.left=this.x*this.width+'px';
      div.style.top=this.y*this.height+'px';
      div.style.position = 'absolute';
      map.appendChild(div);
      foodDivs.push(div);
  }
  function removeFood(){
    for(var i=foodDivs.length-1;i>=0;i--){
        foodDivs[i].parentNode.removeChild(foodDivs[i]);//先从页面删除
        foodDivs.splice(i,1);//删除指定位置元素  //再从数组实际删除
    }
  }
  window.Food=Food;//暴露Food,外部才能访问
})();

3 蛇对象(Snake.js)

(function(){
    var snakeDivs=[];
    //1 蛇构造函数
    function Snake(options){
        options=options||{};
        this.body=[
            {x:3,y:2,bgc:'red'},
            {x:2,y:2,bgc:'blue'},
            {x:1,y:2,bgc:'blue'}
        ];
        this.width=options.width||20;
        this.height=options.height||20;      
        this.direction=options.direction||'right';      
    }
    //2 渲染到map上
    Snake.prototype.render=function(map){
        removeSnake();
        for(var i=0;i<this.body.length;i++){
            var block=this.body[i];
            var div=document.createElement('div');
            div.style.width=this.width+'px';
            div.style.height=this.height+'px';
            div.style.backgroundColor=block.bgc;
            div.style.left=block.x*this.width+'px';
            div.style.top=block.y*this.height+'px';
            div.style.position = 'absolute';
            map.appendChild(div);
            snakeDivs.push(div);//添加蛇divs
        }
    }
    //3 蛇的移动
    Snake.prototype.move=function(food,map){
        //逻辑上从后往前 先蛇身再蛇头
        //蛇身每一节替换上次的位置
        for(var i=this.body.length-1;i>0;i--){
            this.body[i].x=this.body[i-1].x;
            this.body[i].y=this.body[i-1].y;
        }
        //蛇头移动
        var head=this.body[0];
        switch(this.direction){
              case 'left':
              head.x-=1;
              break;
              case 'up':
              head.y-=1;
              break;
              case 'right':
              head.x+=1;
              break;
              case 'down':
              head.y+=1;
              break;
        }
        if(head.x===food.x&&head.y===food.y){//蛇头与食物重合
            var last=this.body[this.body.length-1];
            this.body.push({
                x:last.x,
                y:last.y,
                bgc:last.bgc
            });  
            food.render(map);//这里就包括移除前面的食物这一操作           
        }        
    }
    function removeSnake(){
       for(var i=snakeDivs.length-1;i>=0;i--){
           snakeDivs[i].parentNode.removeChild(snakeDivs[i]);//先从页面删除
           snakeDivs.splice(i,1);//删除指定位置元素  //再从数组实际删除
       }
    }
    window.Snake=Snake;
})();

4 游戏对象(Game.js)

主要是控制游戏的开始,以及按键对应的行为在游戏中的含义,将蛇和食物这两个对象组织在一起。

 (function(){
var that;
 function Game(){
     this.food=new Food();
     this.snake=new Snake();
     that=this;
 }
 Game.prototype.start=function(map){
    this.snake.render(map);
    this.food.render(map);
    var head=this.snake.body[0];
    var span=document.getElementById('tag');
    var timerId=setInterval(function(){
       that.snake.move(that.food,map);
       that.snake.render(map);

       if((head.x>map.offsetWidth/that.snake.width-2)||head.x<=0){
         clearInterval(timerId);
         span.style.display='block';//提示Game Over
       }
       if((head.y>map.offsetHeight/that.snake.height-2)||head.y<=0){
        clearInterval(timerId);
        span.style.display='block';//提示Game Over
      }
    },150);
  
    console.log(map.offsetWidth/this.snake.width-1);
    bindKey();
}
function bindKey(){
    document.addEventListener('keydown',function(e){
        switch(e.keyCode){//left 37 up 38 right 39 down 40
            case 37:
            that.snake.direction='left';
            break;
            case 38:
            that.snake.direction='up';
            break;
            case 39:
            that.snake.direction='right';
            break;
            case 40:
            that.snake.direction='down';
            break;
        }
    });
}
window.Game=Game;
})()
var Game=new Game();
var map=document.getElementById('map');
Game.start(map);

5 index.html

显示的html页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    #map{
        background-color: lightgray;
        width: 800px;
        height: 500px;
        margin: 0 auto;
        position: relative;
    }
    #tag{
    width: 200px;
    height: 100px;
    background-color: gray;
    position: absolute;
    left:300px;
    top:200px;
    line-height: 100px;
    text-align: center;
    display: none;
    }
    </style>
</head>
<body>
    <div id='map'>
        <span id='tag'>Game Over</span>
    </div>
    <script src="js/Tools.js"></script>
    <script src="js/Food.js"></script>
    <script src="js/Snake.js"></script>
    <script src="js/Game.js"></script>
</body>
</html>

6 运行界面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 过虑特殊字符输入的js代码

    过虑特殊字符输入的js代码

    有时候需要客户端限制一些特殊字符的输入,下面是具体的代码,需要的朋友可以参考下。
    2010-08-08
  • JS冷知识之不起眼但有用的String.raw方法

    JS冷知识之不起眼但有用的String.raw方法

    String.raw是JavaScript中模板字符串的一个标签函数,它的作用是将模板字符串不转义的原始字符串内容返回,接下来通过本文给大家介绍JS冷知识之不起眼但有用的String.raw方法,需要的朋友可以参考下
    2022-06-06
  • 学习drag and drop js实现代码经典之作

    学习drag and drop js实现代码经典之作

    今天读John Resig的Pro Javascript Techniques时候看到他书上给的一个关于drag and drop的例子, 合上书本自己写一个简化版本的。大约20分钟完成, 没有考虑兼容firefox。整个代码封装成一个对象 也是借鉴书中的风格。我觉得很好。
    2009-04-04
  • uniapp使用百度地图的保姆式教学(适合初学者!)

    uniapp使用百度地图的保姆式教学(适合初学者!)

    公司项目中有地图展示和定位功能,所以下面这篇文章主要给大家介绍了关于uniapp使用百度地图的保姆式教学,文中通过图文以及实例代码介绍的非常详细,需要的朋友可以参考下
    2023-03-03
  • javascript removeChild 使用注意事项

    javascript removeChild 使用注意事项

    removeChild的注意事项。大家可以参考下。
    2009-04-04
  • 一文带你了解JavaScript垃圾回收机制

    一文带你了解JavaScript垃圾回收机制

    JS自带一套内存管理引擎,负责创建对象、销毁对象,以及垃圾回收,下面这篇文章主要给大家介绍了关于JavaScript垃圾回收机制的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-11-11
  • 详解JavaScript的垃圾回收机制

    详解JavaScript的垃圾回收机制

    这篇文章主要为大家介绍了JavaScript的垃圾回收机制,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • JS树形菜单组件Bootstrap TreeView使用方法详解

    JS树形菜单组件Bootstrap TreeView使用方法详解

    这篇文章主要为大家详细介绍了js组件Bootstrap TreeView使用方法,本文一部分针对于bootstrap的treeview的实践,另一部分是介绍自己写的树形菜单,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-12-12
  • JS中null和undefined的区别

    JS中null和undefined的区别

    在JavaScript中,null和undefined是两个常见的数据类型,本文就详细的介绍了JS中null和undefined的区别,感兴趣的可以了解一下
    2023-05-05
  • JS控制对象移动效果

    JS控制对象移动效果

    用js实现对象的移动,不错的应用
    2008-09-09

最新评论