该程序是一个简单的猜数字游戏,功能说明如下:

  1. 用户可以设置游戏的时间限制,程序会提示用户输入时间限制,并将其保存在变量'timeLimit'中。

  2. 程序会生成一个随机的目标数字,目标数字的范围是1到10000之间。

  3. 游戏开始后,程序会提示用户猜一个数字,用户输入自己的猜测,并将猜测保存在变量'guess'中。

  4. 程序会根据用户的猜测与目标数字进行比较,如果猜测数字小于目标数字,则程序会提示用户猜测数字太低;如果猜测数字大于目标数字,则程序会提示用户猜测数字太高;如果猜测数字等于目标数字,则程序会提示用户猜测正确,并结束游戏。

  5. 程序会记录游戏开始的时间,并计算出已经过去的时间。如果已经过去的时间超过了用户设置的时间限制,程序会提示用户时间已经用完,并显示出目标数字。

  6. 游戏结束后,程序会询问用户是否要再次玩游戏,用户可以输入'Y'或'N'来选择。

下面是程序的测试截图:

  1. 设置时间限制为10秒,猜测正确:

测试截图1

  1. 设置时间限制为10秒,猜测错误:

测试截图2

  1. 设置时间限制为5秒,时间用完:

测试截图3

  1. 再次玩游戏:

测试截图4

代码解析

#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++ 猜数字游戏:代码解析和测试

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

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