How to use Vue to implement the Snake game?
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.
- Run the following command in the terminal:
npm install -g @vue/cli
- Create a new Vue project.
vue create snake-game
- 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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.
