WeChat applet implements the snake game

WeChat applet implements the snake game

This article shares the specific code of the WeChat applet to implement the snake game for your reference. The specific content is as follows

1. Project screenshots

2. Source code

1. WXML

The code is as follows (example):

<view class='container'>
 <view class='content-bottom' bindtouchmove='touchMove' bindtouchstart='touchStart' bindtouchend='touchEnd'>
  <view wx:for="{{ground}}" wx:for-item="cols" class='ground-row'>
   <view wx:for="{{cols}}" class='ground-col'>
    <view class='block block{{item}}'></view>
   </view>   
  </view>
 </view>
 <view class='content-top'>
  <view class='top-item top-score'>
   <view class='score-description'>Score</view>
   <view class='score-number'>{{score}}</view>
  </view>
  <view class='top-item top-start' bindtap='goStart'>START</view>
  <view class='top-item top-score'>
   <view class='score-description'>Historical High</view>
   <view class='score-number'>{{maxScore}}</view>
  </view>
 </view>
</view>

2. WXSS

The code is as follows (example):

/* pages/demo/snake/snake.wxss */
.content-top {
 display: flex;
}
.top-item {
 flex: 1;
 height: 150rpx;
 margin: 0 20rpx;
 line-height: 150rpx;
 text-align: center;
 border-radius: 16rpx;
}
.top-start {
 font-size: 22px;
 background: deepskyblue;
 color: #fff;
}
.top-score {
 background: #eee4da;
}
.score-description {
 line-height: 70rpx;
}
.score-number {
 line-height: 60rpx;
}
.content-bottom {
 display: flex;
 flex-direction: column;
 width: 660rpx;
 height: 840rpx;
 margin: 50rpx auto 0;
}
.ground-row {
 display: flex;
}
.ground-col {
 flex: 1;
 width: 30rpx;
 height: 30rpx;
}
.block {
 width: 100%;
 height: 100%;
 background: #eee;
}
.block1 {
 background: black;
 border-radius: 5px;
}
.block2 {
 background:red;
 border-radius: 5px;
}

3.JS

The code is as follows (example):

// pages/demo/snake/snake.js
Page({

  /**
   * Initial data of the page */
  data: {
  gameStart: false, // Whether the game has started score: 0, // Current score maxScore: 0, // Highest score in history isMaxActive: false,
  rows: 28, // playground rows cols: 22, // playground columns ground: [[]], // playground block position snake: '', // snake position food: [], // food position startX: 0,
  startY: 0,
  endX: 0,
  endY: 0,
  flag: 0, // The current direction of the snake's movement, 0 for right, 1 for down, 2 for left, 3 for up timer: null,
  modaleHidden: true
  },

  /**
   * Life cycle function--listen for page loading*/
  onLoad: function (options) {
  this.initGround(this.data.rows, this.data.cols) // Initialize the playground console.log(wx.getStorageSync("MaxScore"))
  if (wx.getStorageSync("MaxScore")) {
   this.setData({
    maxScore: wx.getStorageSync("MaxScore"),
    isMaxActive: true
   })
  } else {
   this.setData({
    isMaxActive: false
   })
  }
  },

 goStart: function () {
  this.setData({
   gameStart: true
  })
  this.onLoad()
  this.initSnake(3) // Initialize the snake position this.initFood() // Initialize food
  this.move(0)
 },

 /**
  * Initialize the playground */
 initGround: function (rows, cols) {
  this.data.ground = []
  for (let i = 0; i < rows; i++) {
   let arr = []
   this.data.ground.push(arr)
   for (let j = 0; j < cols; j++) {
    this.data.ground[i].push(0)
   }
  }
  this.setData({
   ground: this.data.ground
  })
 },

 /**
  * Initialize the snake */
 initSnake: function (n) {
  this.data.snake = []
  for (let i = 0; i < n; i++) {
   this.data.ground[0][i] = 1
   this.data.snake.push([0,i])
  }
  this.setData({
   ground: this.data.ground,
   snake: this.data.snake
  })
 },

 /**
  * Initialize food
  */
 initFood: function () {
  let row = Math.floor(Math.random()*this.data.rows)
  let col = Math.floor(Math.random() * this.data.cols)
  var ground = this.data.ground
  ground[row][col] = 2
  this.setData({
   ground: ground,
   food: [row, col]
  })
  console.log(this.data.food)
 },

 /**
  * Determine the direction of mouse sliding */
 touchStart: function (event) {
  this.data.startX = event.touches[0].pageX
  this.data.startY = event.touches[0].pageY
 },

 touchMove: function (event) {
  this.data.endX = event.touches[0].pageX
  this.data.endY = event.touches[0].pageY
  // console.log(this.data.endX, this.data.endY)
 },

 touchEnd: function (event) {
  let tX = this.data.endX ? (this.data.endX - this.data.startX) : 0
  let tY = this.data.endY ? (this.data.endY - this.data.startY) : 0
  console.log(tX, tY)
  if (!this.data.gameStart) {
   return false
  }
  if (tY < 0 && Math.abs(tX) <= Math.abs(tY)) { // Slide down this.data.flag = 3
  } else if (tY > 0 && Math.abs(tX) <= Math.abs(tY)) { // Slide up this.data.flag = 1
  } else if (tX < 0 && Math.abs(tX) > Math.abs(tY)) { // Slide to the left this.data.flag = 2
  } else if (tX > 0 && Math.abs(tX) > Math.abs(tY)) { // Slide to the right this.data.flag = 0
  }
  if(this.data.modalHidden){
   this.move(this.data.flag)
  }  
 },
 /**
  * snake moves */
 move: function (state) {
  clearInterval(this.data.timer)
  // console.log(this.data.snake.length)
  var that = this
  switch(state){ // Determine the sliding direction case 0:
    this.data.timer = setInterval(function(){
     that.moveRight()
    }, 600)
    break
   case 1:
    this.data.timer = setInterval(function () {
     that.moveBottom()
    }, 600)
    break
   case 2:
    this.data.timer = setInterval(function () {
     that.moveLeft()
    }, 600)
    break
   case 3:
    this.data.timer = setInterval(function () {
     that.moveTop()
    }, 600)
    break
  }
 },

 moveRight: function () {
  // console.log(this.data.snake)
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0]
  var y = snakeHead[1] + 1

  if (y >= this.data.cols) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // Check if gameover
 },
 moveBottom: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0] + 1
  var y = snakeHead[1]

  if (x >= this.data.rows) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // Check if gameover
 },
 moveLeft: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0]
  var y = snakeHead[1] - 1

  if (y < 0) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // Check if gameover
 },
 moveTop: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0] - 1
  var y = snakeHead[1]

  if (x < 0) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  console.log(y)
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // Check if gameover
 },

 /**
  * Check gameover
  * Hitting the wall - game over, a pop-up box prompts whether to restart, reload
  * Hit yourself - gameover
  * Eat food - the snake's body becomes longer and regenerates food*/
 checkGame: function (snakeTail, snakeHead) {
  console.log("test snake movement")
  console.log(snakeHead)
  
  var snakeArrs = this.data.snake
  var len = this.data.snake.length
  var food = this.data.food
  var ground = this.data.ground

  console.log(this.data.snake[len-1])
  // Determine if there is a wall hit if (snakeHead[0] >= 0 & snakeHead[0] < this.data.rows & snakeHead[1] >= 0 & snakeHead[1] < this.data.cols)
  {   
   this.data.modalHidden = true
   this.collisionSnakeFood(snakeTail, snakeHead, food)
   this.setData({
    // snake: this.data.snakeArr,
    // ground: this.data.ground,
    modaleHidden: this.data.modaleHidden
   })
  } else {
   this.gameOver()
   return
  }
 },

 // Hit the food, the game continues collisionSnakeFood: function (tail, head, food) {
  let snake = this.data.snake
  let ground = this.data.ground
  let row = food[0]
  let col = food[1]
  let score = this.data.score
  let maxScore = this.data.maxScore
  if (head[0] === food[0] & head[1] === food[1]) {
   ground[row][col] = 1
   snake.unshift(tail)
   ground[tail[0]][tail[1]] = 1
   this.initFood()
   score += 5
   if (!this.data.isMaxActive) {
    maxScore = score
   }
  }
  this.setData({
   snake: snake,
   ground: ground,
   score: score,
   maxScore: maxScore
  })
 },

 // Game over gameOver: function () {
  clearInterval(this.data.timer)
  let _that = this
  let maxS = this.data.maxScore
  this.setData({
   modaleHidden: false,
   timer: null
  })
  if (wx.getStorageSync("MaxScore")){
   let hisScore = wx.getStorageSync("MaxScore")
   if (hisScore < maxS) {
    wx.setStorageSync("MaxScore", maxS)
   }
  } else {
   wx.setStorageSync("MaxScore", maxS)
  }
  wx.showModal({
   title: 'Game failed',
   content: 'Click OK to restart a new game; click Cancel to return to the home page',
   success: function(res) {
    if(res.confirm) {
     _that.setData({
      score: 0,
      gameStart: false, // Whether the game has started snake: '', // The position of the snake food: [], // The position of food modaleHidden: true
     })
     _that.onLoad()
    }
   }
  })
 },

  /**
   * User clicks on the upper right corner to share*/
  onShareAppMessage: function () {
  
  }
})

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Snake game implemented by WeChat applet [with source code download]

<<:  How to use & and nohup in the background of Linux

>>:  Comparing the performance of int, char, and varchar in MySQL

Recommend

Quick understanding of Vue routing navigation guard

Table of contents 1. Global Guard 1. Global front...

A brief introduction to mysql mycat middleware

1. What is mycat A completely open source large d...

How to embed flash video format (flv, swf) files in html files

Flash file formats: .FLV and .SWF There are two ex...

WeChat Mini Program video barrage position random

This article shares the specific code for randomi...

React + Threejs + Swiper complete code to achieve panoramic effect

Let’s take a look at the panoramic view effect: D...

Detailed explanation of the use of MySQL Online DDL

Table of contents text LOCK parameter ALGORITHM p...

Analysis of the difference between absolute path and relative path in HTML

As shown in the figure: There are many files conne...

Example of how to set automatic creation time and modification time in mysql

This article describes how to set the automatic c...

RGB color table collection

RGB color table color English name RGB 16 colors ...

CSS -webkit-box-orient: vertical property lost after compilation

1. Cause The requirement is to display two lines,...

vue+rem custom carousel effect

The implementation of custom carousel chart using...

How to implement encryption and decryption of sensitive data in MySQL database

Table of contents 1. Preparation 2. MySQL encrypt...

Detailed explanation of using JavaScript WeakMap

A WeakMap object is a collection of key/value pai...