21xrx.com
2025-06-13 10:34:37 Friday
文章检索 我的文章 写文章
"简单易懂的猜拳游戏C++代码实现"
2023-06-29 16:57:37 深夜i     26     0
猜拳游戏 C++代码 简单易懂 实现 编程技术

猜拳作为休闲娱乐活动,受到了广大人民群众的喜爱。为了增加游戏的趣味性,我们可以借助计算机编程技术实现猜拳游戏。本文将介绍一份简单易懂的猜拳游戏C++代码实现。

首先,我们需要定义猜拳中出拳的三种手势,即“剪刀”、“石头”、“布”,可以使用枚举类型定义。代码如下:

enum Gesture
  PAPER
;

然后,我们可以使用随机数生成器来模拟电脑出拳。使用C++中的rand()函数可以生成一个0-32767之间的随机整数,使用模运算可以将其转化为0-2之间的整数 representing 手势。代码如下:

srand(time(NULL)); // 初始化随机数种子
int computerGesture = rand() % 3// 生成电脑出拳

接下来,我们需要让用户输入出拳手势。可以使用C++中的cin来实现用户输入。代码如下:

int userGesture;
cout << "Please input 0 for Scissor, 1 for Rock, 2 for Paper" << endl;
cin >> userGesture;

最后,我们需要判断胜负关系并输出结果。这里我们可以使用if-else语句进行判断。代码如下:

if (userGesture == computerGesture)
  cout << "Tie game!" << endl;
else if ((userGesture + 1) % 3 == computerGesture)
  cout << "You win!" << endl;
else
  cout << "You lose!" << endl;

将以上代码结合起来,即可实现猜拳游戏的功能。完整代码如下:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
enum Gesture
  PAPER
;
int main() {
  srand(time(NULL)); // 初始化随机数种子
  int computerGesture = rand() % 3// 生成电脑出拳
  int userGesture;
  cout << "Please input 0 for Scissor, 1 for Rock, 2 for Paper" << endl;
  cin >> userGesture; // 用户输入出拳手势
  if (userGesture == computerGesture)
    cout << "Tie game!" << endl;
   else if ((userGesture + 1) % 3 == computerGesture)
    cout << "You win!" << endl;
   else
    cout << "You lose!" << endl;
  
  return 0;
}

以上就是一份简单易懂的猜拳游戏C++代码实现。通过学习这个代码,我们可以更好地理解C++中枚举类型、随机数生成器和if-else语句等基本概念。也希望大家在休闲时间能够通过编程实现自己喜欢的小游戏,让生活更多一份乐趣。

  
  

评论区