Kros的博客 Kros的博客
首页
  • CSS
  • 工具
  • Vue
  • js
  • Vue3
  • 算法
  • 折腾笔记
一言
  • 分类
  • 标签
  • 归档
码云

Kros

凡心所向,素履以往,生如逆旅,一苇以航
首页
  • CSS
  • 工具
  • Vue
  • js
  • Vue3
  • 算法
  • 折腾笔记
一言
  • 分类
  • 标签
  • 归档
码云
  • 拼图小游戏

  • 井字棋

  • 贪吃蛇

    • 实现思考
    • 封装贪吃蛇类
    • 使用贪吃蛇类
  • 扫雷

  • 项目
  • 贪吃蛇
kros
2025-09-02

使用贪吃蛇类

效果如下:

snake

<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

# 总结

花费大半天实现了一个贪吃蛇游戏,代码比较粗糙功能也比较少,后续有空会进一步优化,具体代码见:snake代码

上次更新: 2025/09/05, 8:09:00
封装贪吃蛇类
扫雷规则

← 封装贪吃蛇类 扫雷规则→

最近更新
01
Find the next perfect square
09-05
02
Regex validate PIN code
09-05
03
Find the odd int
09-05
更多文章>
Theme by Vdoing | Copyright © 2020-2025 kros king
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
icon-heart-o icon-heart icon-infinity icon-pause icon-play link next prev