21xrx.com
2025-06-23 03:31:03 Monday
文章检索 我的文章 写文章
易懂的C++小游戏编程代码
2023-07-05 02:51:53 深夜i     11     0
C++ 小游戏 编程代码 易懂 命令行界面

C++语言是一门强大的计算机编程语言,为了帮助初学者更好地理解和掌握C++编程,许多程序员会尝试编写小游戏的代码来让学习变得有趣。

在这里,我们将介绍一些易懂的C++小游戏编程代码,帮助您更好地理解C++语言编程的基本概念。

1. 石头剪刀布游戏

这是一个简单的游戏,其中两个玩家选择石头,剪刀,或布中的一种。程序判定胜负教玩家进行多轮对战。

代码如下:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
  string choose;
  int player;
  int computer;
  int win=0, lose=0, same=0;
  bool redo = true;
  while (redo)
  {
    cout << "Enter the choice for rock, scissors, or paper" << endl;
    cin >> choose;
    while (choose != "rock" && choose != "scissors" && choose != "paper")
    
      cout << "Invalid input. Please enter rock
    if (choose == "rock")
      player=1;
    else if (choose == "scissors")
      player=2;
    else if (choose == "paper")
      player=3;
    srand(time(0));
    computer = rand() % 3 + 1;
    if ((player == 1 && computer == 2) || (player == 2 && computer == 3) || (player == 3 && computer == 1))
    {
      cout << "You win!" << endl;
      win++;
    }
    else if ((computer == 1 && player == 2) || (computer == 2 && player == 3) || (computer == 3 && player == 1))
    {
      cout << "You lose!" << endl;
      lose++;
    }
    else
    {
      cout << "Draw!" << endl;
      same++;
    }
    cout << "Enter q to quit, c to start over. Enter any other key to continue." << endl;
    char input;
    cin >> input;
    if (input == 'q')
      redo = false;
    else if (input == 'c')
    
      win = 0;
      lose = 0;
      same = 0;
    
  }
  cout << "Final score: " << endl;
  cout << "Win: " << win << endl;
  cout << "Lose: " << lose << endl;
  cout << "Draw: " << same << endl;
  return 0;
}

2. 数字猜谜游戏

这是一个经典的游戏,程序会在一个随机数范围内选择一个数字,让玩家猜测该数字是多少,程序会给出提示,让玩家接下来的猜测更加精准。

代码如下:

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
  srand(time(0)); //生成随机数种子
  int n = rand() % 100 + 1; //随机生成1-100之间的数字
  int a;   //保存玩家猜测的数字
  int count = 0; //保存猜测次数
  do {
    count++; //每猜一次,猜测次数加1
    cout << "请输入你猜测的数字(1-100):";
    cin >> a; //获取玩家猜测的数字
    if (a > n)
      cout << "猜大了,请再输入一次:" << endl;
    else if (a < n)
      cout << "猜小了,请再输入一次:" << endl;
    else
      cout << "恭喜你,猜对了,一共猜了" << count << "次" << endl;
  } while (a != n);
  return 0;
}

以上两个小游戏的代码相对简单易懂,不会造成大量语言复杂的部分会适当讲解使用方法和布局。但请注意,代码的可阅读性和易懂性并不等于代码的优化和在细节上的处理,当你编写代码时,请考虑到具体业务的需要,尽可能地避免多余的代码。

  
  

评论区