当前位置:首页 > 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实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

拖拽式编程vue实现

拖拽式编程vue实现

拖拽式编程在 Vue 中的实现方法 使用 HTML5 原生拖放 API Vue 可以结合 HTML5 的拖放 API 实现基础拖拽功能。通过 draggable 属性标记可拖拽元素,监听 dragst…

前端vue登录功能实现

前端vue登录功能实现

Vue 登录功能实现步骤 创建登录表单组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含用户名和密码输入框以及提交按钮。 <template> &…

vue搜索过后实现分页

vue搜索过后实现分页

Vue 实现搜索后分页功能 数据绑定与搜索逻辑 在 Vue 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPa…

vue按钮实现截屏

vue按钮实现截屏

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

vue实现右下角弹框

vue实现右下角弹框

实现右下角弹框的基本思路 在Vue中实现右下角弹框,通常需要结合CSS定位和Vue的组件化特性。弹框可以通过绝对定位固定在右下角,并通过Vue控制其显示与隐藏。 创建弹框组件 新建一个Vue组件(…