WeChat Mini Program-Snake Tutorial Example
A long time ago, almost half a year ago, the author published an article about the development of the OC version of Snake. After many months, the WeChat applet came out, so I wrote it again when I had nothing to do. A small program version
Please be sure to read the following paragraph
The author is working on iOS, and most of the small programs are front-end knowledge. The author has never done similar development before , so the code writing is quite bad. Many things were written while checking information. Please feel free to comment, Amen!
Get to the point
Page layout
I won’t introduce the mini program. The official document has detailed documents, so let’s take a look at the picture first
This is what it looks like. The game interface is similar to the previous OC version. With the author's level, I can only design it like this. After all, I am not a professional. Why does this snake look like this? A J (harmony) ah:joy:
Let’s first take a look at the wxml file used to add components
<view class="backView"> <canvas canvas-id="snakeCanvas" class="canvas"/> </view> <view class="controlView"> <button class="btnClass" bindtap="changeDirection" id="up">up</button> <view style="display:flex; height:33.33%"> <button class="btnClass" bindtap="changeDirection" id="left">left</button> <button class="btnClass" bindtap="startGame" >{{btnTitle}}</button> <button class="btnClass" bindtap="changeDirection" id="right">right</button> </view> <button class="btnClass" bindtap="changeDirection" id="down">down</button> </view>
The content is quite simple, there is a view above, and a view inside Canvas, below is a view with 5 buttons
Let’s take a look at the wxss layout
content Not much. In fact, the author doesn’t know much about CSS. I learned it many years ago, but it was eliminated with :hankey:. There may be a better layout method, but I’ll just make do with it.
Function Implementation
The layout is still very simple. Although I am not familiar with it, I can still figure it out after a few more attempts. The next step is to implement the functional logic. The programming language is of course js.
By the way, when I was learning js, I wrote a book full of notes, but... forget it, let the past go by, and don’t mention the past.
The idea is actually the same as the OC version
Snake: Create a point coordinate array, and then draw a rectangle on the canvas with the coordinate point as the center
Food: Randomly coordinate a point , the point cannot be on the snake, otherwise it will be randomly re-randomly
Movement of the snake: just move the coordinates of the snake's tail in front of the snake's head
Eating food: After each snake moves, if the snake's head The coordinates are the same as the coordinates of the food, then the snake grows
Growth of the snake: Add a point coordinate behind the snake's tail
The game ends: the snake's head crosses the boundary or hits its own body, the game ends
Create snake
//创建蛇,初始为5节,nodeWH为矩形的边长 function createSnake(){ nodes.splice(0, nodes.length) //清空数组 for (var i = 4; i >= 0; i--) { var node = new Node(nodeWH * (i + 0.5), nodeWH * 0.5) nodes.push(node); } }
Create food
function createFood(){ //矩形的边长为10,画布宽度为250,高度为350,所以x只能取5-245,y只能取5-345 var x = parseInt(Math.random() * 24) * nodeWH + nodeWH * 0.5 var y = parseInt(Math.random() * 34) * nodeWH + nodeWH * 0.5 //如果食物的坐标在蛇身上,则重新创建 for (var i = 0; i < nodes.length; i++) { var node = nodes[i] if (node.x == x && node.y == y) { createFood() return } } //Node为自定义的类,有两个属性x和y,表示坐标 food = new Node(x,y) }
Movement of snake
The movement of snake has a direction, so a variable direction is used to record the movement of snake Direction, when the game starts, the default is to move to the right.
It is mentioned above that the movement of the snake is to move the coordinates of the snake's tail to the front of the snake's head, but this front is not fixed, but is judged based on the direction. If it moves to the right, the right side is the front. Analogy
Eating food and snake growth
After each movement, it is OK to judge whether the coordinates of the snake head are equal to the coordinates of the food. After eating food, the length of the snake will increase, and To create a new food
function isEatedFood(){ var head = nodes[0] if (head.x == food.x && head.y == food.y) { score++ nodes.push(lastPoint) createFood() } }
In the above code, lastPoint is the coordinate of the snake's tail before each movement of the snake. If food is eaten after moving, then add a section directly to the tail of the snake before moving. But
Game ends
After each move, you must determine whether the snake head exceeds the canvas or hits your own body
function isDestroy(){ var head = nodes[0] //判断是否撞到自己身体 for (var i = 1; i < nodes.length; i++) { var node = nodes[i] if (head.x == node.x && head.y == node.y) { gameOver() } } //判断水平方向是否越界 if (head.x < 5 || head.x > 245) { gameOver() } //判断垂直方向是否越界 if (head.y < 5 || head.y > 345) { gameOver() } }
Interface drawing
Each time Each movement has to be drawn, so a timer is needed. The setInterval
function move(){ lastPoint = nodes[nodes.length - 1] var node = nodes[0] var newNode = {x: node.x, y: node.y} switch (direction) { case 'up': newNode.y -= nodeWH; break; case 'left': newNode.x -= nodeWH; break; case 'right': newNode.x += nodeWH; break; case 'down': newNode.y += nodeWH; break; } nodes.pop() nodes.unshift(newNode) moveEnd() } function startGame() { if (isGameOver) { direction = 'right' createSnake() createFood() score = 0 isGameOver = false } timer = setInterval(move,300) }
I used says online that the performance of setInterval is not very good. It is recommended to use requestAnimationFrame, but unfortunately, I don’t know how to use it. To be precise, it is I don’t know how to pause
var animateId = 0 function move(){ . . . animateId = requestAnimationFrame(move) } function startGame(){ . . . animateId = requestAnimationFrame(move) }
Using the above method can realize the movement of the snake and the redrawing of the interface. However, every time animateId is executed, it will be given a new value, so it cannot be paused using cancelAnimationFrame(animateId). If you know the front-end The master of development, please give me some guidance.
Almost the whole logic is like this. If you like to research, you can try it yourself
[Related recommendations]
1. Share a use Snake special effects code implemented in html5
2. Code example of writing a snake game using Python
3. Java to realize greedy Snake code example
4. [HTML5 Code Art] Snake game with 17 lines of code
5. JavaScript is simple and greedy Snake, basic object-oriented
The above is the detailed content of WeChat Mini Program-Snake Tutorial Example. 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

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.
