C++ 猜数字

#include <iostream>
#include <random>
#include <limits>

namespace random
{
    std::random_device rd;
    std::seed_seq rr = {rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
    std::mt19937 mt{rr};

    int get(int min, int max)
    {
        std::uniform_int_distribution uid{min, max};
        return uid(mt);
    }

} // namespace random

int getGuess(int i)
{
    while (true)
    {
        std::cout << "Guess #" << i << ":";
        int guess{};
        std::cin >> guess;
        if (!std::cin || guess < 1 || guess > 100)
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Please enter the correct number!" << '\n';
            continue;
        }

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return guess;
    }
}

bool playGame(int guesses, int random)
{
    std::cout << "Let's play a game. I'm thinking of a number between 1 and 100. You have " << guesses << " tries to guess what it is. " << '\n';
    for (int i{1}; i <= guesses; i++)
    {

        int guess{getGuess(i)};

        if (random > guess)
            std::cout << "Your guess is too low." << '\n';
        else if (random < guess)
            std::cout << "Your guess is too high." << '\n';
        else // random == guess
            return true;
    }
    return false;
}

bool playAgain()
{
    while (true)
    {
        std::cout << "Would you like to play again (y/n)? ";
        char ch{};
        std::cin >> ch;

        switch (ch)
        {
        case 'y':
            return true;
        case 'n':
            return false;
        default:
            std::cout << "Please enter the correct option!" << '\n';
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}

int main()
{
    do
    {
        constexpr int guesses{7};
        int num{random::get(1, 100)};

        bool won{playGame(guesses, num)};
        if (won)
        {
            std::cout << "Correct! You win!" << '\n';
        }
        else
        {
            std::cout << "Sorry, you lose. The correct number was " << num << "\n";
        }

    } while (playAgain());

    return 0;
}
posted @ 2023-02-17 17:03  Leafmoes  阅读(40)  评论(0编辑  收藏  举报