封装贪吃蛇类
- 监听
keydown事件,通过event.key区分四个方向,相同方向或相反方向按键无效。 - 定义贪吃蛇蛇身数组
snakeList,将下标转换成坐标点coorX、coorY根据不同方向移动坐标点 - 普通
class变量无法用户响应式渲染,所以格子数组需要使用ref定义,已达到实时响应渲染 - 监听事件需要再页面卸载时移除,暴露
endGame方法用户移除监听事件
import { ref, Ref } from 'vue'
enum Direction {
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
export enum CellType {
/**
* 空白格子
*/
Empty = 0,
/**
* 墙壁格子
*/
Wall = 1,
/**
* 蛇身格子
*/
Snake = 2,
/**
* 食物格子
*/
Snack = 3
}
export class SnakeGame {
/**
* 棋盘相关
*/
private grid: number[];
public renderGrid: Ref<number[]>;
private gH: number;
private gW: number;
/**
* 蛇身相关
*/
private snakeList: number[];
private snack: number | null;
private direction: Direction;
private timer: any;
constructor(rows: number, cols: number) {
this.gH = rows;
this.gW = cols;
this.grid = Array.from({ length: rows * cols }, () => CellType.Empty);
this.initGrid(cols, rows);
this.renderGrid = ref(this.grid)
window.addEventListener('keydown', this.handleKeyDown)
}
/**
* 初始化基础格子
*/
initGrid = (w, h) => {
this.grid = Array(h * w).fill(0)
for(let i = 0; i < this.grid.length; i++) {
if(i < w || i >= (h - 1) * w || i % w === 0 || i % w === w - 1) {
this.grid[i] = CellType.Wall
}
}
}
/**
* 初始化蛇身
*/
private initSnake = () => {
// 获取所有 grid 为 0 的索引
const emptyCells = this.grid
.map((cell, idx) => cell === 0 ? idx : -1)
.filter(idx => idx !== -1)
// 随机选择一个起点
const randomIdx = Math.floor(Math.random() * emptyCells.length)
const startIdx = emptyCells[randomIdx]
// 生成长度为 2 的蛇身(可以调整长度)
if (startIdx + 1 != emptyCells[randomIdx + 1]) {
// 如果起点在右边界,向左延伸
this.snakeList = [startIdx - 1, startIdx]
this.direction = Direction.Left
} else {
if (startIdx % this.gW < this.gW / 2) {
this.snakeList = [startIdx + 1, startIdx]
this.direction = Direction.Right
} else {
this.snakeList = [startIdx, startIdx + 1]
this.direction = Direction.Left
}
}
}
/**
* 生成渲染棋盘
*/
initRenderGrid = () => {
const newGrid = this.grid.concat() || []
if (this.snakeList) {
for(let i = 0; i < this.snakeList.length; i++) {
newGrid[this.snakeList[i]] = CellType.Snake
}
}
if (this.snack !== null) {
newGrid[this.snack] = CellType.Snack
}
this.renderGrid.value = newGrid
// console.log(this.renderGrid)
}
/**
* 生成食物
*/
generateSnack() {
const emptyCells = this.grid
.map((cell, idx) => cell === CellType.Empty ? idx : -1)
.filter(idx => idx !== -1)
const randomIdx = Math.floor(Math.random() * emptyCells.length)
return emptyCells[randomIdx]
}
/**
* 监听按键
*/
handleKeyDown = (event: KeyboardEvent) => {
console.log(event.key)
let dir = null
switch(event.key) {
case 'ArrowUp':
if (this.direction === Direction.Down || this.direction === Direction.Up) return
dir = Direction.Up
break;
case 'ArrowDown':
if (this.direction === Direction.Up || this.direction === Direction.Down) return
dir = Direction.Down
break;
case 'ArrowLeft':
if (this.direction === Direction.Right || this.direction === Direction.Left) return
dir = Direction.Left
break;
case 'ArrowRight':
if (this.direction === Direction.Left || this.direction === Direction.Right) return
dir = Direction.Right
break;
}
if (dir) {
this.direction = dir
clearInterval(this.timer)
this.moveSnake()
this.initRenderGrid()
this.timer = setInterval(() => {
this.moveSnake()
this.initRenderGrid()
}, 1000)
}
}
/**
* 移动
*/
moveSnake = () => {
let newHead = this.snakeList[0]
let coorX = newHead % this.gW
let coorY = Math.floor(newHead / this.gW)
switch (this.direction) {
case Direction.Up:
coorY -= 1
break
case Direction.Down:
coorY += 1
break
case Direction.Left:
coorX -= 1
break
case Direction.Right:
coorX += 1
break
}
newHead = coorX + coorY * this.gW
const renderItem = this.renderGrid.value[newHead]
if (renderItem === CellType.Empty) {
// 有效移动,移除尾部添加新头部
this.snakeList.unshift(newHead)
this.snakeList.pop()
} else if(renderItem === CellType.Snack) {
// 吃到食物,增长蛇身
this.snakeList.unshift(newHead)
this.snack = this.generateSnack()
} else if(renderItem === CellType.Wall || renderItem === CellType.Snake) {
clearInterval(this.timer)
alert('撞墙了,游戏结束!')
}
}
/**
* 判断当前格子是否为蛇头
*/
public isFirst = (idx) => {
return this.snakeList[0] === idx
}
/**
* 开始游戏
*/
public startGame = () => {
this.snack = this.generateSnack()
this.initSnake()
this.initRenderGrid()
this.timer = setInterval(() => {
this.moveSnake()
this.initRenderGrid()
}, 800)
}
/**
* 结束游戏
*/
public endGame = () => {
this.snakeList = []
this.snack = null
this.renderGrid.value = this.grid
window.removeEventListener('keydown', this.handleKeyDown)
}
}
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
上次更新: 2025/09/05, 8:09:00