简单的微信小程序拼图游戏的代码

首先,在你的小程序页面的js文件中,定义拼图游戏相关的数据和方法:

Page({
  data: {
    puzzle: [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, -1] // -1代表空白格
    ]
  },

  onLoad: function () {
    // 初始化拼图
    this.shufflePuzzle();
  },

  shufflePuzzle: function () {
    // 随机打乱拼图数组,保证可还原
    // 这里只是一个示例的打乱方法,具体可以根据需求自行修改
    for (let i = this.data.puzzle.length - 1; i > 0; i--) {
      for (let j = this.data.puzzle[i].length - 1; j > 0; j--) {
        const m = Math.floor(Math.random() * (i + 1));
        const n = Math.floor(Math.random() * (j + 1));
        [this.data.puzzle[i][j], this.data.puzzle[m][n]] = [this.data.puzzle[m][n], this.data.puzzle[i][j]];
      }
    }

    // 更新拼图数据
    this.setData({
      puzzle: this.data.puzzle
    });
  },

  moveTile: function (event) {
    const row = event.currentTarget.dataset.row;
    const col = event.currentTarget.dataset.col;

    // 判断是否可以移动
    if (this.data.puzzle[row][col] === -1) {
      return;
    }

    // 上下左右四个方向的相邻坐标
    const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    // 遍历四个方向,查找空白格
    for (const direction of directions) {
      const newRow = row + direction[0];
      const newCol = col + direction[1];

      // 判断新坐标是否越界
      if (newRow >= 0 && newRow < this.data.puzzle.length && newCol >= 0 && newCol < this.data.puzzle[newRow].length) {
        // 找到空白格,交换位置
        if (this.data.puzzle[newRow][newCol] === -1) {
          [this.data.puzzle[row][col], this.data.puzzle[newRow][newCol]] = [this.data.puzzle[newRow][newCol], this.data.puzzle[row][col]];
          this.setData({
            puzzle: this.data.puzzle
          });
          break;
        }
      }
    }

    // 判断游戏是否完成
    if (this.checkWin()) {
      wx.showToast({
        title: '恭喜你完成拼图!',
        icon: 'success',
        duration: 2000
      });
    }
  },

  checkWin: function () {
    // 遍历拼图数组,检查每个数字是否按顺序排列
    let currentNum = 1;

    for (const row of this.data.puzzle) {
      for (const num of row) {
        if (num !== currentNum) {
          return false;
        }
        currentNum++;
      }
    }
    
    return true;
  }
})

然后,在你的小程序页面的wxml文件中,添加拼图的界面和事件绑定:

<view class="puzzle">
  <view class="row" wx:for="{
   
   {puzzle}}" wx:for-item="row" wx:for-index="rowIndex">
    <view class="cell" wx:for="{
   
   {row}}" wx:for-item="cell" wx:for-index="colIndex" 
          bindtap="moveTile" data-row="{
   
   {rowIndex}}" data-col="{
   
   {colIndex}}">
      <text wx:if="{
   
   {cell !== -1}}">{
   
   {cell}}</text>
    </view>
  </view>
</view>

最后,使用CSS样式来美化拼图的外观。你可以在CSS文件中定义相关样式,例如:

.puzzle {
  display: flex;
  flex-wrap: wrap;
  width: 300rpx;
  height: 300rpx;
}

.row {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100rpx;
}

.cell {
  display: flex;
  justify-content: center;
  align-items:

猜你喜欢

转载自blog.csdn.net/m0_57790713/article/details/131750168