search
HomeWeb Front-endVue.jsHow to use Vue to implement the Snake game?

How to use Vue to implement the Snake game?

Jun 25, 2023 am 09:12 AM
vuegameComponentization.

Snake is a classic game that is simple and easy to play but has tons of fun. This article will introduce how to use the Vue framework to implement a simple snake game.

1. Project preparation

Before we start, we need to install Vue CLI. If you haven't installed it yet, you can follow the steps below to install it.

  1. Run the following command in the terminal:
npm install -g @vue/cli
  1. Create a new Vue project.
vue create snake-game
  1. Enter the project you just created.
cd snake-game

2. Project structure and technology selection

In terms of project structure, we need to create two components: one is the game interface component, and the other is the snake component.

In terms of technology selection, we chose to use HTML5 Canvas to draw the game interface and use Vue componentization ideas to implement logic control.

3. Implementation

  1. Create a game interface component

Create a new Game.vue file in the src/components/ directory, and then add the following code :

<template>
  <div>
    <canvas ref="canvas" width="600" height="400"></canvas>
  </div>
</template>

<script>
export default {
  mounted() {
    this.canvas = this.$refs.canvas;
    this.context = this.canvas.getContext("2d");
    this.canvas.width = 600;
    this.canvas.height = 400;
    this.startGame();
  },
  methods: {
    startGame() {
      // 游戏启动
    },
  },
};
</script>

<style>
canvas {
  border: 1px solid #000;
}
</style>

This is a very simple component, we only need to write an HTML5 Canvas element, and then bind a reference to it, get the reference when the component is mounted and start the game.

  1. Add snake component

Create a new Snake.vue file in the src/components/ directory, and then add the following code:

<template>
  <div>
    <div v-for="(bodyPart, index) in snake" :key="index" :style="getSnakeStyles(bodyPart)"></div>
  </div>
</template>

<script>
export default {
  props: {
    snake: {
      type: Array,
      default: () => [{ x: 0, y: 0 }],
    },
  },
  methods: {
    getSnakeStyles(bodyPart) {
      return {
        position: "absolute",
        width: "20px",
        height: "20px",
        background: "green",
        left: `${bodyPart.x}px`,
        top: `${bodyPart.y}px`,
      };
    },
  },
};
</script>

<style></style>

This component will According to the snake attribute passed in by the parent component, each body part of the snake is rendered in a loop. We only need to write a getSnakeStyles function, return an object containing style information, and dynamically generate snakes based on the data.

  1. Add a snake in the Game component

In the script block of the Game component, we need to introduce the Snake component and add the following code to the startGame method:

import Snake from "./Snake.vue";

export default {
  // ...
  components: {
    Snake,
  },
  data() {
    return {
      snake: [],
    };
  },
  methods: {
    startGame() {
      this.snake.push({ x: 0, y: 0 });
    },
  },
};

Here, we added a data called snake to the Game component, and then added a line of code to the startGame method to add the first body part to the snake data. Finally, we introduced the Snake component and added the snake attribute to the template.

  1. Control snake movement

In order to allow the snake to move, we need to add a timer to the Game component and call the moveSnake method at regular intervals to control the movement of the snake. .

data() {
  return {
    snake: [],
    direction: "right",
    moveInterval: null
  };
},
methods: {
  startGame() {
    this.snake.push({ x: 0, y: 0 });
    this.moveInterval = setInterval(this.moveSnake, 200);
  },
  moveSnake() {
    const snakeHead = { ...this.snake[0] };

    switch (this.direction) {
      case "right":
        snakeHead.x += 20;
        break;
      case "left":
        snakeHead.x -= 20;
        break;
      case "up":
        snakeHead.y -= 20;
        break;
      case "down":
        snakeHead.y += 20;
        break;
    }

    this.snake.pop();
    this.snake.unshift(snakeHead);
  },
  handleKeyDown(event) {
    switch (event.keyCode) {
      case 37:
        if (this.direction !== "right") this.direction = "left";
        break;
      case 38:
        if (this.direction !== "down") this.direction = "up";
        break;
      case 39:
        if (this.direction !== "left") this.direction = "right";
        break;
      case 40:
        if (this.direction !== "up") this.direction = "down";
        break;
    }
  },
},

Among them, we added a data called direction to the Game component, indicating the current direction of the snake. moveInterval represents the id used to clear the timer. In the moveSnake method, we calculate the new position of the snake's head based on the current direction of the snake, delete the original end and insert the new snake's head at the head.

Finally, we implemented the handleKeyDown method, which is used to listen for keyboard events to change the snake's movement direction.

  1. The game ends when it hits the boundary or itself

In order to implement the game end function, we need to determine whether the snake has touched the boundary or itself inside the moveSnake method.

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

  switch (this.direction) {
    case "right":
      snakeHead.x += 20;
      break;
    case "left":
      snakeHead.x -= 20;
      break;
    case "up":
      snakeHead.y -= 20;
      break;
    case "down":
      snakeHead.y += 20;
      break;
  }

  // 判断是否越界
  if (snakeHead.x < 0 || snakeHead.x > 580 || snakeHead.y < 0 || snakeHead.y > 380) {
    clearInterval(this.moveInterval);
    alert("Game over!");
    location.reload();
    return;
  }

  // 判断是否碰到了自身
  for (let i = 1; i < this.snake.length; i++) {
    if (snakeHead.x === this.snake[i].x && snakeHead.y === this.snake[i].y) {
      clearInterval(this.moveInterval);
      alert("Game over!");
      location.reload();
      return;
    }
  }

  this.snake.pop();
  this.snake.unshift(snakeHead);
}

Here, we first determine whether the snake head has crossed the boundary of the game interface. If it crosses the boundary, clear the timer and prompt the game to end. Otherwise, continue execution.

Then, in the loop, it is judged one by one whether the snake head has touched itself. If so, the timer is also cleared and the game is over.

  1. Drawing food in the game interface

Finally, we implement the function of drawing food in the game interface. In order to achieve this function, we use randomFoodPosition to calculate a random food position, and then use the drawCircle method to draw circular food in the game interface.

startGame() {
  // ...
  // 画出第一个食物
  this.food = this.getRandomFoodPosition();
  this.drawCircle(this.context, this.food.x, this.food.y, 10, "red");
},
methods: {
  // ...
  getRandomFoodPosition() {
    return {
      x: Math.floor(Math.random() * 30) * 20,
      y: Math.floor(Math.random() * 20) * 20,
    };
  },
  drawCircle(ctx, x, y, r, color) {
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2, true);
    ctx.fill();
  },
},

Here, we added a data named food to the Game component, indicating the current food location. In the startGame method, we call the getRandomFoodPosition method to calculate a random food position, and then use the drawCircle method to draw food in the interface.

Finally, we only need to determine whether the snake coincides with the food in the moveSnake method. If they coincide, increase the length of the snake's body and recalculate a new food position.

moveSnake() {
  // ...

  // 判断是否吃到了食物
  if (snakeHead.x === this.food.x && snakeHead.y === this.food.y) {
    this.snake.push(this.snake[this.snake.length - 1]);
    this.food = this.getRandomFoodPosition();
  }

  // ...
},

So far, we have completed all the content of implementing the Snake game in Vue.

4. Summary

This article introduces how to use the Vue framework to implement a simple snake game. In this process, we learned how to use HTML5 Canvas elements for interface drawing, and how to use Vue componentization ideas to implement logic control, and finally completed a Snake game with basic gameplay. I hope this article can be helpful to everyone in learning the Vue framework and game development.

The above is the detailed content of How to use Vue to implement the Snake game?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)