vue实现击中类游戏
Vue 实现击中类游戏
游戏核心逻辑设计
使用Vue的响应式特性管理游戏状态,包括目标位置、得分和游戏时间。数据部分可设计为:
data() {
return {
score: 0,
timeLeft: 30,
targetPosition: { x: 0, y: 0 },
isPlaying: false
}
}
动态目标生成
通过随机函数生成目标位置,结合Vue的样式绑定实现动态显示:
methods: {
moveTarget() {
this.targetPosition = {
x: Math.random() * (window.innerWidth - 50),
y: Math.random() * (window.innerHeight - 50)
}
}
}
模板部分使用动态样式:

<div
class="target"
:style="{ left: targetPosition.x + 'px', top: targetPosition.y + 'px' }"
@click="hitTarget">
</div>
点击事件处理
实现击中逻辑和分数计算:
hitTarget() {
if (!this.isPlaying) return
this.score++
this.moveTarget()
clearTimeout(this.timer)
this.startCountdown()
}
游戏计时系统
使用setInterval实现倒计时功能:

startGame() {
this.isPlaying = true
this.score = 0
this.timeLeft = 30
this.moveTarget()
this.startCountdown()
},
startCountdown() {
this.timer = setInterval(() => {
if (this.timeLeft <= 0) {
clearInterval(this.timer)
this.isPlaying = false
} else {
this.timeLeft--
}
}, 1000)
}
动画效果增强
通过CSS过渡效果提升交互体验:
.target {
transition: transform 0.1s;
transform: scale(1);
}
.target:active {
transform: scale(0.9);
}
响应式布局适配
使用vw/vh单位确保游戏在不同设备上的适应性:
.game-area {
width: 100vw;
height: 100vh;
}
完整组件示例
<template>
<div class="game-container">
<div v-if="!isPlaying">
<button @click="startGame">Start Game</button>
</div>
<div v-else>
<div class="info">Score: {{ score }} | Time: {{ timeLeft }}</div>
<div
class="target"
:style="targetStyle"
@click="hitTarget">
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
score: 0,
timeLeft: 30,
targetPosition: { x: 0, y: 0 },
isPlaying: false,
timer: null
}
},
computed: {
targetStyle() {
return {
left: `${this.targetPosition.x}px`,
top: `${this.targetPosition.y}px`
}
}
},
methods: {
startGame() {
this.isPlaying = true
this.score = 0
this.timeLeft = 30
this.moveTarget()
this.startCountdown()
},
moveTarget() {
this.targetPosition = {
x: Math.random() * (window.innerWidth - 50),
y: Math.random() * (window.innerHeight - 50)
}
},
hitTarget() {
this.score++
this.moveTarget()
},
startCountdown() {
this.timer = setInterval(() => {
if (this.timeLeft <= 0) {
clearInterval(this.timer)
this.isPlaying = false
} else {
this.timeLeft--
}
}, 1000)
}
},
beforeUnmount() {
clearInterval(this.timer)
}
}
</script>
<style>
.target {
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
position: absolute;
cursor: pointer;
transition: transform 0.1s;
}
.target:active {
transform: scale(0.9);
}
.game-container {
position: relative;
height: 100vh;
overflow: hidden;
}
.info {
position: fixed;
top: 10px;
left: 10px;
font-size: 20px;
}
</style>






