当前位置:首页 > VUE

vue实现贪吃蛇

2026-01-20 10:00:50VUE

vue实现贪吃蛇

实现思路

Vue实现贪吃蛇游戏的核心在于数据驱动DOM渲染。通过维护蛇身坐标、食物位置和移动方向等状态,结合Vue的响应式特性实现游戏逻辑。

核心代码结构

<template>
  <div class="game-container">
    <div class="grid" :style="gridStyle">
      <div 
        v-for="(cell, index) in grid" 
        :key="index"
        :class="['cell', 
          { 'snake': cell.isSnake, 'food': cell.isFood }]"
      ></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      gridSize: 20,
      snake: [{x: 10, y: 10}],
      food: {},
      direction: 'right',
      gameSpeed: 200
    }
  }
}
</script>

初始化游戏

methods: {
  initGame() {
    this.generateFood();
    this.gameInterval = setInterval(this.moveSnake, this.gameSpeed);
    window.addEventListener('keydown', this.handleKeyPress);
  },

  generateFood() {
    this.food = {
      x: Math.floor(Math.random() * this.gridSize),
      y: Math.floor(Math.random() * this.gridSize)
    };
  }
}

蛇移动逻辑

moveSnake() {
  const head = {...this.snake[0]};

  switch(this.direction) {
    case 'up': head.y--; break;
    case 'down': head.y++; break;
    case 'left': head.x--; break;
    case 'right': head.x++; break;
  }

  if (this.checkCollision(head)) {
    this.gameOver();
    return;
  }

  this.snake.unshift(head);

  if (head.x === this.food.x && head.y === this.food.y) {
    this.generateFood();
  } else {
    this.snake.pop();
  }
}

碰撞检测

checkCollision(head) {
  // 边界检测
  if (head.x < 0 || head.x >= this.gridSize || 
      head.y < 0 || head.y >= this.gridSize) {
    return true;
  }

  // 自碰撞检测
  return this.snake.some(segment => 
    segment.x === head.x && segment.y === head.y
  );
}

键盘控制

handleKeyPress(e) {
  const keyMap = {
    'ArrowUp': 'up',
    'ArrowDown': 'down',
    'ArrowLeft': 'left',
    'ArrowRight': 'right'
  };

  const newDirection = keyMap[e.key];
  const oppositeDirections = {
    up: 'down',
    down: 'up',
    left: 'right',
    right: 'left'
  };

  if (newDirection && oppositeDirections[this.direction] !== newDirection) {
    this.direction = newDirection;
  }
}

样式设计

.game-container {
  display: flex;
  justify-content: center;
}

.grid {
  display: grid;
  grid-template-columns: repeat(20, 20px);
  gap: 1px;
  background: #eee;
}

.cell {
  width: 20px;
  height: 20px;
  background: white;
}

.snake {
  background: #4CAF50;
}

.food {
  background: #F44336;
  border-radius: 50%;
}

游戏状态管理

gameOver() {
  clearInterval(this.gameInterval);
  alert('Game Over!');
  this.resetGame();
},

resetGame() {
  this.snake = [{x: 10, y: 10}];
  this.direction = 'right';
  this.generateFood();
  this.initGame();
}

响应式网格计算

computed: {
  grid() {
    const grid = [];
    for (let y = 0; y < this.gridSize; y++) {
      for (let x = 0; x < this.gridSize; x++) {
        grid.push({
          x, y,
          isSnake: this.snake.some(segment => segment.x === x && segment.y === y),
          isFood: this.food.x === x && this.food.y === y
        });
      }
    }
    return grid;
  },

  gridStyle() {
    return {
      gridTemplateColumns: `repeat(${this.gridSize}, 20px)`
    };
  }
}

生命周期控制

mounted() {
  this.initGame();
},

beforeDestroy() {
  clearInterval(this.gameInterval);
  window.removeEventListener('keydown', this.handleKeyPress);
}

扩展功能建议

  1. 添加分数计算系统
  2. 实现游戏暂停功能
  3. 增加难度等级选择
  4. 添加移动端触摸控制
  5. 实现游戏存档功能

vue实现贪吃蛇

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

相关文章

vue怎么实现动画

vue怎么实现动画

Vue 动画实现方法 Vue 提供了多种方式实现动画效果,包括内置过渡系统、第三方库集成以及 CSS 动画。以下是常见实现方法: 使用 Vue 过渡系统 通过 <transition>…

vue怎么实现数据检测

vue怎么实现数据检测

Vue 数据检测的实现方式 Vue 通过响应式系统实现数据检测,核心机制基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现方法: 基于 Vue…

vue公共列表的实现

vue公共列表的实现

实现 Vue 公共列表组件 公共列表组件通常用于展示重复结构的数据,例如商品列表、用户列表等。以下是一个典型的实现方式: 基础实现 创建可复用的列表组件 List.vue: <templ…

vue实现多选题

vue实现多选题

Vue实现多选题的方法 使用Vue实现多选题功能,可以通过v-model绑定数组、动态渲染选项、以及处理选中状态来实现。以下是一个完整的实现示例: 基础实现代码 <template>…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue原型实现

vue原型实现

Vue 原型实现的关键点 Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。 数据响应式原理 Vue 通过 Obje…