js实现简单的贪吃蛇游戏


Posted in Javascript onApril 23, 2020

本文实例为大家分享了js实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

运行截图:

js实现简单的贪吃蛇游戏

源码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>贪吃蛇小游戏</title>
 
  <style>
    body {
      margin:0px;
      padding:0px;
 
    }
 
    #main {
      margin:100px;
    }
 
    .btn {
      width:100px;
      height:40px;
    }
 
    .gtitle {
      font-size:25px;
      font-weight: bold;
 
    }
 
    #gnum {
      color:red;
    }
  </style>
</head>
 
<body>
 
<div id="main">
  <h1>贪吃蛇</h1>
  <input class="btn" type="button" value="开始游戏" id="begin" />
  <input class="btn" type="button" value="暂停游戏" id="pause" />
  <span class="gtitle">第 <span id="gnum">1</span> 关</span>
 
  <script>
    var main = document.getElementById('main');
    var showcanvas = true; //是否开启画布格子
    /**
     * 地图对象的构造方法
     * @param atom 原子大小宽和高是一样的 10
     * @param xnum 横向原子的数量
     * @param ynum 纵向原子的数量
     * @constructor
     */
    function Map(atom, xnum, ynum){
      this.atom = atom; // 20x20
      this.xnum = xnum; //
      this.ynum = ynum;
 
      this.canvas = null;
 
      //创建画布的方法
      this.create = function(){
        this.canvas = document.createElement('div');
        this.canvas.style.cssText="position:relative;top:40px;border:1px solid darkred; background:#FAFAFA";
        this.canvas.style.width = this.atom * this.xnum + 'px'; //画布的宽
        this.canvas.style.height = this.atom * this.ynum + 'px'; //画布的高
        main.appendChild(this.canvas);
 
        if(showcanvas) {
          for(var y=0; y<ynum; y++) {
            for (var x = 0; x < xnum; x++) {
              var a = document.createElement('div');
              a.style.cssText = "border:1px solid yellow";
              a.style.width = this.atom + 'px';
              a.style.height = this.atom + 'px';
              a.style.backgroundColor = "LightSkyBlue";
              this.canvas.appendChild(a);
              a.style.position = 'absolute';
              a.style.left = x * this.atom + 'px';
              a.style.top = y*this.atom+'px';
            }
          }
        }
 
      }
 
    }
 
    /**
     * 创建食物的构造方法
     * @param map 地图对象
     * @constructor
     */
    function Food(map){
      this.width = map.atom;
      this.height = map.atom;
      this.bgcolor= "rgb("+Math.floor(Math.random()*200)+", "+Math.floor(Math.random()*200)+", " + Math.floor(Math.random() * 200) +")";
      this.x = Math.floor(Math.random()*map.xnum);
      this.y = Math.floor(Math.random()*map.ynum);
      this.flag = document.createElement('div');
      this.flag.style.width = this.width + 'px';
      this.flag.style.height = this.height + 'px';
      this.flag.style.backgroundColor = this.bgcolor;
      // this.flag.style.borderRadius = '50%';
      this.flag.style.position = 'absolute';
      this.flag.style.left = this.x * this.width +'px';
      this.flag.style.top = this.y * this.height + 'px';
 
      map.canvas.appendChild(this.flag);
    }
    function Snake(map) {
      //设置宽,高
      this.width=map.atom;
      this.height = map.atom;
      //默认走的方向
      this.direction = 'right';
 
      this.body = [
        {x:2, y:0}, //蛇头, 第一点 0
        {x:1, y:0}, //蛇脖子, 第二点 1
        {x:0, y:0} //蛇尾, 第三点  2
        //{x:null, y:null, flag:null} 3
      ];
      //显示蛇
      this.display = function(){
        for(var i=0; i<this.body.length; i++){
          if(this.body[i].x !=null) { //当吃到食物时, x==null, 不能新建, 不然会在0,0处理新建一个
            var s = document.createElement('div');
            // 将节点保存到一个状态变量中, 以便以后删除使用
            this.body[i].flag = s;
 
            //设置蛇的样式
            s.style.width = this.width + 'px';
            s.style.height = this.height + 'px';
            s.style.backgroundColor="rgb("+Math.floor(Math.random()*200)+", "+Math.floor(Math.random()*200)+", " + Math.floor(Math.random() * 200) +")";
            //s.style.borderRadius = '50%';
            //设置位置
            s.style.position = 'absolute';
            s.style.left = this.body[i].x * this.width + 'px';
            s.style.top = this.body[i].y * this.height + 'px';
            //添加到地图中
            map.canvas.appendChild(s);
          }
 
        }
      }
      //让蛇运动起来
      this.run = function() {
 
        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;
        }
        //默认是right left up down
        // 根据方向处理蛇头
        switch(this.direction) {
           case "left": this.body[0].x -=1; break;
           case "right": this.body[0].x +=1;break;
           case "up": this.body[0].y -=1; break;
           case "down": this.body[0].y +=1; break;
        }
 
        //判断蛇头吃到食物, xy和食物的XY重合
        if(this.body[0].x ==food.x && this.body[0].y == food.y ){
          //蛇加一节, 根据最后节点定
          this.body.push({x:null, y:null, flag:null});
 
          //判读一下设置级别
          if(this.body.length > l.slength) {
            l.set();
          }
 
          map.canvas.removeChild(food.flag);
          food = new Food(map);
 
        }
        //判断是否出界, 蛇头
        if(this.body[0].x <0 || this.body[0].x > map.xnum-1 || this.body[0].y <0 || this.body[0].y > map.ynum -1) {
          clearInterval(timer); //清除定时器
 
          alert("怎么这么不小心撞墙了呢,摸摸头");
 
          //重新开始游戏
          restart(map, this)
 
          return false;
        }
 
        //判读是否和自己重合
        for(var i=4; i<this.body.length; i++){
          if(this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {
            clearInterval(timer); //清除定时器
 
            alert("呀,怎么喜欢咬自己的肉肉");
 
            //重新开始游戏
            restart(map, this)
 
            return false;
          }
 
        }        
 
        for(var i=0; i<this.body.length; i++){
          if(this.body[i].flag != null) { //当吃到食物, flag是等null, 且不能删除
            map.canvas.removeChild(this.body[i].flag)
          }
        }
 
        this.display();
      }
 
    }
    //重新开始游戏
    function restart(map, snake) {
      for(var i=0; i<snake.body.length; i++) {
        map.canvas.removeChild(snake.body[i].flag);
      }
 
      snake.body = [
        {x:2, y:0}, //蛇头, 第一点 0
        {x:1, y:0}, //蛇脖子, 第二点 1
        {x:0, y:0} //蛇尾, 第三点  2
 
      ];
      snake.direction = 'right';
      snake.display();
      map.canvas.removeChild(food.flag);
      food = new Food(map);
 
    }
    //设置级别对象
    function Level() {
      this.num = 1; //第几级别
      this.speed= 300; //毫秒, 每升一关, 数量减少20, 速度就加快了
      this.slength = 8; //每个关的长度判断
 
      this.set = function() {
        this.num++;
        if(this.speed <= 50) {
          this.speed = 50;
        }else{
          this.speed -=50;
        }
        this.slength += 10; //这个可以自己定义
        this.display();
        start(); //重新开始, 速度加快
      }
 
      this.display = function() {
        document.getElementById('gnum').innerHTML = this.num;
      }
    }
    var l = new Level();
    l.display();
 
    //创建地图对象
    var map = new Map(20, 40, 20);
    map.create(); //显示画布
 
    //构造食物对象
    var food = new Food(map);
 
    //构造蛇对象
    var snake = new Snake(map);
    snake.display();
 
    // 组body加键盘事件, 上下左右
    window.onkeydown = function(e){
      var event = e || window.event;
 
      // console.log(event.keyCode);
 
      switch(event.keyCode) {
        case 38:
          if(snake.direction != "down") {
            snake.direction = "up";
          }
          break;
        case 40:
          if(snake.direction != "up") {
            snake.direction = "down";
          }
          break;
        case 37:
          if(snake.direction != "right") {
            snake.direction = "left";
          }
          break;
        case 39:
          if(snake.direction != "left") {
            snake.direction = "right";
          }
          break;
      }
    }
 
    var timer; //变量可以提升
 
    function start() {
      clearInterval(timer);
      timer = setInterval(function(){
        snake.run();
      },l.speed);
    }
 
    document.getElementById('begin').onclick=function(){
      start();
    }
 
    document.getElementById('pause').onclick=function() {
      clearInterval(timer);
    }
  </script>
</div>
 
</body>
</html>

小编还为大家准备了精彩的专题:javascript经典小游戏汇总

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

Javascript 相关文章推荐
javascript 命名空间以提高代码重用性
Nov 13 Javascript
javascript抽象工厂模式详细说明
Dec 16 Javascript
js实现数字每三位加逗号的方法
Feb 05 Javascript
JavaScript实现自动生成网页元素功能(按钮、文本等)
Nov 21 Javascript
浅析Javascript中bind()方法的使用与实现
May 30 Javascript
浅谈js中对象的使用
Aug 11 Javascript
在JS中a标签加入单击事件屏蔽href跳转页面
Dec 16 Javascript
React-router 4 按需加载的实现方式及原理详解
May 25 Javascript
vue Render中slots的使用的实例代码
Jul 19 Javascript
微信小程序中this.data与this.setData的区别详解
Sep 17 Javascript
解决Vue使用swiper动态加载数据,动态轮播数据显示白屏的问题
Sep 27 Javascript
详解微信小程序的不同函数调用的几种方法
May 08 Javascript
Vue Cli3 打包配置并自动忽略console.log语句的方法
Apr 23 #Javascript
vue项目打包之开发环境和部署环境的实现
Apr 23 #Javascript
javascript设计模式 ? 模板方法模式原理与用法实例分析
Apr 23 #Javascript
谈谈我在vue-cli3中用预渲染遇到的坑
Apr 22 #Javascript
如何修改Vue打包后文件的接口地址配置的方法
Apr 22 #Javascript
nuxt+axios实现打包后动态修改请求地址的方法
Apr 22 #Javascript
JS脚本实现定时到网站上签到/签退功能
Apr 22 #Javascript
You might like
神族 Protoss 剧情介绍
2020/03/14 星际争霸
PHP中的错误处理、异常处理机制分析
2012/05/07 PHP
php和jquery实现地图区域数据统计展示数据示例
2014/02/12 PHP
php读取3389的脚本
2014/05/06 PHP
Laravel5.7框架安装与使用学习笔记图文详解
2019/04/02 PHP
Laravel 集成微信用户登录和绑定的实现
2019/12/27 PHP
验证手机号码的JS方法分享
2013/09/10 Javascript
eclipse如何忽略js文件报错(附图)
2013/10/30 Javascript
javascript实现的弹出层背景置灰-模拟(easyui dialog)
2013/12/27 Javascript
javascript实现倒计时(精确到秒)
2015/06/26 Javascript
JavaScript的jQuery库插件的简要开发指南
2015/08/12 Javascript
使用 Javascript 实现浏览器推送提醒功能的示例
2017/11/03 Javascript
zTree树形菜单交互选项卡效果的实现方法
2017/12/25 Javascript
javascriptvoid(0)含义以及与&quot;#&quot;的区别讲解
2019/01/19 Javascript
JS字符串常用操作方法实例小结
2019/06/24 Javascript
vue 自动化路由实现代码
2019/09/03 Javascript
js实现动态时钟
2020/03/12 Javascript
js面试题之异步问题的深入理解
2020/09/20 Javascript
解决基于 keep-alive 的后台多级路由缓存问题
2020/12/23 Javascript
Python解析命令行读取参数--argparse模块使用方法
2018/01/23 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
2018/02/26 Python
python实现flappy bird小游戏
2018/12/24 Python
Python3使用Matplotlib 绘制精美的数学函数图形
2019/04/11 Python
利用python如何在前程无忧高效投递简历
2019/05/07 Python
python xlwt如何设置单元格的自定义背景颜色
2019/09/03 Python
编写python代码实现简单抽奖器
2020/10/20 Python
python re.match()用法相关示例
2021/01/27 Python
Kappa英国官方在线商店:服装和运动器材
2020/11/22 全球购物
C#软件工程师英语面试题
2015/06/07 面试题
机电一体化求职信
2014/03/10 职场文书
安全生产计划书
2014/05/04 职场文书
公关活动策划方案
2014/05/25 职场文书
公司员工离职证明书
2014/10/04 职场文书
深度学习小工程练习之垃圾分类详解
2021/04/14 Python
Python爬虫之爬取某文库文档数据
2021/04/21 Python
MySQL中B树索引和B+树索引的区别详解
2022/03/03 MySQL