canvas實現的貪吃蛇遊戲程式碼例項

admin發表於2017-02-17

分享一段程式碼例項,它實現了貪吃車遊戲效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.map {
  cursor: none;
  border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="map" class="map" width="800" height="800"></canvas>
<script>
var config = {
  //網格密度
  MeshDensity: 50
}
var Bamboo = function(x, y, ishead) {
  this.x = x;
  this.y = y;
  this.ishead = ishead;
  return this;
}
var DirectionKey = [];
DirectionKey[37] = "left";
DirectionKey[38] = "up";
DirectionKey[39] = "right";
DirectionKey[40] = "down";
var loaded = function() {
  var canvas = document.getElementById("map");
  var context = canvas.getContext("2d");
  var memorydata = {
      //身體
      snakebody: [],
      //移動方向
      moveDirection: "right",
      //敵人
      enemy: {
        x: 0,
        y: 0
      },
      //分數
      score: 0,
      //是否死亡
      isdied: false
    }
    //初始化資料
  var cellsize = canvas.width / config.MeshDensity;
  //構建蛇身
  for (var i = 3; i >= 0; i--) {
    var bamboo = new Bamboo(i, config.MeshDensity - 1, false);
    if (i == 3) {
      bamboo.ishead = true;
    }
    memorydata.snakebody.push(bamboo);
  }
  memorydata.enemy.x = Math.floor(Math.random() * config.MeshDensity);
  memorydata.enemy.y = Math.floor(Math.random() * config.MeshDensity);
  //蛇移動
  function snakeMove() {
    var oldhead = memorydata.snakebody[0];
    oldhead.ishead = false;
    var newhead = new Bamboo();
    newhead.ishead = true;
    if (canEat()) {
      newhead.x = memorydata.enemy.x;
      newhead.y = memorydata.enemy.y;
      memorydata.enemy.x = Math.floor(Math.random() * config.MeshDensity);
      memorydata.enemy.y = Math.floor(Math.random() * config.MeshDensity);
      memorydata.score++;
    } else {
      switch (memorydata.moveDirection) {
        case "up":
          newhead.y = oldhead.y - 1;
          newhead.x = oldhead.x;
          break;
        case "right":
          newhead.y = oldhead.y;
          newhead.x = oldhead.x + 1;
          break;
        case "down":
          newhead.y = oldhead.y + 1;
          newhead.x = oldhead.x;
          break;
        case "left":
          newhead.y = oldhead.y;
          newhead.x = oldhead.x - 1;
          break;
      }
      if (newhead.x < 0) {
        newhead.x = config.MeshDensity - 1;
      }
      if (newhead.x > config.MeshDensity - 1) {
        newhead.x = 0;
      }
      if (newhead.y < 0) {
        newhead.y = config.MeshDensity - 1;
      }
      if (newhead.y > config.MeshDensity - 1) {
        newhead.y = 0;
      }
      memorydata.snakebody.splice(memorydata.snakebody.length - 1, 1);
    }
    memorydata.snakebody.unshift(newhead);
  }
  //判斷蛇是否能吃掉目標
  function canEat() {
    var head = memorydata.snakebody[0];
    var result = false;
    switch (memorydata.moveDirection) {
      case "up":
        if (head.y == memorydata.enemy.y + 1 && head.x == memorydata.enemy.x) {
          result = true;
        }
        break;
      case "right":
        if (head.y == memorydata.enemy.y && head.x == memorydata.enemy.x - 1) {
          result = true;
        }
        break;
      case "down":
        if (head.y == memorydata.enemy.y - 1 && head.x == memorydata.enemy.x) {
          result = true;
        }
        break;
      case "left":
        if (head.y == memorydata.enemy.y && head.x == memorydata.enemy.x + 1) {
          result = true;
        }
        break;
    }
    return result;
  }
  //死亡判斷
  function isDead() {
    var head = memorydata.snakebody[0];
    var result = false;
    for (var i = 1; i < memorydata.snakebody.length; i++) {
      var bamboo = memorydata.snakebody<i>;
      if (bamboo) {
        if (head.x == bamboo.x && head.y == bamboo.y) {
          result = true;
          break;
        }
      }
    }
    return result;
  }
  //繪製蛇身
  function drawSnakeBody() {
    for (var i = 0; i < memorydata.snakebody.length; i++) {
      var bamboo = memorydata.snakebody<i>;
      if (bamboo) {
        var x = bamboo.x * cellsize;
        var y = bamboo.y * cellsize;
        if (bamboo.ishead) {
          context.fillStyle = "blue";
        } else {
          context.fillStyle = "green";
        }
        context.save();
        context.fillRect(x, y, cellsize, cellsize);
      }
    }
    context.restore();
  }
  //繪製敵人
  function drawEnemy() {
    var x = memorydata.enemy.x * cellsize;
    var y = memorydata.enemy.y * cellsize;
    context.fillStyle = "red";
    context.save();
    context.fillRect(x, y, cellsize, cellsize);
    context.restore();
  }
  //繪製分數文字
  function drawTextScore() {
    context.fillStyle = "cyan";
    context.save();
    context.font = "italic 30px sans-serif";
    context.textBaseline = 'top';
    context.fillText(memorydata.score, 0, 0);
    context.restore();
  }
  //繪製遊戲結束文字
  function drawTextFailed() {
    if (memorydata.isdied) {
      context.fillStyle = "#000";
      context.save();
      context.font = "normal 30px sans-serif";
      context.textBaseline = 'top';
      var text = "YOU DIED";
      context.fillText(text, config.MeshDensity / 2 * cellsize - text.length * cellsize / 2, config.MeshDensity / 2 * cellsize);
      context.restore();
    }
  }
  //重新整理幀
  (function drawFrame() {
    window.requestAnimationFrame(drawFrame, canvas);
    context.clearRect(0, 0, canvas.width, canvas.height);
    drawEnemy();
    drawSnakeBody();
    drawTextScore();
    drawTextFailed();
  }());
  //更新資料
 
  var worldTime = setInterval(function() {
    snakeMove();
    if (isDead()) {
      clearInterval(worldTime);
      memorydata.isdied = true;
    }
  }, 200);
  //轉向控制
  function turnCtl(event) {
    var event = event || window.event;
    if (!event.keyCode || event.keyCode == 0) {
      event.keyCode = event.which;
    }
    var direction = DirectionKey[event.keyCode];
    if (direction) {
      switch (memorydata.moveDirection) {
        case "up":
          if (direction == "down") {
            return false;
          }
          break;
        case "right":
          if (direction == "left") {
            return false;
          }
          break;
        case "down":
          if (direction == "up") {
            return false;
          }
          break;
        case "left":
          if (direction == "right") {
            return false;
          }
          break;
      }
      memorydata.moveDirection = DirectionKey[event.keyCode];
    }
  }
  window.addEventListener("keydown", turnCtl, false);
}
window.addEventListener("load", loaded, false);
</script>
</body>
</html>
</i></i>

相關文章