JavaScript 简单的贪吃蛇示例 可以直接html运行

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>贪吃蛇</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
      // 获取画布和绘制上下文
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');

      // 定义常量和变量
      const gridSize = 10;
      const snake = [{ x: 0, y: 0 }];
      let direction = 'right';
      let food = generateFood();
      let score = 0;
      let gameOver = false;

      // 监听键盘事件
      document.addEventListener('keydown', (event) => {
        switch (event.code) {
          case 'ArrowUp':
            if (direction !== 'down') direction = 'up';
            break;
          case 'ArrowDown':
            if (direction !== 'up') direction = 'down';
            break;
          case 'ArrowLeft':
            if (direction !== 'right') direction = 'left';
            break;
          case 'ArrowRight':
            if (direction !== 'left') direction = 'right';
            break;
        }
      });

      // 游戏循环
      setInterval(() => {
        if (gameOver) return;

        // 移动蛇
        const head = { x: snake[0].x, y: snake[0].y };
        switch (direction) {
          case 'up':
            head.y -= gridSize;
            break;
          case 'down':
            head.y += gridSize;
            break;
          case 'left':
            head.x -= gridSize;
            break;
          case 'right':
            head.x += gridSize;
            break;
        }
        snake.unshift(head);

        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
          food = generateFood();
          score += 10;
        } else {
          snake.pop();
        }

        // 检查是否碰到墙壁或自己
        if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
          gameOver = true;
        } else {
          for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
              gameOver = true;
              break;
            }
          }
        }

        // 绘制画面
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x, food.y, gridSize, gridSize);
        ctx.fillStyle = 'green';
        snake.forEach((segment) => {
          ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
        });
        ctx.fillStyle = 'black';
        ctx.fillText(`得分: ${score}`, 10, 20);
      }, 100);

      // 随机生成食物位置
      function generateFood() {
        const x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize;
        const y = Math.floor(Math.random() * (canvas.height/gridSize)) * gridSize;
return { x, y };
}
</script>

  </body>
</html>

这段代码创建了一个400x400像素的画布,每个格子大小为10像素,实现了一个简单的贪吃蛇游戏。游戏循环每隔100毫秒更新一次画面,根据玩家的输入移动蛇并检查游戏是否结束,绘制蛇和食物,显示得分等信息。你可以在浏览器中打开这个HTML文件来运行这个贪吃蛇游戏。如果你想要定制更多的游戏规则或添加更多的功能,可以在这个代码的基础上进行修改和扩展。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值