当前位置:首页 > 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实现下拉菜单可以通过动态绑定v-show或v-if控制菜单显示隐藏,结合事件监听(如@click或@mouseenter)触发状态切换。以下是两种常见实现方式: 方…

vue按钮实现截屏

vue按钮实现截屏

Vue 按钮实现截屏的方法 在 Vue 项目中实现截屏功能可以通过多种方式完成,以下是几种常见的方法: 使用 html2canvas 库 安装 html2canvas 库: npm ins…

vue实现自定义登录

vue实现自定义登录

实现自定义登录的基本步骤 在Vue中实现自定义登录功能通常需要结合前端和后端技术。以下是一个基本的实现流程: 创建登录表单组件 使用Vue的单文件组件创建一个登录表单,包含用户名和密码输入框以及提交…

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue 实现tabs

vue 实现tabs

Vue 实现 Tabs 组件的方法 使用动态组件和 v-for 在 Vue 中实现 Tabs 可以通过动态组件和 v-for 指令结合完成。定义一个 tabs 数组,包含每个标签的标题和对应的组件。…

vue 实现grid

vue 实现grid

在Vue中实现Grid布局可以通过多种方式完成,以下是几种常见的方法: 使用CSS Grid布局 CSS Grid是一种强大的布局系统,可以直接在Vue组件的样式中使用。以下是一个简单的示例:…