21xrx.com
2024-11-22 07:40:08 Friday
登录
文章检索 我的文章 写文章
"C++小游戏代码,简单易懂"
2023-07-03 13:56:17 深夜i     --     --
C++ 游戏 代码 简单易懂

如果你正在学习C++编程语言,并且想尝试写一些小游戏的话,那么你来对地方了。在这篇文章里,我会分享一些简单易懂的C++小游戏代码,供大家参考。

1. 猜数字游戏

这是一个非常简单的游戏,游戏设置一个随机数,玩家需要猜出这个数是多少。如果玩家猜错了,游戏会提示玩家这个数是偏大还是偏小,让玩家再次猜测,直到猜中为止。

下面是代码:


#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main(){

  int secret, guess, count = 0;

  srand(static_cast<unsigned int>(time(0)));

  secret = rand() % 100 + 1;

  cout << "Welcome to guess the number game!" << endl;

  do {

    cout << "Please enter your guess: ";

    cin >> guess;

    count++;

    if (guess > secret)

      cout << "Your guess is too big!" << endl;

     else if (guess < secret)

      cout << "Your guess is too small!" << endl;

     else

      cout << "Congratulations! You win the game with " << count << " guesses!" << endl;

    

  } while (guess != secret);

  return 0;

}

2. 打印三角形

这个游戏充满了算法的乐趣,要求程序根据用户的输入,打印出指定行数的等腰三角形。下面是代码:


#include <iostream>

using namespace std;

int main(){

  int n;

  cout << "Please enter the number of rows: ";

  cin >> n;

  for (int i = 1; i <= n; i++) {

    for (int j = 1; j <= n-i; j++)

      cout << " ";

    

    for (int j = 1; j <= 2*i-1; j++) {

      cout << "*";

    }

    cout << endl;

  }

  return 0;

}

3. 石头剪刀布游戏

这是一个经典的游戏,要求程序随机出拳,并与用户比较大小。下面是代码:


#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main(){

  int n, computer, player;

  srand(static_cast<unsigned int>(time(0)));

  computer = rand() % 3 + 1; //1表示石头,2表示剪刀,3表示布

  cout << "Welcome to rock-paper-scissors game!" << endl;

  cout << "Please enter your choice: 1 for rock, 2 for scissors, 3 for paper." << endl;

  cin >> player;

  switch (player) {

    case 1:

      if (computer == 1)

        cout << "The computer also chooses rock. It's a draw." << endl;

       else if (computer == 2)

        cout << "The computer chooses scissors. You win!" << endl;

       else

        cout << "The computer chooses paper. You lose." << endl;

      

      break;

    case 2:

      if (computer == 2)

        cout << "The computer also chooses scissors. It's a draw." << endl;

       else if (computer == 3)

        cout << "The computer chooses paper. You win!" << endl;

       else

        cout << "The computer chooses rock. You lose." << endl;

      

      break;

    case 3:

      if (computer == 3)

        cout << "The computer also chooses paper. It's a draw." << endl;

       else if (computer == 1)

        cout << "The computer chooses rock. You win!" << endl;

       else

        cout << "The computer chooses scissors. You lose." << endl;

      

      break;

    default:

      cout << "Invalid input. Please enter 1, 2 or 3." << endl;

      break;

  }

  return 0;

}

这些小游戏的代码非常简单明了,适合初学者练习使用。希望大家可以通过这些样例,发挥自己的想象力,开发出更多更有趣的小游戏。

  
  

评论区

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