当前位置:首页 > VUE

vue 实现贪吃蛇

2026-01-20 06:45:14VUE

Vue 实现贪吃蛇游戏

贪吃蛇是一个经典的游戏,可以通过 Vue 结合 Canvas 或纯 DOM 操作实现。以下是两种实现方式的具体方法。

使用 Canvas 实现贪吃蛇

Canvas 适合高性能渲染,适合复杂游戏场景。

  1. 初始化游戏画布
    在 Vue 组件的 mounted 钩子中初始化 Canvas,并设置游戏区域和蛇的初始状态。
<template>
  <canvas ref="gameCanvas" width="400" height="400"></canvas>
</template>

<script>
export default {
  data() {
    return {
      snake: [{ x: 10, y: 10 }],
      food: { x: 5, y: 5 },
      direction: 'right',
      gameLoop: null
    };
  },
  mounted() {
    const canvas = this.$refs.gameCanvas;
    this.ctx = canvas.getContext('2d');
    this.startGame();
  },
  methods: {
    startGame() {
      this.gameLoop = setInterval(this.updateGame, 100);
    },
    updateGame() {
      this.moveSnake();
      this.drawGame();
    },
    drawGame() {
      this.ctx.clearRect(0, 0, 400, 400);
      this.ctx.fillStyle = 'green';
      this.snake.forEach(segment => {
        this.ctx.fillRect(segment.x * 20, segment.y * 20, 20, 20);
      });
      this.ctx.fillStyle = 'red';
      this.ctx.fillRect(this.food.x * 20, this.food.y * 20, 20, 20);
    }
  }
};
</script>
  1. 控制蛇的移动
    监听键盘事件,更新蛇的移动方向,并处理蛇的移动逻辑。
methods: {
  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.snake.unshift(head);
    if (head.x === this.food.x && head.y === this.food.y) {
      this.generateFood();
    } else {
      this.snake.pop();
    }
  },
  generateFood() {
    this.food = {
      x: Math.floor(Math.random() * 20),
      y: Math.floor(Math.random() * 20)
    };
  }
},
created() {
  window.addEventListener('keydown', (e) => {
    switch (e.key) {
      case 'ArrowUp': this.direction = 'up'; break;
      case 'ArrowDown': this.direction = 'down'; break;
      case 'ArrowLeft': this.direction = 'left'; break;
      case 'ArrowRight': this.direction = 'right'; break;
    }
  });
}

使用纯 DOM 实现贪吃蛇

如果不涉及复杂动画,可以用纯 DOM 实现,适合简单场景。

  1. 渲染蛇和食物
    使用 v-for 动态渲染蛇的身体和食物。
<template>
  <div class="game-board">
    <div 
      v-for="(segment, index) in snake" 
      :key="index" 
      class="snake-segment" 
      :style="{ left: segment.x * 20 + 'px', top: segment.y * 20 + 'px' }"
    ></div>
    <div 
      class="food" 
      :style="{ left: food.x * 20 + 'px', top: food.y * 20 + 'px' }"
    ></div>
  </div>
</template>

<style>
.game-board {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #000;
}
.snake-segment {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: green;
}
.food {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: red;
}
</style>
  1. 控制游戏逻辑
    监听键盘事件并更新蛇的位置,逻辑与 Canvas 版本类似。
methods: {
  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.snake.unshift(head);
    if (head.x === this.food.x && head.y === this.food.y) {
      this.generateFood();
    } else {
      this.snake.pop();
    }
  }
}

游戏边界检测和结束逻辑

添加边界检测和碰撞检测,游戏结束时清除定时器。

methods: {
  checkCollision(head) {
    // 撞墙检测
    if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) {
      return true;
    }
    // 撞到自己检测
    for (let i = 1; i < this.snake.length; i++) {
      if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
        return true;
      }
    }
    return false;
  },
  updateGame() {
    this.moveSnake();
    if (this.checkCollision(this.snake[0])) {
      clearInterval(this.gameLoop);
      alert('Game Over!');
    }
    this.drawGame();
  }
}

以上是 Vue 实现贪吃蛇的两种方式,Canvas 适合高性能需求,DOM 方式更简单直观。可以根据需求选择合适的方法。

vue 实现贪吃蛇

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

相关文章

vue实现倒计时抢券

vue实现倒计时抢券

Vue 实现倒计时抢券功能 核心逻辑 倒计时抢券功能需要结合时间计算、状态管理和界面交互。通过 Vue 的响应式特性和生命周期钩子,可以高效实现这一需求。 实现步骤 1. 数据准备 在 Vue 组件…

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要…

vue全选实现

vue全选实现

Vue 全选实现方法 在 Vue 中实现全选功能通常涉及数据绑定和事件处理。以下是几种常见的实现方式: 基础实现方式 <template> <div> <…

vue组件实现

vue组件实现

Vue 组件实现基础 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件的实现包括定义、注册、数据传递和生命周期管理等。 定义组件 组件可以通过单文件组件(.…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式…