WeChat applet implements jigsaw puzzle game

WeChat applet implements jigsaw puzzle game

This article shares the specific code for implementing a jigsaw puzzle game in a WeChat applet for your reference. The specific content is as follows

Page display

Project Link

WeChat applet implements jigsaw puzzle game

Project Design

Home

wxml

<!--index.wxml-->
<view class="container">
  <!-- Title -->
  <view class="title">Game level selection</view>

  <!-- Level List -->
  <view class="levelBox">
    <view class="box" wx:for="{{levels}}" wx:key="levels{{index}}" bindtap="chooseLevel" data-level="{{item}}">
      <image src="/images/{{item}}"></image>
      <text>Level {{index+1}}</text>
    </view>
  </view>

</view>

wxss

/**index.wxss**/
/* Level area list */
.levelBox{
  width: 100%;
}

/* Single level area */
.box{
  width: 50%;
  float: left;
  margin: 25rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/*Level selection picture*/
image{
  width: 260rpx;
  height: 260rpx;
}
//index.js
Page({

  /**
   * Initial data of the page */
  data: {
    levels: [
      'pic01.jpg',
      'pic02.jpg',
      'pic03.jpg',
      'pic04.jpg',
      'pic05.jpg',
      'pic06.jpg'
    ]

  },

  /**
   * Custom function -- game level selection */
  chooseLevel: function(e) {
    // console.log(e.currentTarget.dataset.level)
    // Get the level selection image let level = e.currentTarget.dataset.level

    // Jump to the game page wx.navigateTo({
      url: '../game/game?level='+level,
    })

  },
})

Game Page

wxml

<!--pages/game/game.wxml-->
<view class="container">
  <!-- Top Tip Picture -->
  <view class="title">Prompt Image</view>
  <image src="{{url}}"></image>

  <!-- Game Area -->
  <canvas canvas-id="myCanvas" bindtouchstart="touchBox"></canvas>

  <!-- Restart Button -->
  <button type="warn" bindtap="restartGame">Restart</button>
</view>

wxss

/* pages/game/game.wxss */
/* Prompt image*/
image{
  width: 250rpx;
  height: 250rpx;
}

/* Game canvas area */
canvas{
  border: 1rpx solid;
  width: 300px;
  height: 300px;
}

js

// pages/game/game.js
// The initial position of the block var num = [
  ['00', '01', '02'],
  ['10', '11', '12'],
  ['20', '21', '22']
]

// The width of the block var w = 100

// The initial address of the picture var url = '/images/pic01.jpg'

Page({

  /**
   * Initial data of the page */
  data: {
    isWin: false

  },

  /**
   * Custom function - randomly disrupt the order of blocks */
  shuffle: function() {
    // First return all blocks to their initial positions num = [
      ['00', '01', '02'],
      ['10', '11', '12'],
      ['20', '21', '22']
    ]

    // Record the row and column of the current blank square var row = 2
    var col = 2

    // Randomly shuffle the order of blocks 100 times for (var i = 0; i < 100; i++) {
      // Randomly generate a direction: up 0, down 1, left 2, right 3
      var direction = Math.round(Math.random() * 3)

      // Up: 0
      if (direction == 0) {
        // The blank square cannot be in the top row if (row != 0) {
          // Swap positions num[row][col] = num[row - 1][col]
          num[row - 1][col] = '22'

          // Update the row of the blank square row -= 1
        }
      }

      // Next: 1
      if (direction == 1) {
        // The blank square cannot be in the bottom row if (row != 2) {
          // Swap positions num[row][col] = num[row + 1][col]
          num[row + 1][col] = '22'

          // Update the row of the blank square row += 1
        }
      }

      // Left: 2
      if (direction == 2) {
        // Blank squares cannot be in the leftmost column if (col != 0) {
          // Swap positions num[row][col] = num[row][col - 1]
          num[row][col - 1] = '22'

          // Update the blank square column col -= 1
        }
      }

      // Right: 3
      if (direction == 3) {
        // Blank squares cannot be in the rightmost column if (col != 2) {
          // Swap positions num[row][col] = num[row][col + 1]
          num[row][col + 1] = '22'

          // Update the blank square column col += 1
        }
      }

    }

  },

  /**
   * Custom function - draw canvas content */
  drawCanvas: function() {
    let ctx = this.ctx

    // Clear the canvas ctx.clearRect(0, 0, 300, 300)

    // Use double for loop statement to draw 3x3 puzzle for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        if (num[i][j] != '22') {
          // Get the row and column var row = parseInt(num[i][j] / 10)
          var col = num[i][j] % 10

          // Draw the square ctx.drawImage(url, col * w, row * w, w, w, j * w, i * w, w, w)
        }
      }
    }

    ctx.draw()
  },

  /**
   * Custom function - listen for click block events*/
  touchBox: function(e) {
    // If the game is already successful, do nothing if (this.data.isWin) {
      //Terminate this function return
    }

    // Get the x and y coordinates of the clicked block
    var x = e.changedTouches[0].x
    var y = e.changedTouches[0].y
    // console.log('x:'+x+',y:'+y)

    // Convert to rows and columns var row = parseInt(y / w)
    var col = parseInt(x / w)

    // If the clicked position is not blank if (num[row][col] != '22') {
      // Try to move the box this.moveBox(row, col)

      // Redraw the canvas content this.drawCanvas()

      // Determine whether the game is successful if (this.isWin()) {
        // Draw prompt statement on the screen let ctx = this.ctx

        // Draw the complete picture ctx.drawImage(url, 0, 0)

        // Draw text ctx.setFillStyle('#e64340')
        ctx.setTextAlign('center')
        ctx.setFontSize(60)
        ctx.fillText('Game success', 150, 150)
        ctx.draw()
      }
    }
  },

  /**
   * Custom function - move the clicked block */
  moveBox: function(i, j) {
    // Case 1: If the clicked block is not at the top, check whether it can be moved up if (i > 0) {
      // If the top of the block is blank if (num[i - 1][j] == '22') {
        // Swap the currently clicked block with the blank position num[i - 1][j] = num[i][j]
        num[i][j] = '22'
        return
      }
    }

    // Case 2: If the clicked block is not at the bottom, check whether it can be moved down if (i < 2) {
      // If the area below the block is empty if (num[i + 1][j] == '22') {
        // Swap the currently clicked block with the blank position num[i + 1][j] = num[i][j]
        num[i][j] = '22'
        return
      }
    }

    // Case 3: If the clicked block is not on the far left, check whether it can be moved left if (j > 0) {
      // If the left side of the square is blank if (num[i][j - 1] == '22') {
        // Swap the currently clicked block with the blank position num[i][j - 1] = num[i][j]
        num[i][j] = '22'
        return
      }
    }

    // Case 4: If the clicked block is not on the far right, check whether it can be moved right if (j < 2) {
      // If the right side of the square is blank if (num[i][j + 1] == '22') {
        // Swap the currently clicked block with the blank position num[i][j + 1] = num[i][j]
        num[i][j] = '22'
        return
      }
    }
  },

  /**
   * Custom function - determine whether the game is successful*/
  isWin: function() {
    // Use a double for loop to check the entire array for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        // If a block is in the wrong position if (num[i][j] != i * 10 + j) {
          // Return false, the game has not yet succeeded return false
        }
      }
    }

    // Game success, update status this.setData({
      isWin: true
    })
    // Return true, the game is successful return true
  },

  /**
   * Custom function - restart the game */
  restartGame: function() {
    // Update the game status this.setData({
      isWin: false
    })

    // Shuffle the order of blocks this.shuffle()

    // Draw the canvas content this.drawCanvas()
  },

  /**
   * Life cycle function--listen for page loading*/
  onLoad: function(options) {
    // console.log(options.level)

    // Update the image path address url = '/images/' + options.level
    // Update the address of the prompt image this.setData({
      url: url
    })

    // Create a canvas context this.ctx = wx.createCanvasContext("myCanvas")

    // Shuffle the order of blocks this.shuffle()

    // Draw the canvas content this.drawCanvas()
  },

  /**
   * Life cycle function - listen for the completion of the initial rendering of the page*/
  onReady: function() {

  },

  /**
   * Life cycle function--monitor page display*/
  onShow: function() {

  },

  /**
   * Life cycle function--listen for page hiding*/
  onHide: function() {

  },

  /**
   * Life cycle function--monitor page uninstallation*/
  onUnload: function() {

  },

  /**
   * Page related event processing function - listen to user pull-down action */
  onPullDownRefresh: function() {

  },

  /**
   * The function that handles the bottoming event on the page*/
  onReachBottom: function() {

  },

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

  }
})

I would like to recommend a WeChat Mini Program tutorial which is quite popular right now: "WeChat Mini Program Development Tutorial" which has been carefully compiled by the editor. I hope you like it.

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:
  • WeChat applet implements puzzle game

<<:  Detailed explanation of the underlying implementation method of Nginx polling algorithm

>>:  Summary of situations where MySQL indexes will not be used

Recommend

SQL uses ROW_NUMBER() OVER function to generate sequence number

Syntax: ROW_NUMBER() OVER(PARTITION BY COLUMN ORD...

Solve the problem of ifconfig being unavailable in docker

Recently, when I was learning docker, I found tha...

Detailed analysis of the chmod command to modify file permissions under Linux

Use the Linux chmod command to control who can ac...

Vue+thinkphp5.1+axios to realize file upload

This article shares with you how to use thinkphp5...

MySQL 8.0.20 Installation Tutorial with Pictures and Text (Windows 64-bit)

1: Download from mysql official website https://d...

react-beautiful-dnd implements component drag and drop function

Table of contents 1. Installation 2.APi 3. react-...

Thinking about grid design of web pages

<br />Original address: http://andymao.com/a...

Optimize the storage efficiency of BLOB and TEXT columns in InnoDB tables

First, let's introduce a few key points about...

Example of stars for CSS rating effect

What? What star coat? Well, let’s look at the pic...

How to use CSS to center a box horizontally and vertically (8 methods)

Original code: center.html : <!DOCTYPE html>...

Our thoughts on the UI engineer career

I have been depressed for a long time, why? Some t...

How to deploy Tencent Cloud Server from scratch

Since this is my first post, if there are any mis...