游戏入口
创建应用
1 | > npm create vite@latest |
进入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 | import { Guid } from 'guid-typescript'; |
Grid类定义
1 | import Position from "./Position"; |
主处理类定义
核心代码如下: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
6App.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 | <script setup lang="ts"> |