vue实现猜拳
实现思路
使用Vue实现猜拳游戏需要几个核心功能:玩家选择手势、电脑随机生成手势、比较胜负逻辑以及显示结果。通过Vue的数据绑定和事件处理可以轻松实现交互。
核心代码结构
<template>
<div>
<h2>猜拳游戏</h2>
<div>
<button @click="play('rock')">石头</button>
<button @click="play('scissors')">剪刀</button>
<button @click="play('paper')">布</button>
</div>
<div v-if="result">
<p>你的选择: {{ playerChoice }}</p>
<p>电脑选择: {{ computerChoice }}</p>
<p>结果: {{ result }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
playerChoice: '',
computerChoice: '',
result: ''
}
},
methods: {
play(choice) {
this.playerChoice = choice
this.computerChoice = this.getComputerChoice()
this.result = this.getResult(this.playerChoice, this.computerChoice)
},
getComputerChoice() {
const choices = ['rock', 'scissors', 'paper']
const randomIndex = Math.floor(Math.random() * 3)
return choices[randomIndex]
},
getResult(player, computer) {
if (player === computer) return '平局'
const winMap = {
rock: 'scissors',
scissors: 'paper',
paper: 'rock'
}
return winMap[player] === computer ? '你赢了' : '你输了'
}
}
}
</script>
样式美化
可以添加CSS使游戏界面更美观:
button {
padding: 10px 20px;
margin: 0 10px;
font-size: 16px;
cursor: pointer;
}
div {
text-align: center;
margin-top: 20px;
}
h2 {
color: #333;
}
功能扩展
-
添加计分功能:
data() { return { score: { player: 0, computer: 0, draw: 0 } } }, methods: { play(choice) { // ...原有代码 if (this.result === '你赢了') this.score.player++ else if (this.result === '你输了') this.score.computer++ else this.score.draw++ } } -
添加动画效果:
<transition name="fade"> <div v-if="result"> <!-- 结果展示 --> </div> </transition>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
注意事项
- 游戏逻辑基于经典猜拳规则:石头赢剪刀,剪刀赢布,布赢石头
- 随机数生成使用Math.random(),确保电脑选择完全随机
- 结果判断通过预先定义的胜负关系映射表实现
- 组件化设计使得功能扩展和维护更加方便







