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!

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



When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.
