vue实现打地鼠
实现思路
使用 Vue.js 实现打地鼠游戏需要结合数据驱动和事件处理。游戏核心逻辑包括随机生成地鼠、点击得分、计时器和难度控制。
基础代码结构
<template>
<div class="game-container">
<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 class="score">得分: {{ score }}</div>
<div class="time">剩余时间: {{ timeLeft }}</div>
<button @click="startGame">开始游戏</button>
</div>
</template>
数据定义
<script>
export default {
data() {
return {
holes: Array(9).fill({ active: false }),
score: 0,
timeLeft: 30,
gameInterval: null,
moleInterval: null,
isPlaying: false
}
}
}
</script>
游戏逻辑
methods: {
startGame() {
this.score = 0;
this.timeLeft = 30;
this.isPlaying = true;
this.gameInterval = setInterval(() => {
this.timeLeft--;
if (this.timeLeft <= 0) {
this.endGame();
}
}, 1000);
this.moleInterval = setInterval(() => {
const randomIndex = Math.floor(Math.random() * 9);
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 });
}
},
endGame() {
clearInterval(this.gameInterval);
clearInterval(this.moleInterval);
this.isPlaying = false;
alert(`游戏结束! 最终得分: ${this.score}`);
}
}
样式设计
<style>
.game-container {
text-align: center;
margin-top: 50px;
}
.holes {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
width: 300px;
margin: 0 auto 20px;
}
.hole {
width: 100px;
height: 100px;
background-color: #8B4513;
border-radius: 50%;
position: relative;
overflow: hidden;
}
.mole {
width: 80px;
height: 80px;
background-color: #A0522D;
border-radius: 50%;
position: absolute;
bottom: 0;
left: 10px;
transition: transform 0.1s;
}
.mole:hover {
cursor: pointer;
transform: scale(1.1);
}
.score, .time {
font-size: 20px;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
功能扩展
- 增加难度控制:可以添加速度滑块控制地鼠出现频率
- 添加音效:在地鼠出现和被击中时播放不同音效
- 添加动画效果:使用CSS动画让地鼠有弹出效果
- 保存最高分:使用localStorage保存玩家最高分记录
- 添加关卡系统:随着分数增加提高游戏难度
优化建议
- 使用Vue的transition组件实现更流畅的动画效果
- 考虑使用Vuex管理游戏状态,特别是多组件复杂交互时
- 添加响应式设计,确保在不同设备上都能良好显示
- 实现游戏暂停功能,允许玩家临时中断游戏







