Teach you how to easily make a snake game using Vue (with demo code)
This article is going to share how to use Vue.js to implement a command line snake game (temir-snake-game). Everyone must be familiar with the snake game and use Vue. It seems that it is not difficult to implement a Web version of the Snake game in js, but what if it is a command line version? Are you interested in its implementation principle? Let's get started!
Vue.js Write a command line Snake game
Install
npm install temir-snake-game -g
Start the game
Run in the terminal windowtemir -sg
.
For Windows systems, it is recommended to use the hyper terminal for experience.
Render Vue to the command line interface
Use Vue .js to implement the command line Snake game, first means that we have to render Vue.js to the command line interface before we can start the specific game implementation. We often use Vue.js to write web applications, but Vue’s capabilities are not only Limited to this, its stage is not limited to browsers. Vue3 has excellent cross-platform capabilities. We can create a custom renderer through the createRenderer API, create the corresponding Node and Element in the host environment, and add, delete, and modify elements. Check the operation. [Recommendation: vue.js video tutorial]
Thanks to the excellent cross-platform capabilities of Vue3, I implemented Temir, a command line interface application that uses Vue components. Tools. Developers only need to use Vue to write command line applications without any additional learning costs. By the way, it is worth mentioning that it also supports HMR~
I won’t introduce Temir in detail here. Interested children can check out the introduction on Github or read this article about using Vue.js to write a command line interface.
Snake Game Implementation
With Temir, we have the conditions to use Vue.js to write command line games. Next, let’s take a look at the specific implementation of the game:
Implementation Disassembly
First of all, let’s do a simple dismantling of the game implementation. From the perspective of element logic, it can be simply divided into several parts:
Element initialization
Competition stage
Both the crawling of snakes and the generation of food depend on coordinates. The simplest coordinates actually only require one index value. . Therefore, the composition of the arena is also very simple. It is composed of many small boxes (here represented by ⬛). Each box corresponds to a coordinate (index). What we want to do is a 28*28 arena, so its The index set is (0~783).
const basic = 28 const backgroundIcon = '⬛' const arena = ref<string[]>([]) function initArena() { arena.value = Array.from({ length: basic * basic }, () => backgroundIcon) }
SNAKE
We mentioned the concept of coordinates earlier, and the snake body is composed of a series of regular coordinates.
const snakeIcon = '?' // 坐标(索引)30,29 长度为2的蛇身 const snakeBody = ref([30, 29])
Food
The generation of food is actually a random coordinate (index), but it should be noted that we need to avoid the coordinates of the snake itself.
const foodIcon = '?' // 食物坐标 const foodCoord = ref(77) // 生成食物 function generateFood() { const food = Math.floor(Math.random() * basic * basic) // 与蛇身冲突,重新生成 if (snakeBody.value.includes(food)) { generateFood() return } foodCoord.value = food }
The initialized element looks like this :
The snake's crawling
The snake's crawling logic has two basic elements, the number of direction steps. Earlier we mentioned that the composition of the arena is a 28 *28 determinant structure, then the mapping of direction and number of steps is relatively clear:
const map = { left: -1, right: 1, top: -28, bottom: 28 }
With two basic elements, we can get the next coordinate of each crawl. We You only need to add the corresponding coordinates to the snake's head each time it crawls, and remove the coordinates of the snake's tail to achieve the effect of the snake crawling.
function move() { const h = snakeBody.value[0] // 计算下一次爬行坐标,并添加至蛇头 head.value = h + direction.value snakeBody.value.unshift(head.value) // 吃到食物,重新生成 if (head.value === foodCoord.value) { generateFood() } // 只有在未吃到食物的时候,才需要移除蛇尾 else { snakeBody.value.pop() } }
cross-border logic
Greedy Snake Game The end of the rule is that the snake's head crosses the boundary when crawling (the boundary here refers to beyond the range of the arena) or touches the snake's body.
function isOutOfRange(h: number) { // 1. 蛇头碰到蛇身 return snakeBody.value.indexOf(h, 1) > 0 // 2. 蛇头超出竞技台上方 || h < 0 // 3. 蛇头超出竞技台下方 || h > basic * basic - 1 // 4. 蛇头超出竞技台右方 || (direction.value === 1 && h % basic === 0) // 5. 蛇头超出竞技台左方 || (direction.value === -1 && h % basic === basic - 1) }
Direction Control
The core operating logic of the Snake game It lies in manipulating the direction of the snake to catch food. So what we need to do is to capture the input of the user's direction keys to switch the direction. Temir provides the useInput function to monitor the user's input.
import { useInput } from '@temir/core' useInput(onKeyBoard, { isActive: true }) function onKeyBoard(_, keys) { const { upArrow, downArrow, leftArrow, rightArrow } = keys const d = { [+leftArrow]: -1, [+rightArrow]: 1, [+upArrow]: -basic, [+downArrow]: basic, }[1] ?? direction.value direction.value = (snakeBody.value[1] - snakeBody.value[0] === d) ? direction.value : d }
UI Drawing
About UI drawing and presentation Temir provides some Vue components. We only need to build the terminal UI like building Flexbox layout:
<script setup> import { computed } from 'vue' import { TBox, TText } from '@temir/core' import { useGame } from './composables' import Header from './components/Header.vue' import Home from './components/Home.vue' import Game from './components/Game.vue' import GameOver from './components/GameOver.vue' import Exit from './components/Exit.vue' const { playStatus } = useGame() const activeComponent = computed(() => { return { unplayed: Home, playing: Game, over: GameOver, exit: Exit, }[playStatus.value] }) </script> <template> <TBox :width="100" justify-content="center" align-items="center" flex-direction="column" border-style="double" > <Header /> <component :is="activeComponent" /> </TBox> </template>
At this point, the implementation of Snake is over, and we have a sense of the specific implementation. If you are interested, you can check the source code.
Demo
The above is the detailed content of Teach you how to easily make a snake game using Vue (with demo code). For more information, please follow other related articles on the PHP Chinese website!

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' 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.

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 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.

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.

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

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.

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.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools