当前位置:首页 > 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 实现屏幕共享的方法 使用 WebRTC 和 getDisplayMedia API 通过 navigator.mediaDevices.getDisplayMedia 捕获屏幕内容,结合 We…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store 示…

vue自己实现下拉导航

vue自己实现下拉导航

实现下拉导航的基本思路 在Vue中实现下拉导航,可以通过结合Vue的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue datepicker 实现

vue datepicker 实现

实现 Vue Datepicker 的基本方法 在 Vue 项目中实现日期选择功能,可以使用第三方库如 vue-datepicker 或 v-calendar。以下是两种常见实现方式: 安装 vu…

vue 指令实现

vue 指令实现

Vue 指令实现 Vue 指令是 Vue.js 提供的特殊属性,用于在 DOM 元素上添加特殊行为。指令以 v- 前缀开头,例如 v-model、v-if、v-for 等。以下是实现自定义指令和常用内…