C++ 数当てゲーム

#include <iostream>
#include <random>

int main() {
    // 1. 初期化処理(1〜100のランダムな正解を生成)
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(1, 100);

    int target = dist(gen);
    int guess = 0;
    int attempts = 0;
    bool isGameOver = false;

    std::cout << "=== 数当てゲーム (1〜100) ===" << std::endl;
    std::cout << "コンピュータが思い浮かべた数字を当ててください!" << std::endl;

    // 2. ゲームループ(クリアするまで繰り返す)
    while (!isGameOver) {
        std::cout << "\n数字を入力 > ";

        // 数字以外の不正な入力に対するエラー処理
        if (!(std::cin >> guess)) {
            std::cin.clear();
            std::cin.ignore(10000, '\n');
            std::cout << "有効な数字を入力してください。" << std::endl;
            continue;
        }

        attempts++;

        // 3. 判定と結果の出力
        if (guess < target) {
            std::cout << "もっと【大きい】数字です。" << std::endl;
        }
        else if (guess > target) {
            std::cout << "もっと【小さい】数字です。" << std::endl;
        }
        else {
            std::cout << "\n正解! " << attempts << " 回目でクリアしました!" << std::endl;
            isGameOver = true; // ループ終了フラグを立てる
        }
    }

    // 4. 終了処理
    std::cout << "ゲームを終了します。お疲れ様でした!" << std::endl;
    return 0;
}