C++ 猜数字游戏:带时间限制和趣味提示

本程序使用 C++ 编写了一个猜数字游戏,包含时间限制、提示和游戏结果显示,并允许玩家选择是否继续游戏。

游戏规则

  1. 计算机随机生成一个 1 到 10000 之间的数字。
  2. 玩家根据提示猜测该数字。
  3. 游戏结束条件:
    • 在规定时间内正确猜出该数字;
    • 规定时间耗尽。
  4. 游戏提示:
    • 根据玩家输入与所生成数字的大小关系给出提示,例如:
      • 如果玩家输入 6000,而随机生成的数字为 5000,则提示 '高了'。
      • 如果玩家输入 4000,而随机生成的数字为 5000,则提示 '低了'。
  5. 游戏结果显示:
    • 如果玩家在规定时间内正确猜出数字,则显示 '恭喜!正确猜出数字 ***'。
    • 如果到达规定时间但未猜出,则显示 '很遗憾,未能在规定时间内猜出正确数字,该数字为 '。其中 '' 表示所需猜出的随机数。
  6. 游戏时间设置:玩家可以在游戏开始前灵活设置游戏时间。
  7. 游戏退出设置:在每轮游戏结束之后,给出提示语,请玩家选择是否继续游戏。

代码实现

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    int min = 1;
    int max = 10000;
    int target;
    int guess;
    int timeLimit;
    char playAgain;
    
    srand(time(0)); // seed the random number generator
    
    do {
        // Setting game time
        cout << "Enter the time limit for the game (in seconds): ";
        cin >> timeLimit;
        
        // Generating random target number
        target = rand() % (max - min + 1) + min;
        
        // Start game timer
        time_t startTime = time(0);
        time_t currentTime;
        int elapsedTime;
        
        cout << "Guess the number between " << min << " and " << max << endl;
        
        // Game loop
        do {
            cout << "Enter your guess: ";
            cin >> guess;
            
            if (guess < target) {
                cout << "Too low! Try again." << endl;
            } else if (guess > target) {
                cout << "Too high! Try again." << endl;
            } else {
                cout << "Congratulations! You guessed the correct number " << target << "." << endl;
                break;
            }
            
            // Check time limit
            currentTime = time(0);
            elapsedTime = currentTime - startTime;
            
        } while (elapsedTime < timeLimit);
        
        // Game over
        if (elapsedTime >= timeLimit) {
            cout << "Sorry, you ran out of time. The correct number was " << target << "." << endl;
        }
        
        // Prompt for replay
        cout << "Do you want to play again? (Y/N): ";
        cin >> playAgain;
        
    } while (playAgain == 'Y' || playAgain == 'y');
    
    return 0;
}

总结

本程序通过 C++ 实现了一个简单的猜数字游戏,包含时间限制和提示,并允许玩家选择是否继续游戏。您可以根据自己的需求修改和扩展该程序,例如添加更多趣味性内容,如提示特定位上的数字等。

C++ 猜数字游戏:带时间限制和趣味提示

原文地址: https://www.cveoy.top/t/topic/qfE3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录