微信小程序翻牌游戏如何做,微信小程序翻牌游戏实现效果
2018-09-20
导读:背景 ps:本次开发基于wepy框架 由于最近接到一个需求--抽奖活动; 翻牌打乱活动抽奖活动,大概需求是这样的,九宫格卡牌,先正面展示所有奖品,然后卡牌翻转,打乱排序,点击卡...
背景
ps:本次开发基于wepy框架
由于最近接到一个需求--抽奖活动;
翻牌打乱活动抽奖活动,大概需求是这样的,九宫格卡牌,先正面展示所有奖品,然后卡牌翻转,打乱排序,点击卡牌,然后抽奖。
这个需求本身其实不难,主要是分为三步;
-
展示所有卡牌,然后翻转。
-
打乱所有卡牌
-
点击其中一张卡牌,抽奖
第一步:卡牌翻转
我们先在dom中渲染9个卡牌。
-
{{cardItem.front}} -
{{cardItem.back}}
script
-
allMove () {
-
// 110 是卡牌宽度加边距
-
this.methods.shuffle.call(this, 110)
-
let timer = setTimeout(() => {
-
clearTimeout(timer)
-
this.methods.shuffle.call(this, 0)
-
this.$apply()
-
}, 1000)
-
},
-
// 洗牌
-
shuffle (translateUnit) {
-
let curCardData = this.cardData
-
curCardData.map((item, index) => {
-
let animation = wepy.createAnimation({
-
duration: 500,
-
timingFunction: 'ease'
-
})
-
animation.export()
-
switch (index) {
-
case 0:
-
animation.translate(translateUnit, translateUnit).step()
-
break
-
case 1:
-
animation.translate(0, translateUnit).step()
-
break
-
case 2:
-
animation.translate(-translateUnit, translateUnit).step()
-
break
-
case 3:
-
animation.translate(translateUnit, 0).step()
-
break
-
case 4:
-
animation.translate(0, 0).step()
-
break
-
case 5:
-
animation.translate(-translateUnit, 0).step()
-
break
-
case 6:
-
animation.translate(translateUnit, -translateUnit).step()
-
break
-
case 7:
-
animation.translate(0, -translateUnit).step()
-
break
-
case 8:
-
animation.translate(-translateUnit, -translateUnit).step()
-
break
-
}
-
item.animationData = animation.export()
-
})
-
this.cardData = curCardData
-
this.$apply()
-
},
算法后面需要优化,我们先完成功能效果,
第三步:卡牌翻转
dom代码
-
{{cardItem.front}} -
{{cardItem.back}}
script代码
-
data中定义一个curIndex = -1的对象
-
data = {
-
curOpen: -1,
-
}
-
methods = {
-
// 抽奖
-
itemChage (item, curIndex) {
-
this.cardData[curIndex].front = 'iphone x'
-
console.log(item, curIndex)
-
this.curOpen = curIndex
-
}
-
}
less
-
.card.getprize{
-
.front{
-
z-index:2;
-
transform: rotateY(0deg);
-
}
-
.back{
-
z-index:1;
-
transform: rotateY(180deg);
-
}
-
}
现在我们就已经完成了基本的需求;但是在位移动画时候代码写的太丑陋了。
我们来想想怎么优化算法;
我们现在就九宫格布局,我们可以看成是二维布局
那我们是不是可以在卡牌中也使用二维数组布局属性
-
resetData () {
-
const total = 9 // 总数
-
const lineTotal = 3 // 单行数
-
curCardData.map((item, index) => {
-
let curCardData = this.cardData
-
let x = index % lineTotal
-
let y = parseInt(index / lineTotal)
-
item.twoArry = {x, y}
-
})
-
}
在位移动画中使用二维布局的差值进行位移
-
// 洗牌
-
shuffle (translateUnit) {
-
let curCardData = this.cardData
-
curCardData.map((item, index) => {
-
let animation = wepy.createAnimation({
-
duration: 500,
-
timingFunction: 'ease'
-
})
-
animation.export()
-
const translateUnitX = translateUnit * (1 - item.twoArry.x)
-
const translateUnitY = translateUnit * (1 - item.twoArry.y)
-
animation.translate(translateUnitX, translateUnitY).step()
-
item.animationData = animation.export()
-
})
-
this.cardData = curCardData
-
this.$apply()
-
},
这样整个动画就算完成了,
第二部分:如何开通一个小商店