21xrx.com
2024-09-19 11:38:18 Thursday
登录
文章检索 我的文章 写文章
C++编写的剪刀石头布游戏
2023-07-14 17:21:26 深夜i     --     --
C++ 编写 剪刀石头布游戏 程序设计 游戏逻辑

剪刀石头布是非常受欢迎的小游戏,它简单易学,规则简单却又趣味无穷,许多人小时候都喜欢玩这个游戏。

如何利用C++编写一个完整的剪刀石头布游戏呢?下面我们就一起来看看。

首先,我们要定义并显示游戏菜单,让用户选择自己想要出的手势。选择完成之后,我们需要判断人机之间的胜负情况。最后,我们需要显示最终的胜负结果,并向用户询问是否继续游戏。

让我们来看一下主要代码:

//剪刀石头布游戏

#include

#include

#include

using namespace std;

int main()

{

  string hand[3] = "布" ;

  int player, computer;

  int player_win = 0, computer_win = 0;

  cout << "==============================" << endl;

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

  cout << "      -Menu-      " << endl;

  cout << "    1.剪刀   2.石头   3.布   " << endl;

  cout << "    0.结束游戏        " << endl;

  cout << "==============================" << endl;

  do {

    cout << "请选择您想出的手势(1-3):";

    cin >> player;

    if (player == 0)

      break;

    srand(time(0));

    computer = rand() % 3 + 1;

    cout << "您出:" << hand[player - 1] << endl;

    cout << "电脑出:" << hand[computer - 1] << endl;

    if (player == computer)

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

    else if ((player - computer + 3) % 3 == 1) {

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

      player_win++;

    }

    else {

      cout << "电脑赢了!" << endl;

      computer_win++;

    }

  } while (true);

  cout << "==============================" << endl;

  cout << "谢谢使用,游戏结束!" << endl;

  cout << "您的成绩:" << player_win << "胜" << computer_win << "负" << endl;

  return 0;

}

在这段代码中,我们定义了三个不同的手势,并通过srand()和rand()函数生成了电脑随机的出拳,同时根据规则判断胜负并计分。

运行以上代码,我们就可以愉快地玩起剪刀石头布游戏了!

总结一下,这篇文章中我们通过C++编写了一个简单的剪刀石头布游戏。尽管游戏规则简单,代码实现依然需要我们熟悉C++的基础知识。希望这篇文章能够帮助大家更好地理解和掌握C++编程的技巧,提高我们的编程能力。

  
  

评论区

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