4.13更新:
介于之前版本的效果不理想,换了一个思路来完成2048
1、游戏逻辑上,是根据滑动方向改变数组:遍历数组,根据方向逐个移动,每当遇到方块,判断能加与否。并且加了的方块不能再加。
2、游戏动画上,之前用了animation,发现要清除之前的动画,会发生闪烁。所以改用画布。难点是画布的动画定时器。
----------------------------------------------------------------------------------------------------------------------------
原文:
页面布局,先写大致框架,再完善细节。
1、一个view中并排显示多个view,需要将父级的css设置为 display: flex;flex-direction: row;
2、生成0到3的随机整数:random = Math.floor(Math.random()*4);
3、随机生成2或4,2的几率比4大:value = Math.random() < 0.9 ? 2 : 4;
4、wx:for 的嵌套循环。修改数组后,需要将数组的值保存,如下
this
.setData({
cells: cells,
})
在视图中,遍历数组并生成控件
<
view
wx:for
=
"{{cells}}"
wx:for-item
=
"i"
wx:key
=
"key"
class
=
"grid-row">
<
view
class
=
'{{j?"":"none"}} grid-cell'
wx:for
=
"{{i}}"
wx:for-item
=
"j"
wx:key
=
"key">
{{j}}
</
view
>
</
view
>
5、打印数组:cosole.Log(数组名);
6、在游戏区域,放两层view,设置底层的css属性为 z-index:1; 顶层的css属性为 z-index:2;
7、在手机扫描预览时,滑动屏幕,整个界面也会滑动,就得添加如下配置:
8、缩放动画:获取到新增和被加的方块位置,添加缩放动画
这是方块层的xml
<
view
class
=
"tile-container">
<
view
wx:for
=
"{{tile}}"
wx:for-item
=
"i"
wx:key
=
"key"
wx:for-index
=
"idx1">
<
view
wx:for
=
"{{i}}"
wx:for-item
=
"value"
wx:key
=
"key"
class
=
'{{value?"":"blank"}} tile'
wx:for-index
=
"idx2"
animation
=
"{{tile_active[idx1][idx2]?animation:''}}">
<
view
wx:if
=
"{{value == 2}}"
class
=
'tile-2'
>
2
</
view
>
<
view
wx:if
=
"{{value == 4}}"
class
=
'tile-4'
>
4
</
view
>
<
view
wx:if
=
"{{value == 8}}"
class
=
'tile-8'
>
8
</
view
>
<
view
wx:if
=
"{{value == 16}}"
class
=
'tile-16'
>
16
</
view
>
<
view
wx:if
=
"{{value == 32}}"
class
=
'tile-32'
>
32
</
view
>
<
view
wx:if
=
"{{value == 64}}"
class
=
'tile-64'
>
64
</
view
>
<
view
wx:if
=
"{{value == 128}}"
class
=
'tile-128'
>
128
</
view
>
<
view
wx:if
=
"{{value == 256}}"
class
=
'tile-256'
>
256
</
view
>
<
view
wx:if
=
"{{value == 512}}"
class
=
'tile-512'
>
512
</
view
>
<
view
wx:if
=
"{{value == 1024}}"
class
=
'tile-1024'
>
1024
</
view
>
<
view
wx:if
=
"{{value == 2048}}"
class
=
'tile-2048'
>
2048
</
view
>
</
view
>
</
view
>
</
view
>
这是添加的js动画
//初始化动画
initAnimation:
function
(){
this
.animation = wx.createAnimation({
//缩放动画的设置
duration:
50
,
timingFunction:
'ease'
,
delay:
0
,
transformOrigin:
'center center 0'
,
})
},
//缩放动画
scale:
function
() {
this
.animation.scale3d(
0.9
,
0.9
,
0.9
).step().scale3d(
1.1
,
1.1
,
1.1
).step().scale3d(
1
,
1
,
1
).step()
this
.setData({
animation:
this
.animation.export()
})
},
然后再滑动结束时,调用动画