vue实现打地鼠
Vue实现打地鼠游戏
打地鼠游戏是一种常见的互动小游戏,通过Vue的响应式特性和组件化开发可以高效实现。以下是实现步骤和代码示例:
游戏界面布局
使用Vue模板构建游戏界面,包含地鼠洞和计分板:
<template>
<div class="game-container">
<div class="score">得分: {{ score }}</div>
<div class="holes">
<div
v-for="(hole, index) in holes"
:key="index"
class="hole"
@click="hitMole(index)"
>
<div v-if="hole.active" class="mole"></div>
</div>
</div>
</div>
</template>
游戏状态管理
在Vue的data中定义游戏状态变量:

data() {
return {
holes: Array(9).fill({ active: false }),
score: 0,
gameInterval: null,
gameDuration: 30000,
timeLeft: 30
}
}
地鼠随机出现
使用定时器控制地鼠随机出现:
methods: {
startGame() {
this.gameInterval = setInterval(() => {
const randomIndex = Math.floor(Math.random() * this.holes.length)
this.$set(this.holes, randomIndex, { active: true })
setTimeout(() => {
this.$set(this.holes, randomIndex, { active: false })
}, 1000)
}, 800)
setTimeout(() => {
clearInterval(this.gameInterval)
}, this.gameDuration)
}
}
击中地鼠逻辑
实现点击地鼠得分功能:

methods: {
hitMole(index) {
if (this.holes[index].active) {
this.score++
this.$set(this.holes, index, { active: false })
}
}
}
样式设计
添加CSS样式增强游戏体验:
.game-container {
max-width: 600px;
margin: 0 auto;
}
.holes {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.hole {
width: 100px;
height: 100px;
background: #8B4513;
border-radius: 50%;
position: relative;
overflow: hidden;
}
.mole {
width: 80px;
height: 80px;
background: #000;
border-radius: 50%;
position: absolute;
bottom: 0;
left: 10px;
transition: all 0.1s;
}
.score {
font-size: 24px;
margin-bottom: 20px;
}
游戏控制
添加开始按钮和倒计时功能:
<button @click="startGame">开始游戏</button>
<div>剩余时间: {{ timeLeft }}秒</div>
methods: {
startGame() {
this.score = 0
this.timeLeft = 30
const timer = setInterval(() => {
this.timeLeft--
if (this.timeLeft <= 0) {
clearInterval(timer)
}
}, 1000)
// 原有游戏逻辑...
}
}
完整组件代码
将上述代码整合为完整Vue组件:
<template>
<div class="game-container">
<div class="score">得分: {{ score }}</div>
<div>剩余时间: {{ timeLeft }}秒</div>
<button @click="startGame">开始游戏</button>
<div class="holes">
<div
v-for="(hole, index) in holes"
:key="index"
class="hole"
@click="hitMole(index)"
>
<div v-if="hole.active" class="mole"></div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
holes: Array(9).fill({ active: false }),
score: 0,
gameInterval: null,
timeLeft: 30
}
},
methods: {
startGame() {
this.score = 0
this.timeLeft = 30
this.holes = Array(9).fill({ active: false })
const timer = setInterval(() => {
this.timeLeft--
if (this.timeLeft <= 0) {
clearInterval(timer)
clearInterval(this.gameInterval)
}
}, 1000)
this.gameInterval = setInterval(() => {
const randomIndex = Math.floor(Math.random() * this.holes.length)
this.$set(this.holes, randomIndex, { active: true })
setTimeout(() => {
this.$set(this.holes, randomIndex, { active: false })
}, 1000)
}, 800)
},
hitMole(index) {
if (this.holes[index].active) {
this.score++
this.$set(this.holes, index, { active: false })
}
}
}
}
</script>
这个实现包含了游戏的核心功能,可以根据需要进一步扩展,如添加难度级别、音效、动画效果等。






