vue实现猜拳
实现猜拳游戏的步骤
创建Vue项目
使用Vue CLI或Vite初始化一个新项目,确保已安装Vue 3。
设计游戏界面
在组件中定义三个按钮分别代表石头、剪刀、布,并添加一个显示区域展示玩家和电脑的选择结果。

<template>
<div>
<h2>猜拳游戏</h2>
<button @click="play('rock')">石头</button>
<button @click="play('scissors')">剪刀</button>
<button @click="play('paper')">布</button>
<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;
const choices = ['rock', 'scissors', 'paper'];
this.computerChoice = choices[Math.floor(Math.random() * 3)];
this.determineWinner();
},
determineWinner() {
if (this.playerChoice === this.computerChoice) {
this.result = '平局';
} else if (
(this.playerChoice === 'rock' && this.computerChoice === 'scissors') ||
(this.playerChoice === 'scissors' && this.computerChoice === 'paper') ||
(this.playerChoice === 'paper' && this.computerChoice === 'rock')
) {
this.result = '你赢了';
} else {
this.result = '你输了';
}
}
}
}
</script>
添加样式
为按钮和结果显示区域添加CSS样式,提升用户体验。
<style>
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
div {
margin-top: 20px;
font-size: 18px;
}
</style>
运行和测试
启动开发服务器,测试游戏功能是否正常,确保所有可能的胜负情况都能正确判断。
npm run dev
通过以上步骤,一个简单的Vue猜拳游戏即可完成。可以根据需求进一步扩展,如添加计分系统或动画效果。






