Go2048说明

游戏入口

创建应用

1
2
3
4
5
> npm create vite@latest

√ Project name: ... go2048
√ Select a framework: » Vue
√ Select a variant: » TypeScript

进入go2048目录,初始化工程

npm install

运行:

npm run dev

导入依赖

npm i -D @types/node

npm i -D unocss

npm i -D @iconify-json/carbon

npm i -D sass

npm i @vueuse/core

npm i guid-typescript

开发说明

Position 类定义

位置类中包含行,列属性,并提供位置移动,位置比较方法

Tile类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { Guid } from 'guid-typescript';
import Position from './Position';

export default class Tile {
id: string; //id
value: number; //值
position: Position; //位置信息
moveToPosition: Position; //移动目标位置信息
isEmpty: boolean; //是否是空格子

mergedOut: boolean; //是否是被合并格子(合并后消失)
mergedIn: boolean; //是否是合并格子(合并后值*2)

/**
* 构造函数
* @param position 位置信息
* @param value 值
* @param isEmpty 是否是空格子
*/
constructor(position: Position, value: number, isEmpty: boolean = false) {
this.id = Guid.create().toString();
this.value = value;
this.position = position;
this.moveToPosition = position;
this.isEmpty = isEmpty;
this.mergedOut = false;
this.mergedIn = false;
}

/**
* 合并处理
*/
merge(): void {
this.mergedIn = false;
this.value *= 2;
}

/**
* 是否需要移动判定
* @returns
*/
isNeedMove(): boolean {
return !this.position.equal(this.moveToPosition);
}

/**
* 清空为空格子
*/
clear(): void {
this.value = 0;
this.isEmpty = true;
this.moveToPosition = this.position;
this.mergedOut = false;
this.mergedIn = false;
}
}

Grid类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import Position from "./Position";
import Tile from "./Tile";

export default class Grid {
size: number; //大小
tiles: Array<Tile> = []; //格子

/**
* 初始化表格
* @param size 表格大小
*/
constructor(size: number) {
this.size = size;
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
this.tiles.push(new Tile(new Position(i, j), 0, true));
}
}
}

/**
* 是否在表格范围内
* @param position 位置
* @returns
*/
inBound(position: Position): boolean {
return position.row >= 0 &&
position.row < this.size &&
position.column >= 0 &&
position.column < this.size;
}

/**
* 产生一个新格子
*/
generateTile() {
const position: Position = this.randomAvailableCell();
const value: number = Math.random() < 0.7 ? 2 : 4;
let cell = this.tiles.filter((cell) => cell.position.equal(position))[0];
cell.value = value;
cell.isEmpty = false;
}

/**
* 删除指定格子
* @param tile 指定格子
*/
removeTile(tile: Tile) {
let cell = this.tiles.filter((cell) => cell.position.equal(tile.position))[0];
this.tiles.splice(this.tiles.indexOf(cell), 1, new Tile(tile.position, 0, true));
}

/**
* 给定位置是否是空格子
* @param position 给定位置
* @returns
*/
isAvailable(position: Position) {
let cell = this.tiles.filter((cell) => cell.position.equal(position))[0];
if (cell.isEmpty) {
return true;
}
return false;
}

/**
* 模拟移动后,给定位置是否是空格子
* @param position 给定位置
* @returns
*/
isAvailableAfterMove(position: Position) {
let cell = this.tiles.filter((cell) => cell.moveToPosition.equal(position))[0];
if (cell.isEmpty) {
return true;
}
return false;
}

/**
* 取得给定位置的格子信息
* @param position 给定位置
* @returns
*/
getTileByPosition(position: Position): Tile {
return this.tiles.filter((tile) => tile.position.equal(position))[0];
}

/**
* 模拟移动后,取得给定位置的格子信息
* @param position 给定位置
* @returns
*/
getTileByPositionAfterMove(position: Position): Tile {
return this.tiles.filter((tile) => tile.moveToPosition.equal(position))[0];
}

/**
* 随机确定一个空格子位置
* @returns 空格子位置
*/
randomAvailableCell(): Position {
let availableCells = this.tiles.filter((cell) => cell.isEmpty);
return availableCells[Math.floor(Math.random() * availableCells.length)].position;
}

/**
* 是否存在空格子
* @returns
*/
hasAvailableCells(): boolean {
let availableCells = this.tiles.filter((cell) => cell.isEmpty);
return availableCells.length > 0;
}

/**
* 将指定格子移动到指定位置
* @param tile 指定格子
* @param position 指定位置
* @returns
*/
moveTo(tile: Tile, position: Position) {
if (tile.position.equal(position)) {
return;
}
let from = this.tiles.indexOf(this.tiles.filter((cell) => cell.position.equal(tile.position))[0]);
let to = this.tiles.indexOf(this.tiles.filter((cell) => cell.position.equal(position))[0]);
const swapTile = this.tiles[from];
const swapPositon = swapTile.position;

this.tiles[from].position = position;
this.tiles[to].position = swapPositon;

this.tiles[from] = this.tiles[to];
this.tiles[to] = swapTile;
}

/**
* 模拟将指定格子移动到指定位置
* @param tile 指定格子
* @param position 指定位置
* @returns
*/
simulateMoveTo(tile: Tile, position: Position) {
if (tile.moveToPosition.equal(position)) {
return;
}
let from = this.tiles.indexOf(this.tiles.filter((cell) => cell.moveToPosition.equal(tile.position))[0]);
let to = this.tiles.indexOf(this.tiles.filter((cell) => cell.moveToPosition.equal(position))[0]);
const swapTile = this.tiles[from];
const swapPositon = swapTile.moveToPosition;

this.tiles[from].moveToPosition = position;
this.tiles[to].moveToPosition = swapPositon;
}

/**
* 打乱格子
*/
public resurrect() {
let temp = this.tiles.sort(() => { return Math.random() - 0.5; });
temp.forEach((tile, i) => {
tile.position.row = Math.floor(i / this.size);
tile.position.column = i - tile.position.row * this.size;
tile.moveToPosition = tile.position;
tile.mergedOut = false;
tile.mergedIn = false;
});
}
}

主处理类定义

核心代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

export default class MainManager {
//构造函数
constructor(config: GameConfig) {
...
}

//重新开始
public reStart(): void {
...
}

//随机产生一个新格子
private generateTile(): void {
...
}

//获得移动方向
private getDirection(key: string): Position {
let direction: Position = new Position(0, 0);
switch (key) {
case 'ArrowUp':
direction.row = -1;
break;
case 'ArrowDown':
direction.row = 1;
break;
case 'ArrowLeft':
direction.column = -1;
break;
case 'ArrowRight':
direction.column = 1;
break;
default:
console.error("Main Managere getDirection() should not accept key ", key);
return direction;
}
return direction;
}

//构造移动路径
private buildTraversal(direction: Position) {
let traversal: Array<Array<number>> = [];
for (let i = 0; i < 2; i++) {
traversal.push([]);
for (let j = 0; j < this.size; j++) {
traversal[i].push(j);
}
}
if (direction.row === 1) { traversal[0].reverse(); }
if (direction.column === 1) { traversal[1].reverse(); }
return traversal;
}

//移动处理
public async move(key: string) {
if (this.isMoving) {
return;
}
this.timing = '';
this.isMoving = true;
const direction = this.getDirection(key);
const traversal: Array<Array<number>> = this.buildTraversal(direction);

this.timing = 'beformove';
this.arrange(direction, traversal);
let isHaveNeedMoveTilesBefor = this.grid.tiles.some(tile => {
return !tile.isEmpty && tile.isNeedMove();
});
if (isHaveNeedMoveTilesBefor) {
this.events.moveCallback && this.events.moveCallback();
await this.moveAction(direction, traversal);
}

this.timing = 'beformerge';
let isHaveNeedMergeTiles = this.grid.tiles.some(tile => {
return !tile.isEmpty && tile.mergedOut;
});
if (isHaveNeedMergeTiles) {
await this.delay(200);
//merge
await this.mergeAction();
}

this.timing = 'aftermerge';
//after merge
this.arrange(direction, traversal, true);
let isHaveNeedMoveTilesAfter = this.grid.tiles.some(tile => {
return !tile.isEmpty && tile.isNeedMove();
});
if (isHaveNeedMoveTilesAfter) {
await this.moveAction(direction, traversal);
}

if (isHaveNeedMoveTilesBefor || isHaveNeedMergeTiles) {
this.generateTile();
}

this.isMoving = false;
this.timing = '';
}

//模拟移动
private arrange(direction: Position, traversal: Array<Array<number>>, isAfterMerge: boolean = false) {
this.grid.tiles.forEach(tile => {
tile.moveToPosition = tile.position;
});
for (let row = 0; row < this.size; row++) {
for (let column = 0; column < this.size; column++) {
const currentPosition = new Position(traversal[0][row], traversal[1][column]);
if (!this.grid.isAvailable(currentPosition)) {
const tile = this.grid.getTileByPosition(currentPosition);
if (tile instanceof Tile && !tile.isEmpty) {
this.arrangeMove(tile, direction, isAfterMerge);
}
}
}
}
}

//模拟移动
private arrangeMove(tile: Tile, direction: Position, isAfterMerge: boolean = false) {
const moveTo = new Position(tile.position.row, tile.position.column);
let mergeInTile = null;

moveTo.add(direction);
while (this.grid.inBound(moveTo) && this.grid.isAvailableAfterMove(moveTo)) {
moveTo.add(direction);
}
if (!isAfterMerge && this.grid.inBound(moveTo)) {
const otherTile = this.grid.getTileByPositionAfterMove(moveTo);
if (!otherTile.mergedOut && !otherTile.mergedIn && otherTile.value === tile.value) {
tile.mergedOut = true;
otherTile.mergedIn = true;
mergeInTile = otherTile;
}
}
moveTo.sub(direction);
this.grid.simulateMoveTo(tile, moveTo);
}

//移动
private async moveAction(direction: Position, traversal: Array<Array<number>>) {
for (let row = 0; row < this.size; row++) {
for (let column = 0; column < this.size; column++) {
const currentPosition = new Position(traversal[0][row], traversal[1][column]);
if (!this.grid.isAvailable(currentPosition)) {
const tile = this.grid.getTileByPosition(currentPosition);
if (tile instanceof Tile && !tile.isEmpty && tile.isNeedMove()) {
this.grid.moveTo(tile, tile.moveToPosition);
}
}
}
}
await this.delay(400)
}

//合并
public async mergeAction() {
let isMerged: boolean = false;
this.grid.tiles.forEach((v) => {
if (v.mergedIn) {
isMerged = true;
v.merge();
this.score += v.value;
} else if (v.mergedOut) {
isMerged = true;
v.clear();
}
});
if (isMerged) {
//await this.delay(100);
}
}

private delay(ms: number) {
...
}

private ifGameOver(isNeedCallback: boolean = true): boolean {
...
}

private canMergeToAround(tile: Tile): boolean {
...
}

public onGameStatusChange(oldValue: boolean, newValue: boolean) {
...
}

public resurrect() {
...
}

public isShuffled() {
...
}
}

组件定义

结构如下:

1
2
3
4
5
6
App.vue
PageComponent.vue
HeaderComponent.vue
TileComponent.vue
ScoreComponent.vue
FooterComponent.vue

PageComponent.vue :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<script setup lang="ts">
import { watch, onMounted, ref } from "vue";
import { basicCannon, schoolPride } from "../util/utils";
import MainManager from "../modules/MainManager";
import TileComponent from "./TileComponent.vue";
import HeaderComponent from "./HeaderComponent.vue";
import ScoreComponent from "./ScoreComponent.vue";
import FooterComponent from "./FooterComponent.vue";

const mainManager = ref(
new MainManager({
events: {
moveCallback,
winCallback,
loseCallback,
},
})
);

function isAvaliableKey(key: string): boolean {
return (
key === "ArrowUp" ||
key === "ArrowDown" ||
key === "ArrowLeft" ||
key === "ArrowRight"
);
}

/**
* 移动回调事件
*/
function moveCallback() {
//改善:DOMException: The play() request was interrupted
setTimeout(function () {
if (clickAudioRef.value?.paused) {
clickAudioRef.value.play();
} else if (clickAudioRef.value) {
clickAudioRef.value.load();
clickAudioRef.value.play();
}
}, 300);
}
...

function keyHandler(event: KeyboardEvent) {
if (mainManager.value.gameOver || !isAvaliableKey(event.key)) {
return;
}
event.preventDefault();
mainManager.value.move(event.key);
}
...

let isOpenTooltip = ref(false);
let startX: number = 0;
let startY: number = 0;
let isMoving: boolean = false;

onMounted(() => {
window.addEventListener("keyup", keyHandler);

window.addEventListener(
"touchstart",
function (e) {
。。。
},
{ passive: false }
);

window.addEventListener(
"touchend",
function (e) {
。。。
},
{ passive: false }
);

window.addEventListener(
"touchmove",
function (e) {
。。。
},
{ passive: false }
);
});

watch(
() => mainManager.value.gameOver,
(newValue, oldValue) => {
mainManager.value.onGameStatusChange(oldValue, newValue);
}
);
</script>

<template>
<HeaderComponent/>

<TransitionGroup
tag="div"
name="list"
class="wrapper normal-bg"
:style="{ 'grid-template-columns': `repeat(${mainManager.size}, 1fr)` }"
v-bind="$attrs"
>
<div v-for="tile in mainManager.grid.tiles" :key="tile.id.toString()">
<TileComponent :tile="tile" :timing="mainManager.timing"> </TileComponent>
</div>
<div v-if="mainManager.gameOver" class="won">
<span class="ml-3 mr-3">{{ mainManager.msg }}</span>
</div>
</TransitionGroup>
<ScoreComponent class="mt-2" :score="mainManager.score" />

<div class="mt-3" id="gameOver">
<div class="mt-3">
<button
class="button ml-2 py-2 px-7 w-25 needtouch"
@click="mainManager.reStart()"
>
重来
</button>
<button
:data-num="mainManager.maxShuffleNum - mainManager.shuffleNum"
:class="[
'button',
'ml-2',
'py-2',
'px-7',
'w-25',
'needtouch',
'used'
]"
:disabled="!mainManager.gameOver || mainManager.shuffleNum < 1"
@click="mainManager.resurrect()"
>
打乱
</button>
</div>
</div>
<FooterComponent :isShowTip="isShowTip" @toggleTip="toggleTip()"/>
<audio
ref="clickAudioRef"
style="display: none"
controls
src="./audio/click.mp3"
/>
<audio
ref="winAudioRef"
style="display: none"
controls
src="./audio/win.mp3"
/>
<audio
ref="loseAudioRef"
style="display: none"
controls
src="./audio/lose.mp3"
/>
</template>

<style scoped lang="scss">
@import "../assets/scss/page.scss";
</style>

TileComponent.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script setup lang="ts">
import { isDark } from "../modules/Dark";
import Tile from "../modules/Tile";

defineProps<{
tile: Tile;
timing: string;
}>();
</script>

<template>
<button v-if="tile.isEmpty" class="tile" />
<button
v-else
:class="[
tile.mergedIn && timing == 'beformerge'
? isDark
? 'mergein-dark'
: 'mergein'
: '',
'tile-' + tile.value,
'tile',
]"
>
{{ tile.value }}
</button>
</template>

<style scoped lang="scss">
@import "../assets/scss/tile.scss";
</style>
Author: jimmy367
Link: http://www.ohtudou.com/2022/11/15/go2048/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
支付宝打赏