javascript貪吃蛇小遊戲程式碼例項

admin發表於2017-04-12

本章節分享一段程式碼例項,它實現了貪吃蛇小遊戲功能。

雖然美觀度和真正商業應用的沒法相比,但是功能是基本實現了。

非常適合學習者參考之用,程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#container {
  width: 1000px;
  height: 550px;
  border: 1px solid #000;
  margin: 0 auto;
}
#ground {
  width: 1000px;
  height: 500px;
  background: gray;
  position: relative;
}
#button {
  float: right;
  height: 50px;
  line-height: 50px;
}
button {
  width: 50px;
  height: 20px;
}
.block {
  width: 20px;
  height: 20px;
  float: left;
  background: #2abad9;
}
.snakeBody {
  width: 20px;
  height: 20px;
  background: #f57926;
  position: absolute;
  top: 60px;
}
.snake-block {
  background: #f57926;
  position: absolute;
}
.food-block {
  background: green;
  position: absolute;
}
</style>
</head>
<body>
<div id="container">
  <div id="ground"></div>
    <div id="gameControl">
      <div id="button">
        <button id="start">開始</button>
        <button id="pause">暫停</button>
      </div>
    </div>
  </div>
  <script>
    //建立草坪
    var oGround = document.getElementById("ground");
    for (var i = 0; i < 50 ; i++) {
      for (var j = 0; j < 25 ; j++) {
        var oDiv = document.createElement("div");
        oDiv.className = "block";
        oGround.appendChild(oDiv);
      }
    };
    //建立蛇
    var snakeBody = new Array();//蛇身陣列
    for (var i = 3; i > 0; i--) {
      var oDiv = document.createElement("div");
      oDiv.className = "block snakeBody";
      oDiv.style.left = i * 20 + "px";
      oGround.appendChild(oDiv);
      snakeBody.push(oDiv);//向蛇身陣列新增蛇身
    }
 
 
    //建立食物
    var food = createFood();
    //蛇移動
    var direction = 'right';
    var oBtnStart = document.getElementById("start");
    var timer = null;
    oBtnStart.onclick = function () {
      clearInterval(timer);
      timer = setInterval(function () {
        // for(var i=0; i<snakeBody.length;i++){
        //         snakeBody[i].style.left=snakeBody[i].offsetLeft + 20 + "px";
        // }
        move(direction);
      }, 300);
 
    }
    //蛇轉向
    document.onkeydown = function (e) {
      e = e || window.event;
      var keyCode = e.which || e.keyCode;
      if (keyCode == 37) {//左
        if (direction != 'right') {
          direction = 'left';
          move(direction);
        }
      } else if (keyCode == 38) {//上
        if (direction != 'down') {
          direction = 'up';
          move(direction);
        }
      } else if (keyCode == 39) {//右
        if (direction != 'left') {
          direction = 'right';
          move(direction);
        }
      } else if (keyCode == 40) {//下
        if (direction != 'up') {
          direction = 'down';
          move(direction);
        }
      }
    };
    //蛇暫停
    var oPause = document.getElementById("pause");
    oPause.onclick = function () {
      clearInterval(timer);
    }
    //蛇移動的方法
    function move(dir) {
      var snakeHead = snakeBody[0];//取出蛇頭
      for (var i = snakeBody.length - 1; i > 0; i--) {
        snakeBody[i].style.left = snakeBody[i - 1].offsetLeft + "px";
        snakeBody[i].style.top = snakeBody[i - 1].offsetTop + "px";
      }
      switch (dir) {
        case "left":
          snakeHead.style.left = snakeHead.offsetLeft - 20 + "px";
          break;
        case "up":
          snakeHead.style.top = snakeHead.offsetTop - 20 + "px";
          break;
        case "right":
          snakeHead.style.left = snakeHead.offsetLeft + 20 + "px";
          break;
        case "down":
          snakeHead.style.top = snakeHead.offsetTop + 20 + "px";
          break;
 
      }
      //蛇是否吃到身體/牆
      if (snakeHead.offsetLeft == -20 || snakeHead.offsetTop == -20 || snakeHead.offsetLeft == 1000 || snakeHead.offsetTop == 500) {
        alert("Game over");
        clearInterval(timer);
        location.reload(); // 頁面重新整理
      }
      //蛇吃身體
      for (var i = 1; i < snakeBody.length; i++) {
        if (snakeHead.offsetLeft == snakeBody[i].offsetLeft && snakeHead.offsetTop == snakeBody[i].offsetTop) {
          alert(1);
          clearInterval(timer);
        }
      }
      //蛇吃食物
      if (snakeHead.offsetLeft == food.offsetLeft && snakeHead.offsetTop == food.offsetTop) {
        food.className = "block snake-block";
        if ("direction" == "right") {
          food.style.left = snakeBody[snakeBody.length - 1].offsetLeft - 20 + "px";
        } else if ("direction" == "down") {
          food.style.top = snakeBody[snakeBody.length - 1].offsetTop - 20 + "px";
        } else if ("direction" == "left") {
          food.style.left = snakeBody[snakeBody.length - 1].offsetLeft + 20 + "px";
        } else if ("direction" == "up") {
          food.style.top = snakeBody[snakeBody.length - 1].offsetTop + 20 + "px";
        }
        snakeBody.push(food);//蛇吃到食物
        food = createFood();//重新生成食物
      }
    }
    //生成食物
    function createFood() {
      var oFood = document.createElement("div");
      oFood.className = "block food-block";
      var iLeft = iTop = 0;
      do {
        var bFound = true;//一個標識,表示是否找到食物合適的位置
        iLeft = Math.floor(Math.random() * 1000);
        iLeft = iLeft - iLeft % 20;//隨機產生食物的位置
        iTop = Math.floor(Math.random() * 500);
        iTop = iTop - iTop % 20;
        for (var i = 0; i < snakeBody.length; i++) {
          if (snakeBody[i].offsetLeft == iLeft && snakeBody[i].offsetTop == iTop) {
            bFound = false;//表示食物與蛇身重合
            break;
          }
        }
        oFood.style.left = iLeft + "px";
        oFood.style.top = iTop + "px";
        oGround.appendChild(oFood);
      } while (!bFound);
      return oFood;
    }
  </script>
</body>
</html>

相關文章