当前位置:首页 > VUE

vue 实现贪吃蛇

2026-02-20 22:48:45VUE

实现贪吃蛇的基本思路

使用 Vue 实现贪吃蛇游戏需要处理游戏逻辑、渲染蛇和食物、控制移动方向以及碰撞检测。Vue 的响应式特性适合管理游戏状态(如蛇的位置、食物位置、得分等),通过键盘事件监听控制蛇的移动方向。

核心代码结构

  1. 游戏状态初始化
    在 Vue 的 data 中定义游戏所需的状态:

    data() {
      return {
        snake: [{ x: 10, y: 10 }], // 蛇的初始位置(数组存储每一节)
        food: { x: 5, y: 5 },      // 食物的位置
        direction: 'right',        // 移动方向
        gameOver: false,           // 游戏结束标志
        score: 0,                  // 得分
        gridSize: 20,              // 网格大小(像素)
        cellCount: 20,             // 网格行列数
      };
    }
  2. 游戏循环与蛇的移动
    使用 setInterval 驱动游戏循环,每隔一定时间更新蛇的位置:

    methods: {
      startGame() {
        this.gameInterval = setInterval(() => {
          if (this.gameOver) return;
          this.moveSnake();
        }, 200); // 控制蛇的速度
      },
      moveSnake() {
        const head = { ...this.snake[0] };
        switch (this.direction) {
          case 'up':    head.y -= 1; break;
          case 'down':  head.y += 1; break;
          case 'left':  head.x -= 1; break;
          case 'right': head.x += 1; break;
        }
        this.checkCollision(head);
        this.snake.unshift(head); // 添加新头部
        if (this.isEatingFood(head)) {
          this.generateFood();
          this.score += 1;
        } else {
          this.snake.pop(); // 移除尾部(未吃到食物时)
        }
      }
    }
  3. 碰撞检测
    检测蛇是否撞墙或撞到自己:

    vue 实现贪吃蛇

    checkCollision(head) {
      // 撞墙
      if (
        head.x < 0 || head.x >= this.cellCount ||
        head.y < 0 || head.y >= this.cellCount
      ) {
        this.gameOver = true;
      }
      // 撞到自己
      this.snake.forEach(segment => {
        if (segment.x === head.x && segment.y === head.y) {
          this.gameOver = true;
        }
      });
    }
  4. 生成食物
    随机生成食物位置,确保不在蛇身上:

    generateFood() {
      const food = {
        x: Math.floor(Math.random() * this.cellCount),
        y: Math.floor(Math.random() * this.cellCount),
      };
      // 检查食物是否与蛇重叠
      const isOnSnake = this.snake.some(segment => 
        segment.x === food.x && segment.y === food.y
      );
      if (isOnSnake) this.generateFood();
      else this.food = food;
    }
  5. 键盘控制方向
    监听键盘事件,限制反向移动(如不能从右直接转向左):

    mounted() {
      window.addEventListener('keydown', (e) => {
        const keyToDirection = {
          ArrowUp: 'up',
          ArrowDown: 'down',
          ArrowLeft: 'left',
          ArrowRight: 'right',
        };
        const newDirection = keyToDirection[e.key];
        const oppositeDirections = {
          up: 'down',
          down: 'up',
          left: 'right',
          right: 'left',
        };
        if (newDirection && oppositeDirections[this.direction] !== newDirection) {
          this.direction = newDirection;
        }
      });
      this.startGame();
    }

渲染游戏界面

在模板中通过 v-for 渲染蛇和食物:

vue 实现贪吃蛇

<template>
  <div class="game-container">
    <div class="grid">
      <!-- 渲染食物 -->
      <div 
        class="food" 
        :style="{
          left: `${food.x * gridSize}px`,
          top: `${food.y * gridSize}px`,
          width: `${gridSize}px`,
          height: `${gridSize}px`,
        }"
      ></div>
      <!-- 渲染蛇 -->
      <div 
        v-for="(segment, index) in snake" 
        :key="index"
        class="snake-segment"
        :style="{
          left: `${segment.x * gridSize}px`,
          top: `${segment.y * gridSize}px`,
          width: `${gridSize}px`,
          height: `${gridSize}px`,
        }"
      ></div>
    </div>
    <div v-if="gameOver" class="game-over">Game Over! Score: {{ score }}</div>
  </div>
</template>

样式设计

添加基础 CSS 样式:

.game-container {
  position: relative;
  width: 400px;
  height: 400px;
  margin: 0 auto;
  border: 1px solid #000;
}
.grid {
  position: relative;
  width: 100%;
  height: 100%;
}
.snake-segment {
  position: absolute;
  background-color: green;
  border-radius: 2px;
}
.food {
  position: absolute;
  background-color: red;
  border-radius: 50%;
}
.game-over {
  text-align: center;
  font-size: 24px;
  margin-top: 20px;
}

完整示例与扩展建议

  1. 完整代码
    将上述代码片段整合到 Vue 单文件组件(.vue)中即可运行。

  2. 扩展功能

    • 添加开始/暂停按钮。
    • 调整游戏难度(如速度随得分增加)。
    • 实现本地存储高分记录。
    • 添加音效或动画效果。

标签: 贪吃蛇vue
分享给朋友:

相关文章

vue手写签名如何实现

vue手写签名如何实现

实现手写签名的基本思路 在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。…

vue怎么实现

vue怎么实现

Vue 实现方法 Vue 是一个流行的前端框架,用于构建用户界面。以下是几种常见的实现方法: 数据绑定 使用 v-model 指令实现双向数据绑定,适用于表单输入元素。 <input v-m…

vue实现github

vue实现github

Vue 实现 GitHub 相关功能 创建 GitHub API 请求 在 Vue 项目中,可以使用 axios 或 fetch 与 GitHub API 进行交互。需要在 GitHub 上创建个人访…

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用第三方库(如 Element UI) Element UI 提供了现成的分页组件 el-pagination,适合快速集成。 安装 Element UI: npm ins…

vue实现评价

vue实现评价

Vue实现评价功能 数据绑定与双向绑定 Vue的核心特性是数据绑定和双向绑定,通过v-model指令可以轻松实现表单输入与应用状态之间的双向绑定。在评价功能中,可以使用v-model绑定评论文本和评分…

vue实现数据渲染

vue实现数据渲染

Vue 数据渲染的实现方式 Vue.js 提供了多种数据渲染的方式,包括插值表达式、指令和计算属性等。以下是常见的实现方法: 插值表达式 使用双大括号 {{ }} 将数据绑定到模板中,数据变化时会自…