Home > WeChat Applet > WeChat Development > WeChat Mini Program-Snake Tutorial Example

WeChat Mini Program-Snake Tutorial Example

零下一度
Release: 2017-05-31 16:58:03
Original
6876 people have browsed it

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

WeChat Mini Program-Snake Tutorial Example

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>
Copy after login

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

WeChat Mini Program-Snake Tutorial Example

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);
  }
}
Copy after login

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)
}
Copy after login

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()
  }
}
Copy after login

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()
  }
}
Copy after login

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 &#39;up&#39;:
      newNode.y -= nodeWH;
    break;
    case &#39;left&#39;:
      newNode.x -= nodeWH;
    break;
    case &#39;right&#39;:
      newNode.x += nodeWH;
    break;
    case &#39;down&#39;:
      newNode.y += nodeWH;
    break;
  } 
  nodes.pop()
  nodes.unshift(newNode)
  moveEnd()
}

function startGame() {
  if (isGameOver) {
    direction = &#39;right&#39;
    createSnake()
    createFood()
    score = 0
    isGameOver = false
  }
  timer = setInterval(move,300)
}
Copy after login

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template