當前位置 主頁 > 服務器問題 > Linux/apache問題 > 最大化 縮小

    原生js實現貪食蛇小游戲的思路詳解

    欄目:Linux/apache問題 時間:2019-11-26 16:26

    先不多說先上圖

    下面是代碼部分(這里你可以根據需要改變蛇頭和身體還有食物的圖片,然后默認的樣式是使用純顏色的如果沒有更改我的背景圖片的話------改這些圖開始是想搞笑一下朋友哈哈哈,請不要在意哈),還有操作鍵是使用 ↑ ↓ ← → )

    <!DOCTYPE html>
    <html>
    <head lang="en">
      <meta charset="UTF-8">
      <title>貪食蛇</title>
      <style>
        .map {
          width: 800px;
          height: 600px;
          background-color: #ccc;
          position: relative;
          left: 50%;
          transform: translate(-50%);
        }
        #dv {
          color: whitesmoke;
          font-weight: 700;
          text-align: center;
          line-height: 50px;
          width: 150px;
          height: 50px;
          position: absolute;
          background-color: orange;
          border-radius: 10px;
          top: 50%;
          left: 50%;
          transform: translate(-50%);
          cursor: pointer;
        }
      </style>
    </head>
    <body>
      <div class="map">
        <div >開始游戲</div>
      </div>
      <script>
        //食物:是一個對象,有寬,有高,有顏色,有橫縱坐標
        //自調用函數
        (function () {
          var element = []; //用來保存每個小方塊食物的
          function Food(x, y, width, height, color) {
            this.x = x || 0;
            this.y = y || 0;
            this.width = width || 20;
            this.height = height || 20;
            this.color = color || "green";
          }
          //為原型添加初始化的方法(作用:在頁面上顯示這個食物)
          //因為食物要在地圖上顯示,所以,需要地圖的這個參數(map--就是頁面上的.class=map的這個div)
          Food.prototype.init = function (map) {
            //先刪除這個小食物
            //外部無法訪問,此函數在自調用函數里面
            remove();
            //創建div
            var div = document.createElement("div");
            //把div加到map里面
            map.appendChild(div);
            //獲取div的樣式
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            //脫離文檔流
            div.style.position = "absolute";
            //橫縱坐標先停止----隨機產生
            this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;
            this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;
            div.style.left = this.x + "px";
            div.style.top = this.y + "px";
            //把div加入element數組中
            element.push(div);
            //改變食物的樣式---改成自己喜歡的東西
            div.style.backgroundImage = "url(" + "../images/shi.png" + ")";
            div.style.backgroundRepeat = "no-repaet";
            div.style.backgroundSize = "cover";
          };
          //私有函數
          function remove() {
            for (var i = 0; i < element.length; i++) {
              var ele = element[i];
              //找到這個子元素的父級元素,然后刪除這個子元素
              ele.parentNode.removeChild(ele);
              //再次把element中的這個子元素刪除
              element.splice(i, 1);
            }
          }
          //把Food暴露給window,外部可以使用
          window.Food = Food;
        }());
        //自調用函數---小蛇
        (function () {
          //存放小蛇的每個身體部分
          var element = [];
          //小蛇的構造函數
          function Snake(width, height, driection) {
            this.width = width || 20;
            this.height = height || 20;
            //小蛇的身體
            this.body = [{
                x: 3,
                y: 2,
                color: "red"
              },
              {
                x: 2,
                y: 2,
                color: "orange"
              },
              {
                x: 1,
                y: 2,
                color: "orange"
              }
            ];
            //方向
            this.driection = driection || "right";
          }
          //為原型添加方法---小蛇初始化的方法
          Snake.prototype.init = function (map) {
            //先刪除之前的小蛇
            remove();
            //循環遍歷創建div
            for (var i = 0; i < this.body.length; i++) {
              //數組中的每個數組元素都是一個對象
              var obj = this.body[i];
              //創建div
              var div = document.createElement("div");
              //把div加入地圖map中
              map.appendChild(div);
              //設置div的樣式
              div.style.position = "absolute";
              div.style.width = this.width + "px";
              div.style.height = this.height + "px";
              //橫縱坐標
              div.style.left = obj.x * this.width + "px";
              div.style.top = obj.y * this.height + "px";
              //背景顏色
              div.style.backgroundColor = obj.color;
              //方向還沒定
              //把div加入到element數組中---目的是為了刪除
              //把div加入數組中
              element.push(div);
              //更改頭部的----變成圖片
              if (i == 0) {
                div.style.backgroundImage = "url(" + "../images/tou_03.png" + ")";
                div.style.backgroundRepeat = "no-repaet";
                div.style.backgroundSize = "cover";
              }
              //更改尾巴的樣式照片
              if (i != 0) {
                div.style.backgroundImage = "url(" + "../images/shi.png" + ")";
                div.style.backgroundRepeat = "no-repaet";
                div.style.backgroundSize = "cover";
              }
            }
          };
          //為原型添加方法---小蛇動起來
          Snake.prototype.move = function (food, map) {
            var i = this.body.length - 1;
            for (; i > 0; i--) {
              this.body[i].x = this.body[i - 1].x;
              this.body[i].y = this.body[i - 1].y;
            }
            //判斷方向---改變小蛇的頭的坐標位置
            switch (this.driection) {
              case "left":
                this.body[0].x -= 1;
                break;
              case "right":
                this.body[0].x += 1;
                break;
              case "top":
                this.body[0].y -= 1;
                break;
              case "bottom":
                this.body[0].y += 1;
                break;
            }
            //判斷有沒有吃到食物
            //小蛇的頭的坐標和食物的坐標一致
            var headX = this.body[0].x * this.width;
            var headY = this.body[0].y * this.height;
            //判斷小蛇的頭和食物坐標是否相同
            if (headX == food.x && headY == food.y) {
              //獲取小蛇的最后的尾巴
              var last = this.body[this.body.length - 1];
              //把最后的蛇尾復制一個,重新的加入到小蛇的body中
              this.body.push({
                x: last.x,
                y: last.y,
                color: last.color
              });
              //把食物刪除,重新初始化食物
              food.init(map);
            }
          };
          //刪除小蛇的私有函數
          function remove() {
            //獲取數組
            var i = element.length - 1;
            for (; i >= 0; i--) {
              var ele = element[i];
              //從map地圖上刪除這個子元素div
              ele.parentNode.removeChild(ele);
              element.splice(i, 1);
            }
          }
          window.Snake = Snake;
        }());
        //自調用函數---游戲對象
        (function () {
          var that = null;
          //游戲的構造函數
          function game(map) {
            this.food = new Food(); //食物對象
            this.snake = new Snake(); //小蛇對象
            this.map = map; //地圖
            that = this;
          }
          game.prototype.init = function () {
            //初始化游戲
            //食物初始化
            this.food.init(this.map);
            //小蛇初始化
            this.snake.init(this.map);
            that = this;
            document.getElementById("dv").onclick = function () {
              document.getElementById("dv").style.display = "none";
              //調用小蛇移動的方法
              that.runSnake(that.food, that.map);
              //調用按鍵的方法
              that.bindKey();
            }.bind(that);
          };
          //添加原型方法---設置小蛇可以自動跑起來
          game.prototype.runSnake = function (food, map) {
            //自動的去移動
            var time = 90;
            var fn = function () {
              //此時this是window
              //移動小蛇
              this.snake.move(food, map);
              //初始化小蛇
              this.snake.init(map);
              //橫坐標的最大值
              var maxX = map.offsetWidth / this.snake.width;
              //縱坐標的最大值
              var maxY = map.offsetHeight / this.snake.height;
              //小蛇的頭的坐標
              var headX = this.snake.body[0].x;
              var headY = this.snake.body[0].y;
              //判斷 橫坐標 有沒撞墻
              if (headX < 0 || headX >= maxX) {
                //撞墻停止定時器
                clearInterval(timeId);
                alert("游戲結束");
                location.reload();
              }
              //判斷 縱坐標 有沒撞墻
              if (headY < 0 || headY >= maxY) {
                clearInterval(timeId);
                alert("游戲結束");
                location.reload();
              }
              //判斷 小蛇的頭部 有沒有 撞到自己
              for (let i = 1; i < this.snake.body.length; i++) {
                let x = this.snake.body[i].x;
                let y = this.snake.body[i].y;
                if (headX === x && headY === y) {
                  clearInterval(timeId);
                  alert("游戲結束");
                  location.reload();
                }
              }
              //增加游戲難度,判斷 到達一定數量的時候 加速
              switch (true) {
                case 5 <= this.snake.body.length && this.snake.body.length <= 10:
                  clearInterval(timeId);
                  time = 60;
                  timeId = setInterval(fn, time);
                  break;
                case 10 <= this.snake.body.length && this.snake.body.length <= 15:
                  clearInterval(timeId);
                  time = 40;
                  timeId = setInterval(fn, time);
                  break;
                case 15 <= this.snake.body.length:
                  clearInterval(timeId);
                  time = 30;
                  timeId = setInterval(fn, time);
                  break;
              }
              console.log(this.snake.body.length + "--" + "time:" + time);
            }.bind(that);
            //定時器小蛇自運動
            var timeId = setInterval(fn, time);
          };
          //添加原型方法---設置用戶按鍵,改變小蛇移動的方向
          game.prototype.bindKey = function () {
            //獲取用戶的按鍵,改變小蛇的移動方向
            document.addEventListener("keydown", function (e) {
              //獲取按鍵的值并進行判斷是,改變小蛇移動的方向
              switch (e.keyCode) {
                //沒有bind方法時此時的this指向的是documen
                case 37:
                  if (this.snake.driection != "right") {
                    this.snake.driection = "left";
                  }
                  break;
                case 38:
                  if (this.snake.driection != "bottom") {
                    this.snake.driection = "top";
                  }
                  break;
                case 39:
                  if (this.snake.driection != "left") {
                    this.snake.driection = "right";
                  }
                  break;
                case 40:
                  if (this.snake.driection != "top") {
                    this.snake.driection = "bottom";
                  }
                  break;
              }
            }.bind(that), false);
          };
          //把game暴露給window,外部就可以訪問game對象
          window.game = game;
        }());
        //初始化游戲對象
        var gm = new game(document.querySelector(".map"));
        //初始化游戲---開始游戲
        gm.init();
      </script>
    </body>
    </html>
    
777亚洲人成视频免费视频