当前位置:首页 > 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();
    }
  }
}

游戏边界检测和结束逻辑

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

vue 实现贪吃蛇

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 实现简单弹窗 组件基础结构 创建一个名为 Modal.vue 的组件文件,包含模板、脚本和样式部分: <template> <div class="mod…

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录组…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue 实现弹幕

vue 实现弹幕

vue 实现弹幕的方法 使用 CSS 动画和动态渲染 在 Vue 中实现弹幕效果,可以通过动态渲染弹幕元素并结合 CSS 动画实现。以下是具体步骤: 数据准备 创建一个数组存储弹幕数据,每条弹幕包…

vue实现同步

vue实现同步

Vue 实现同步的方法 在 Vue 中实现同步操作通常涉及数据绑定、状态管理和异步操作的处理。以下是几种常见的方法: 使用计算属性(Computed Properties) 计算属性基于响应式依赖进…

vue实现图册

vue实现图册

Vue实现图册功能 在Vue中实现图册功能通常涉及图片展示、切换、缩放等交互效果。以下是常见的实现方法和关键代码示例: 基础图册组件结构 使用Vue单文件组件构建基础结构: <templat…