返回

贪食蛇游戏 - Canvas实现

前端

<!DOCTYPE html>
<html>
<head>
  
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1>贪食蛇游戏 - Canvas实现</h1>
  <canvas id="canvas" width="400" height="400"></canvas>

  <script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    // 定义蛇的初始位置和方向
    var snake = [
      {x: 200, y: 200},
      {x: 190, y: 200},
      {x: 180, y: 200},
      {x: 170, y: 200},
      {x: 160, y: 200}
    ];
    var dx = 10;
    var dy = 0;

    // 定义食物的初始位置
    var food = {
      x: Math.floor(Math.random() * 380 + 10),
      y: Math.floor(Math.random() * 380 + 10)
    };

    // 定义游戏状态
    var gameOver = false;

    // 定义键盘事件监听器
    document.addEventListener("keydown", function(e) {
      if (e.keyCode === 37) {
        dx = -10;
        dy = 0;
      } else if (e.keyCode === 38) {
        dx = 0;
        dy = -10;
      } else if (e.keyCode === 39) {
        dx = 10;
        dy = 0;
      } else if (e.keyCode === 40) {
        dx = 0;
        dy = 10;
      }
    });

    // 定义游戏循环
    function gameLoop() {
      // 清除画布
      ctx.fillStyle = "white";
      ctx.fillRect(0, 0, 400, 400);

      // 绘制蛇
      ctx.fillStyle = "green";
      for (var i = 0; i < snake.length; i++) {
        ctx.fillRect(snake[i].x, snake[i].y, 10, 10);
      }

      // 绘制食物
      ctx.fillStyle = "red";
      ctx.fillRect(food.x, food.y, 10, 10);

      // 移动蛇
      var head = {
        x: snake[0].x + dx,
        y: snake[0].y + dy
      };
      snake.unshift(head);

      // 检测是否吃到食物
      if (head.x === food.x && head.y === food.y) {
        food.x = Math.floor(Math.random() * 380 + 10);
        food.y = Math.floor(Math.random() * 380 + 10);
      } else {
        snake.pop();
      }

      // 检测是否撞墙
      if (head.x < 0 || head.x > 390 || head.y < 0 || head.y > 390) {
        gameOver = true;
      }

      // 检测是否吃到自己
      for (var i = 4; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
          gameOver = true;
        }
      }

      // 检测游戏是否结束
      if (gameOver) {
        alert("游戏结束!");
        window.location.reload();
      }

      // 重新绘制画布
      setTimeout(gameLoop, 100);
    }

    // 启动游戏循环
    gameLoop();
  </script>
</body>
</html>