vue实现打地鼠
实现思路
使用Vue的响应式数据和事件绑定功能,构建一个简单的打地鼠游戏界面。通过随机生成地鼠出现的位置,玩家点击地鼠得分,计时结束后统计总分。
代码实现
<template>
<div class="game-container">
<h2>打地鼠游戏</h2>
<div class="info">
<span>得分: {{ score }}</span>
<span>时间: {{ timeLeft }}秒</span>
</div>
<div class="game-board">
<div
v-for="(hole, index) in holes"
:key="index"
class="hole"
@click="hitMole(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().map(() => ({ active: false })),
score: 0,
timeLeft: 30,
gameStarted: false,
timer: null,
moleInterval: null
}
},
methods: {
startGame() {
this.gameStarted = true
this.score = 0
this.timeLeft = 30
this.timer = setInterval(() => {
this.timeLeft--
if (this.timeLeft <= 0) {
this.endGame()
}
}, 1000)
this.moleInterval = setInterval(() => {
this.popRandomMole()
}, 800)
},
popRandomMole() {
// 先重置所有洞
this.holes.forEach(hole => {
hole.active = false
})
// 随机选择一个洞显示地鼠
const randomIndex = Math.floor(Math.random() * this.holes.length)
this.holes[randomIndex].active = true
// 1秒后地鼠消失
setTimeout(() => {
this.holes[randomIndex].active = false
}, 1000)
},
hitMole(index) {
if (this.holes[index].active) {
this.score++
this.holes[index].active = false
}
},
endGame() {
clearInterval(this.timer)
clearInterval(this.moleInterval)
this.gameStarted = false
alert(`游戏结束! 你的得分是: ${this.score}`)
}
}
}
</script>
<style>
.game-container {
max-width: 500px;
margin: 0 auto;
text-align: center;
}
.info {
display: flex;
justify-content: space-around;
margin: 20px 0;
}
.game-board {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-bottom: 20px;
}
.hole {
position: relative;
width: 100px;
height: 100px;
background-color: #8B4513;
border-radius: 50%;
cursor: pointer;
}
.mole {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 60px;
height: 60px;
background-color: #A0522D;
border-radius: 50%;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
</style>
功能说明
-
游戏初始化
- 创建9个洞的数组,每个洞初始状态为不活跃(无地鼠)
- 设置初始得分0,剩余时间30秒
-
开始游戏
- 点击开始按钮后启动游戏
- 设置计时器每秒减少剩余时间
- 设置地鼠随机出现间隔(800毫秒)
-
地鼠逻辑
- 随机选择一个洞显示地鼠
- 1秒后地鼠自动消失
- 玩家点击活跃的地鼠得分
-
游戏结束

- 时间归零时清除所有定时器
- 显示最终得分
优化建议
- 增加难度系统,随着游戏进行加快地鼠出现速度
- 添加音效增强游戏体验
- 实现地鼠不同状态(出现/被打中)的动画效果
- 添加最高分记录功能
- 增加游戏关卡设置选项
这个实现使用了Vue的核心功能,包括数据绑定、事件处理和条件渲染,适合作为Vue初学者的练习项目。可以根据需要进一步扩展功能或优化界面。






