# 微信小程序版2048实战教程

2018-01-24

## 逻辑实现

#### 2、判断用户滑动方向

`````` var disX = this.touchStartX - this.touchEndX;
var absdisX = Math.abs(disX);
var disY = this.touchStartY - this.touchEndY;
var absdisY = Math.abs(disY);

// 确定移动方向
// 0:上, 1:右, 2:下, 3:左
var direction = absdisX > absdisY ? (disX < 0 ? 1 : 3) : (disY < 0 ? 2 : 0);
``````

#### 3、根据滑动方向（假设向右滑动）移动表格以及相同项合并

``````// 比如棋盘数据如下
var grid = [
[2, 2, 0, 0],
[0, 0, 0, 0],
[0, 8, 4, 0],
[0, 0, 0, 0]
];
``````

``````var list = [
[0, 0, 2, 2],  // 注意是0022不是2200，因为像右滑动所以从右边push入数组
[0, 0, 0, 0],
[0, 4, 8, 0],
[0, 0, 0, 0]
];
``````

``````formList(dir) {  // 根据传入的滑动方向生成list的四个数组
var list = [[], [], [], []];
for(var i = 0; i < this.size; i++)
for(var j = 0; j < this.size; j++) {
switch(dir) {
case 0:
list[i].push(this.board.grid[j][i]);
break;
case 1:
list[i].push(this.board.grid[i][this.size-1-j]);
break;
case 2:
list[i].push(this.board.grid[this.size-1-j][i]);
break;
case 3:
list[i].push(this.board.grid[i][j]);
break;
}
}
return list;
}
``````

``````list2 = [
[2, 2, 0, 0],
[0, 0, 0, 0],
[4, 8, 0, 0],
[0, 0, 0, 0]
];
``````

``````changeItem(item) {  // 将 [0, 2, 0, 2] 改为 [2, 2, 0, 0]
var cnt = 0;
for(var i = 0; i < item.length; i++)
if(item[i] != 0)
item[cnt++] = item[i];
for(var j = cnt; j < item.length; j++)
item[j] = 0;
return item;
}
``````

``````list2 = [
[4, 0, 0, 0],
[0, 0, 0, 0],
[4, 8, 0, 0],
[0, 0, 0, 0]
];
``````

``````combine(list) { // 滑动时相同的合并
for(var i = 0; i < list.length; i++)  // 数字靠边
list[i] = this.changeItem(list[i]);

for(var i = 0; i < this.size; i++) {
for(var j = 1; j < this.size; j++) {
if(list[i][j-1] == list[i][j] && list[i][j]!=0) {
list[i][j-1] += list[i][j];
list[i][j] = 0;
}
}
}
for (var i = 0; i < list.length; i++)  // 再次数字靠边，避免0220变成0400的情况发生
list[i] = this.changeItem(list[i]);

return list;
}
``````

``````list = [
[0, 0, 0, 4],
[0, 0, 0, 0],
[0, 0, 8, 4],
[0, 0, 0, 0]
];
``````

``````move(dir) {
// 0:上, 1:右, 2:下, 3:左
var curList = this.formList(dir);

var list = this.combine(curList);
var result = [[],[],[],[]];

for(var i = 0; i < this.size; i++)
for(var j = 0; j < this.size; j++) {
switch (dir) {
case 0:
result[i][j] = list[j][i];
break;
case 1:
result[i][j] = list[i][this.size-1-j];
break;
case 2:
result[i][j] = list[j][this.size-1-i];
break;
case 3:
result[i][j] = list[i][j];
break;
}
}
this.board.grid = result;
this.setDataRandom();  // 移动一次之后随机用2或4填充两个单元格

return result;
}
``````

#### 5、判断游戏是否结束

``````isOver() {  // 游戏是否结束，结束条件：可用格子为空且所有格子上下左右值不等
for (var i = 0; i < this.size; i++) // 左右不等
for (var j = 1; j < this.size; j++) {
if (this.board.grid[i][j] == this.board.grid[i][j - 1])
return false;
}
for (var j = 0; j < this.size; j++)  // 上下不等
for (var i = 1; i < this.size; i++) {
if (this.board.grid[i][j] == this.board.grid[i - 1][j])
return false;
}
return true;
}
``````

#### 6、根据游戏结果给出相应提示

po一个源码地址：windlany/wechat-weapp-2048有兴趣的可以fork一下。