Home > Article > Web Front-end > 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.
npm install -g @vue/cli
vue create snake-game
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 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.
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.
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.
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.
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.
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!