21xrx.com
2024-09-20 00:21:22 Friday
登录
文章检索 我的文章 写文章
C++代码实现石头剪刀布游戏
2023-07-04 19:57:35 深夜i     --     --
C++ 石头剪刀布 游戏 代码

石头剪刀布,是一种常见的游戏,在学习编程的过程中,我们可以通过编写C++代码来实现这个游戏的功能。下面是一份参考代码:


#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;

int main(){

  int user_choice;

  int computer_choice;

  int rounds;

  int user_win = 0;

  int computer_win = 0;

  

  cout << "欢迎来到石头剪刀布游戏!" << endl;

  cout << "请输入游戏轮数:" << endl;

  cin >> rounds;

  

  for(int i = 0; i < rounds; i++){

    cout << "请选择你的出招:1(石头)、2(剪刀)、3(布)" << endl;

    cin >> user_choice;

    

    srand(time(0));

    computer_choice = rand() % 3 + 1;

    

    if(user_choice == computer_choice)电脑出了:" << computer_choice << endl;

      cout << "平局!" << endl;

    

    else if((user_choice == 1 && computer_choice == 2) || (user_choice == 2 && computer_choice == 3) || (user_choice == 3 && computer_choice == 1)){

      cout << "你出了:" << user_choice << ",电脑出了:" << computer_choice << endl;

      cout << "你赢了!" << endl;

      user_win++;

    }

    else{

      cout << "你出了:" << user_choice << ",电脑出了:" << computer_choice << endl;

      cout << "你输了!" << endl;

      computer_win++;

    }

  }

  

  if(user_win == computer_win)

    cout << "最后结果:平局!" << endl;

  

  else if(user_win > computer_win)

    cout << "最后结果:你赢了!" << endl;

  

  else

    cout << "最后结果:你输了!" << endl;

  

  

  return 0;

}

这份代码实现了一个石头剪刀布游戏,其中通过循环的方式实现了多轮游戏,并计算了最后的胜负结果。游戏中,用户需要输入游戏轮数和自己的出招,电脑会随机出招。通过判断用户和电脑的出招,判断出当前比赛的胜负情况,并累计每轮的胜负情况,最后比较胜利的次数来计算最后的胜负结果。这样通过编写C++代码,就可以实现一个简单的石头剪刀布游戏了。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复