vue实现打地鼠
Vue 实现打地鼠游戏
游戏逻辑设计
打地鼠游戏的核心逻辑包括随机生成地鼠、玩家点击得分、计时和计分系统。在Vue中可以通过数据驱动的方式实现这些功能。

创建Vue组件
新建一个Vue组件,命名为WhackAMole.vue,包含游戏区域、计分板和计时器。

<template>
<div class="game-container">
<h2>打地鼠游戏</h2>
<div class="score-board">
<span>得分: {{ score }}</span>
<span>剩余时间: {{ timeLeft }}秒</span>
</div>
<div class="game-board">
<div
v-for="(hole, index) in holes"
:key="index"
class="hole"
@click="whack(index)"
>
<div v-if="hole.active" class="mole"></div>
</div>
</div>
<button v-if="!gameStarted" @click="startGame">开始游戏</button>
</div>
</template>
数据与状态管理
在组件中定义必要的数据属性:
<script>
export default {
data() {
return {
holes: Array(9).fill({ active: false }),
score: 0,
timeLeft: 30,
gameStarted: false,
gameInterval: null,
moleInterval: null
}
},
methods: {
startGame() {
this.gameStarted = true
this.score = 0
this.timeLeft = 30
this.gameInterval = setInterval(() => {
this.timeLeft--
if (this.timeLeft <= 0) {
clearInterval(this.gameInterval)
clearInterval(this.moleInterval)
this.gameStarted = false
}
}, 1000)
this.moleInterval = setInterval(this.popUpMole, 1000)
},
popUpMole() {
// 随机选择一个洞显示地鼠
const randomIndex = Math.floor(Math.random() * this.holes.length)
this.holes = this.holes.map((hole, index) =>
index === randomIndex ? { active: true } : { active: false }
)
// 1秒后地鼠消失
setTimeout(() => {
this.holes = this.holes.map(hole => ({ active: false }))
}, 1000)
},
whack(index) {
if (this.holes[index].active) {
this.score++
this.holes = this.holes.map(hole => ({ active: false }))
}
}
}
}
</script>
样式设计
添加CSS样式使游戏界面更美观:
<style scoped>
.game-container {
text-align: center;
max-width: 600px;
margin: 0 auto;
}
.game-board {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin: 20px auto;
width: 300px;
}
.hole {
width: 80px;
height: 80px;
background-color: #8B4513;
border-radius: 50%;
position: relative;
cursor: pointer;
}
.mole {
width: 60px;
height: 60px;
background-color: #654321;
border-radius: 50%;
position: absolute;
top: 10px;
left: 10px;
}
.score-board {
display: flex;
justify-content: space-around;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
游戏优化建议
- 增加游戏难度随时间递增的功能,可以缩短地鼠出现的时间间隔
- 添加音效增强游戏体验,如击中地鼠的声音
- 实现不同地鼠类型,设置不同分值
- 添加游戏结束后的排行榜功能
完整实现要点
- 使用Vue的响应式数据管理游戏状态
- 通过
setInterval和setTimeout控制游戏流程 - 利用数组方法更新地鼠位置
- 使用网格布局创建游戏棋盘
- 通过条件渲染显示/隐藏地鼠






