21xrx.com
2025-04-12 23:57:06 Saturday
文章检索 我的文章 写文章
C++代码示例:添加自定义函数实现猜拳游戏
2023-06-24 08:54:12 深夜i     20     0
C++代码 自定义函数 猜拳游戏

猜拳游戏是深受大家喜爱的一种游戏。现在,我们可以利用C++语言来编写猜拳游戏并实现自定义函数。下面,我们将介绍一段示例代码,帮助大家学习如何编写一个简单的猜拳程序。

下面是代码实现:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int getChoice()
3——布: ";
  cin >> choice;
  return choice;
int computerChoice()
{
  srand(time(0));
  int choice = rand() % 3 + 1;
  cout << "电脑出拳: ";
  switch (choice)
  case 1: cout << "石头" << endl; break;
  case 2: cout << "剪刀" << endl; break;
  case 3: cout << "" << endl; break;
  
  return choice;
}
int judge(int playerChoice, int computerChoice)
{
  if ((playerChoice == 1 && computerChoice == 2) ||
    (playerChoice == 2 && computerChoice == 3) ||
    (playerChoice == 3 && computerChoice == 1))
    return 1;
  else if ((playerChoice == 1 && computerChoice == 3) ||
       (playerChoice == 2 && computerChoice == 1) ||
       (playerChoice == 3 && computerChoice == 2))
    return -1;
  else
    return 0;
}
void printResult(int result)
{
  if (result == 1) cout << "你赢了!" << endl;
  else if (result == -1) cout << "你输了!" << endl;
  else cout << "平局!" << endl;
}
int main()
{
  int playerChoice, result;
  do {
    playerChoice = getChoice();
    result = judge(playerChoice, computerChoice());
    printResult(result);
  } while (result == 0);
  return 0;
}

上述代码是一个完整的猜拳游戏实现。函数`getChoice()`实现了从控制台输入玩家出拳的选项;`computerChoice()`则利用随机数实现了电脑随机选择一个选项;`judge()`完成玩家和电脑选项的比较,给出输和赢的情况;最后,`printResult()`根据结果输出最终获胜者。

以上就是一段简单的猜拳游戏代码实现,如果您想深入了解更多的C++编程知识,不妨多多练习,提高自己的编程水平。

  
  

评论区