vue实现猜拳游戏
Vue实现猜拳游戏
创建Vue项目
使用Vue CLI创建新项目,确保已安装Node.js和Vue CLI。运行以下命令创建项目:
vue create rock-paper-scissors
游戏组件结构
在src/components目录下创建Game.vue文件,包含以下基本结构:

<template>
<div class="game">
<h1>猜拳游戏</h1>
<div class="choices">
<button @click="play('rock')">石头</button>
<button @click="play('paper')">布</button>
<button @click="play('scissors')">剪刀</button>
</div>
<div class="result" 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.determineWinner()
},
getComputerChoice() {
const choices = ['rock', 'paper', 'scissors']
const randomIndex = Math.floor(Math.random() * 3)
return choices[randomIndex]
},
determineWinner() {
if (this.playerChoice === this.computerChoice) {
return '平局!'
}
if (
(this.playerChoice === 'rock' && this.computerChoice === 'scissors') ||
(this.playerChoice === 'paper' && this.computerChoice === 'rock') ||
(this.playerChoice === 'scissors' && this.computerChoice === 'paper')
) {
return '你赢了!'
}
return '你输了!'
}
}
}
样式设计
在<style>部分添加基本样式:

.game {
text-align: center;
margin-top: 50px;
}
.choices button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.result {
margin-top: 30px;
font-size: 18px;
}
集成到主应用
在App.vue中引入并使用游戏组件:
<template>
<div id="app">
<Game />
</div>
</template>
<script>
import Game from './components/Game.vue'
export default {
components: {
Game
}
}
</script>
运行项目
启动开发服务器查看效果:
npm run serve
功能扩展建议
- 添加游戏历史记录功能
- 实现分数统计系统
- 增加动画效果增强用户体验
- 添加响应式设计适配移动设备
- 实现多语言支持






