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经典小游戏汇总

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

(0)

相关推荐

  • javascript实现贪吃蛇经典游戏

    js面向对象编程之贪吃蛇,供大家参考,具体内容如下 首先:面向对象编程,我们要找到项目中具体的对象,此处为(食物(food),蛇(snake),游戏本身(game))也可不把游戏本身作为对象,逻辑体现出来即可. 接着分析每个对象的具体的属性及方法: 1)food 对象:属性有:位置,大小,颜色:方法有:渲染在页面,随机不同位置生成: 2)snake对象:属性有:位置,大小,总节数(计分方便),颜色:方法有:渲染在页面,移动(移动过程中判断其它). 3)game对象:游戏逻辑的编写: ok 开敲:

  • 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

  • 纯js和css完成贪吃蛇小游戏demo

    本文实例为大家分享了js贪吃蛇小游戏demo,纯js和css完成,供大家参考,具体内容如下 <!doctype html> <html> <meta charset="utf-8"> <head> <style> *{ margin: 0; padding:0; } .content{ position: absolute; width: 500px; height: 500px; background-color: #212

  • 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实现贪吃蛇小游戏(容易理解)

    话不多说,请看代码: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>贪吃蛇</title> <link rel="stylesheet" href="style.css"> <script src="style.js" >

  • JavaScript编写一个贪吃蛇游戏

    写的比较乱,有个逻辑错误:蛇吃了果果后应该是蛇尾加一节,写成了蛇头部增加一节- -. 可用键盘的上下左右键操作: 效果图: 代码如下: <html> <head> <title> 贪吃蛇 </title> <style type="text/css"> body{margin:0;padding:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:n

  • js贪吃蛇网页版游戏特效代码分享(挑战十关)

    js贪吃蛇网页版游戏特效,经测试图片切换过程非常酷,相信大家一定都玩过这个经典小游戏吧,但是它是怎么实现的呐,感兴趣的朋友快来学习学习吧 运行效果图:----------------------查看效果----------------------- 小提示:浏览器中如果不能正常运行,可以尝试切换浏览模式. 为大家分享的js贪吃蛇网页版游戏特效代码如下 <body><title>js贪吃蛇网页版游戏特效</title></body> <script>

  • javascript贪吃蛇完整版(源码)

    javascript贪吃蛇完整版 注释完整,面向对象 复制代码 代码如下: <html><head>    <title>贪吃蛇 Snake v2.4</title><style>    body{        font-size:9pt;    }    table{        border-collapse: collapse;        border:solid #333 1px;    }    td{        heigh

  • 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;

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

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

随机推荐