使用贪吃蛇类
效果如下:

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { CellType, SnakeGame } from '@/utils/snake'
const snakeGame = ref<SnakeGame | null>(null)
const wSize = ref<number>(30)
const hSize = ref<number>(30)
const cellClass = computed(() => {
return (cell, idx) => {
return {
'cell-wall': cell === CellType.Wall,
'cell-snake': cell === CellType.Snake,
'cell-snake-head': cell === CellType.Snake && snakeGame.value?.isFirst(idx),
'cell-snack': cell === CellType.Snack
}
}
})
const initGame = () => {
snakeGame.value = new SnakeGame(hSize.value, wSize.value)
}
initGame()
onMounted(() => {
setTimeout(() => {
snakeGame.value?.startGame()
}, 2000)
}),
onUnmounted(() => {
snakeGame.value?.endGame()
})
</script>
<template>
<div class="playground">
<div
v-for="(cell, cIdx) in snakeGame?.renderGrid || []"
:key="cIdx"
class="cell"
:class="cellClass(cell, cIdx)"
></div>
</div>
</template>
<style lang="scss" scoped>
.playground {
display: grid;
grid-template-columns: repeat(v-bind(wSize), 1fr);
gap: 1px;
width: fit-content;
.cell {
display: inline-block;
width: 16px;
height: 16px;
background: white;
transition: all 0.1s;
&-wall {
background: red;
}
&-snake {
background: green;
}
&-snake-head {
border-radius: 35%;
}
&-snack {
background: yellow;
}
}
}
</style>
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
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
# 总结
花费大半天实现了一个贪吃蛇游戏,代码比较粗糙功能也比较少,后续有空会进一步优化,具体代码见:snake代码
上次更新: 2025/09/05, 8:09:00