1. 程式人生 > 程式設計 >javascript實現貪吃蛇小練習

javascript實現貪吃蛇小練習

本文例項為大家分享了js實現貪吃蛇的具體程式碼,供大家參考,具體內容如下

遊戲思路:

  • 建立方塊、控制按鈕(showBlock)
  • 方塊移動(點選開始,不斷建立並移除前面的方塊,用到佇列先進先出)
  • 控制移動(doUp\doDown\doLeft\doRight,加入用鍵盤控制)
  • 產生食物方塊(generateFood)
  • 吃到食物變長(當方塊位置相同時,吃食物)
  • 判斷撞牆、撞到自己遊戲結束
  • 設定積分
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    .content {
      width: 800px;
      height: 400px;
      background-color: gray;
      display: absolute;

    }
  </style>

  <div id="content" class="content">
  </div>
  <button onclick="start()">開始遊戲</button>
  <button onclick="doUp()">上</button>
  <button onclick="doDown()">下</button>
  <button onclick="doLeft()">左</button>
  <button onclick="doRight()">右</button>
  <div id="score">0</div>

  <script>
    //定義引數
    var snackBlock = {};
    snackBlock.top = 20;
    snackBlock.left = 20;
    var firstDiv = showBlock(snackBlock.left,snackBlock.top,"red");
    var snackDivArray = [];//裝方塊的陣列
    snackDivArray.push(firstDiv);

    var left = 1,right = 2,up = 3,down = 4;
    var direction = right;
    var food = generateFood();//生成食物
    var hasEat = false;
    var score = 0;


    function generateFood() {

      var left = getRandomNum(39);
      var top = getRandomNum(19);
      var foodBlock = showBlock(left,top,"pink");
      foodBlock.left = left;
      foodBlock.top = top;
      return foodBlock;
    }

    function getRandomNum(max) {
      return Math.round(Math.random() * max) * 20;
    }

    function start() {
      var interval = setInterval(function () {
        var newBlock = {};
        switch (direction) {
          case up:
            newBlock.top = snackBlock.top - 20;
            newBlock.left = snackBlock.left;
            break;
          case down:
            newBlock.top = snackBlock.top + 20;
            newBlock.left = snackBlock.left;
            break;
          case left:
            newBlock.top = snackBlock.top;
            newBlock.left = snackBlock.left - 20;
            break;
          case right:
            newBlock.top = snackBlock.top;
            newBlock.left = snackBlock.left + 20;
            break;

        }


        var currentLeft = newBlock.left;
        var currentTop = newBlock.top;
        var eat = false;

        //吃食物
        if (currentLeft == food.left && currentTop == food.top) {
          removeBlock(food);
          food = generateFood();
          eat = true;
          hasEat = true;
          score += 10;//吃一個加10分
          document.getElementById("score").innerHTML = score;//寫入div
        }

        snackBlock = newBlock;
        //是否撞牆
        if (currentLeft < 0 || currentLeft >= 800 || currentTop < 0 || currentTop >= 400) {
          alert("game over!");
          clearInterval(interval);
          return;
        }
        if (eat == false) {
          //移除尾巴
          removeBlock(snackDivArray.shift(div));
        }
        //是否撞到自己
        snackDivArray.forEach(function (item,index,array) {
          if (item.top == currentTop && item.left == currentLeft) {
            alert("game over!");
            clearInterval(interval);
            return;
          }
        });

        //建立新的身體
        var div = showBlock(newBlock.left,newBlock.top,"red");
        div.left = newBlock.left;
        div.top = newBlock.top;
        snackDivArray.push(div);

      },300);

    }

    //方向控制
    function doUp() {
      if (direction == down && hasEat) {
        return;
      }
      direction = up;
    }
    function doDown() {
      if (direction == up && hasEat) {
        return;
      }
      direction = down;
    }
    function doRight() {
      if (direction == left && hasEat) {
        return;
      }
      direction = right;
    }
    function doLeft() {
      if (direction == right && hasEat) {
        return;
      }
      direction = left;
    }

    function showBlock(left,color) {//產生方塊
      var content = document.getElementById("content");
      var snackDiv = document.createElement("div");
      snackDiv.style.width = "20px";
      snackDiv.style.height = "20px";
      snackDiv.style.left = left + "px";
      snackDiv.style.top = top + "px";
      snackDiv.style.background = color;
      snackDiv.style.position = "absolute";
      content.appendChild(snackDiv);
      return snackDiv;
    }
    function removeBlock(div) {//移除方塊
      div.parentNode.removeChild(div);
    }
    //鍵盤控制方向
    document.onkeydown = function (e) {
      if (e && e.keyCode == 38) {
        doUp();
      } else if (e && e.keyCode == 40) {
        doDown();
      } else if (e && e.keyCode == 37) {
        doLeft();
      } else if (e && e.keyCode == 39) {
        doRight();
      }
    }
  </script>
</body>

</html>

更多有趣的經典小遊戲實現專題,分享給大家:

C++經典小遊戲彙總

python經典小遊戲彙總

python俄羅斯方塊遊戲集合

JavaScript經典遊戲 玩不停

java經典小遊戲彙總

javascript經典小遊戲彙總

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。