当前位置:首页 > VUE

vue实现猜拳

2026-02-09 22:14:11VUE

实现思路

使用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使游戏界面更美观:

vue实现猜拳

button {
  padding: 10px 20px;
  margin: 0 10px;
  font-size: 16px;
  cursor: pointer;
}

div {
  text-align: center;
  margin-top: 20px;
}

h2 {
  color: #333;
}

功能扩展

  1. 添加计分功能:

    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++
    }
    }
  2. 添加动画效果:

    <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;
}

注意事项

  1. 游戏逻辑基于经典猜拳规则:石头赢剪刀,剪刀赢布,布赢石头
  2. 随机数生成使用Math.random(),确保电脑选择完全随机
  3. 结果判断通过预先定义的胜负关系映射表实现
  4. 组件化设计使得功能扩展和维护更加方便

标签: 猜拳vue
分享给朋友:

相关文章

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Vue 中实现 Autocomplete(自动完成)功能可以通过自定义组件或使用现有库完成。以下是几种常见方法: 方法一:使用 Vue 原生实现 创建…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue 实现直播

vue 实现直播

Vue 实现直播的基本方法 在Vue中实现直播功能,通常需要结合WebRTC、RTMP或HLS等技术。以下是几种常见的实现方式: 使用WebRTC实现实时直播 WebRTC适合低延迟的实时直播场景,…

vue 实现回复

vue 实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例: 数据绑定与表单 <template> <div>…

vue实现粘贴

vue实现粘贴

Vue 实现粘贴功能的方法 在 Vue 中实现粘贴功能通常涉及监听粘贴事件并处理剪贴板数据。以下是几种常见的实现方式: 监听原生粘贴事件 通过 @paste 指令或原生 addEventListen…

vue实现fullpage

vue实现fullpage

Vue 实现 FullPage 效果 在 Vue 中实现全屏滚动(FullPage)效果可以通过多种方式完成,以下是几种常见的方法: 使用现有库 vue-fullpage.js 安装 vue-ful…