Home > WeChat Applet > Mini Program Development > Implement a lucky wheel game in WeChat mini program

Implement a lucky wheel game in WeChat mini program

coldplay.xixi
Release: 2020-11-11 17:34:08
forward
3807 people have browsed it

WeChat Mini Program Development Tutorial column introduces the implementation of the Lucky Spin mini game.

Implement a lucky wheel game in WeChat mini program

I mainly introduce how to develop a lucky wheel game in the WeChat applet, which mainly uses javascript and css syntax, you can easily implement a simple lucky wheel (take 6 prize areas as an example). Of course, if you have a better implementation plan, please leave a message in the comment area.

Preface

This tutorial requires you to master a certain amount of javascript and css basic knowledge, and you need to have certain experience in developing small programs. The specific knowledge points that need to be mastered are:

  • css position, transform, transition, overflow
  • javascript basic random algorithm
  • wxs syntax
  • small Program built-in animation api

Rendering

Small program

Development idea

There are three parts to the development idea , the first part is to use css to draw the turntable background, the second part is to use the wxs syntax to implement responsive styles, and the third part is to realize the rotation of the turntable through the built-in animation API of the mini program and the randomness of the rotation through js.

I mainly introduce the writing ideas, and I will start my explanation below.

How to draw a triangle

At the beginning, we need to write a basic wxml framework.

<view class="turntable">
  <view class="wrapper">
    <view class="item" >
	  <view class="item-inner">
		<text>10分</text>
	  </view>
	</view>
  </view>
</view>复制代码
Copy after login

I drew two rectangles of the same size, with the length and width being 300rpx and 600rpx respectively. I used the position css attribute to merge the two rectangles together.

.turntable {
  display: block;
  width: 100%;
  height: 600rpx;
}
.turntable .wrapper{
  position: relative;
  transform-origin: center;
  width: 100%;
  height: 600rpx;
}复制代码
Copy after login

After merging, I need to separate the two cuboids and turn the red cuboid into a semicircle. The blue cuboid swings 60 degrees clockwise and the red cuboid swings counterclockwise. 30 degrees, why does it turn like this? Because the blue originally swings 30 degrees counterclockwise with the red, and the internal angle of a triangle is 60 degrees. In order to form this 60-degree angle, I need to move the blue clockwise after the red is placed. 60 degrees, thus forming a 60-degree angle.

.turntable .wrapper .item {
  position: absolute;
  left: 50%;
  width: 300rpx;
  height: 600rpx;
  border-radius: 0px 300rpx 300rpx 0;
  transform-origin: left center;
  transform: rotate(-30deg);
}
.turntable .wrapper .item .item-inner {
  text-align: center;
  width: 300rpx;
  height: 600rpx;
  transform: translateX(-300rpx) rotate(60deg); 
  transform-origin: right center;
  border-radius: 300rpx 0 0 300rpx;
  font-size: 32rpx;
}复制代码
Copy after login

The next key step is to add the overflow: hidden attribute at item, a triangle will appear, and adjust the font s position.

.turntable .wrapper .item {
  position: absolute;
  left: 50%;
  width: 300rpx;
  height: 600rpx;
  border-radius: 0px 300rpx 300rpx 0;
  overflow: hidden;
  transform-origin: left center;
}
.turntable .wrapper .item .item-inner text {
  display: block;
  transform-origin: center;
  transform: translateY(100rpx) translateX(43rpx) rotate(-30deg);
}复制代码
Copy after login

After a triangle is drawn, 6 triangles of equal size can be spliced ​​together to form a disk. You only need to modify the rotation angle of each triangle. That’s it.

.turntable .wrapper .item:nth-child(1) {
  transform: rotate(-30deg);
}

.turntable .wrapper .item:nth-child(2) {
  transform: rotate(-90deg);
}

.turntable .wrapper .item:nth-child(3) {
  transform: rotate(-150deg);
}

.turntable .wrapper .item:nth-child(4) {
  transform: rotate(-210deg);
}

.turntable .wrapper .item:nth-child(5) {
  transform: rotate(-270deg);
}

.turntable .wrapper .item:nth-child(6) {
  transform: rotate(-330deg);
}复制代码
Copy after login

Implement responsive style

In order to better adapt to different business needs, I changed the style of the carousel into responsive style, so that I can easily adjust the style according to the length of the prize data passed in from the outside. To set different styles, I put the judgment of this step in the wxs module.

<wxs module="computed">
	var rotate = function (index, length) {
		var inital = - (360 / length / 2)
		var averageRotate = 360 / length
		var deg = inital - averageRotate * index
		return 'transform: rotate(' + deg + 'deg);'
	}
	var inner = function (length) {
		var averageRotate = 360 / length
		return 'transform: translateX(-300rpx) rotate(' + averageRotate + 'deg);'
	}
	var text = function (length) {
		var distance = 0
		var rotate = 0
		switch (length) {
			case 6:
				distance = 43
				rotate = 30
				break
			case 8:
				distance = 72
				rotate = 30
				break
			case 4:
				distance = -20
				rotate = 40
				break
		}
		return 'transform: translateY(100rpx) translateX(' + distance + 'rpx) rotate(-45deg);'
	}
	module.exports = {
		rotate: rotate,
		inner: inner,
		text: text
	}
</wxs>复制代码
Copy after login

Animation system and winning system

By setting the winning rate and calculating a circle as 360 degrees, a winning range of 0-360 is obtained, and the randomly obtained Use the number to determine which interval value it belongs to, and use the interval value reward to determine the angle at which the disk needs to rotate. The idea is roughly like this. Let’s start to explain the main ideas.

圆盘要转的角度 = reward * 一个圆分成6块的平均值  + 3 * 360复制代码
Copy after login

First, set the winning rates of the 6 prize areaswinning. The winning rates should add up to 1. Combine the initialized data into a 6-digit array from the component Passed out into the component.

prize: [{
        'name': '1分',
        'winnning': 0.2,
        'count': 1
      },
      {
        'name': '谢谢参与',
        'winnning': 0.5,
        'count': 0
      }, {
        'name': '5分',
        'winnning': 0.05,
        'count': 5
      }, {
        'name': '7分',
        'winnning': 0.05,
        'count': 7
      }, 
      {
        'name': '3分',
        'winnning': 0.1,
        'count': 3
      }, 
      {
        'name': '4分',
        'winnning': 0.1,
        'count': 4
      }
    ],复制代码
Copy after login

Using a circle as 360 degrees to calculate the winning value range of 0-360.

getRange(winning) {
   let temp = []
     winning.forEach((item, index) => {
       if (index === 0) {
         temp.push(item['winnning'] * 360)
       } else {
         temp.push(parseInt(temp.slice(-1)) + item['winnning'] * 360)
       }
      })
      return temp
    },复制代码
Copy after login

Generate a random integer. Of course, this number must be between 0-360, otherwise it will be meaningless if it exceeds 360 or is less than 0.

let random = Math.round(Math.random() * 360)复制代码
Copy after login

After obtaining the random number, determine which prize range it is within and assign the corresponding interval value to the response number reward .

for (let i in winningRange) {
    let currentwinning = winningRange[i] // 当前取值
       if (random < currentwinning) {
          this.setData({
            reward: i
          })
          break
      } else {
        if (i == 0) {
           continue
        }
        if (random >= winningRange[i - 1] && random <= currentwinning) {
           this.setData({
              reward: i
           })
           break
       }
     }
}复制代码
Copy after login

Place the main function of clicking to start in onPoint(). At the beginning of the function, it is necessary to determine whether there is still a lottery opportunity and prevent the animation from being executed by clicking the function again. After calculation, Use the animation api animation of the WeChat applet to rotate the disk at the required angle. After the animation ends, the winning information is triggered through the custom component to allow the event to be monitored outside the component.

onPoint() {
      // 平均值
      const averageRotate = 360 / this.properties.prize.length
      // 是否有抽奖机会
      if (this.properties.chance === 0) {
        this.triggerEvent('none')
        return
      }
      // 防止转动时点击开始按钮
      if (!this.data.onRotation) {
        this.setData({
          onRotation: true
        })
        this.getReward()
        let deg = this.data.reward * averageRotate + 3 * 360  // 至少3圈以上
        this.animate('.wrapper', [{
            rotate: 0,
            ease: 'ease-in-out'
          },
          {
            rotate: deg,
            ease: 'ease-in-out'
          }
        ], 5000, function () {
          this.setData({
            onRotation: false
          })
          // 发送自己的抽奖信息
          this.triggerEvent('onResult', this.properties.prize[this.data.reward])
        }.bind(this))
      }
    },复制代码
Copy after login

Finally, don’t forget to perform the animation reset action before each execution of the animation to ensure that the animation goes to the correct angle next time. Of course I put it inside a function so that it can be used outside the component.

onClear(){
   this.clearAnimation('.wrapper')
}复制代码
Copy after login

最后

整个思路就这些,怎么样,是不是很简单呢?实现关键一步是绘制圆盘,只要这一步搞好了,其他就会简单很多,因为动画实现那部分,微信小程序已经帮我们全部弄好了。最后,如果有更好的方法,欢迎在评论讨论一下。

相关免费学习推荐:微信小程序开发教程

The above is the detailed content of Implement a lucky wheel game in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
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