2025年2月10日月曜日

C ++で3桁の数字を当てるゲームのコードを作成してください 。1ゲームは10回として結果を表示してください。

 はい、承知いたしました。C++で3桁の数字当てゲームのコードを作成します。

C++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using namespace std;

// 3桁のランダムな数字を生成する関数
vector<int> generate_random_number() {
    vector<int> digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    random_shuffle(digits.begin(), digits.end());
    return {digits[0], digits[1], digits[2]};
}

// ユーザーの入力を検証する関数
vector<int> get_user_input() {
    int input;
    while (true) {
        cout << "3桁の数字を入力してください: ";
        cin >> input;
        if (cin.fail() || input < 100 || input > 999) {
            cout << "無効な入力です。3桁の数字を入力してください。" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
        } else {
            break;
        }
    }
    return {input / 100, (input % 100) / 10, input % 10};
}

// 数字と桁が一致している数をカウントする関数
int count_correct_digits(const vector<int>& secret_number, const vector<int>& user_input) {
    int count = 0;
    for (int i = 0; i < 3; ++i) {
        if (secret_number[i] == user_input[i]) {
            count++;
        }
    }
    return count;
}

// 数字は含まれているが桁が一致していない数をカウントする関数
int count_incorrect_digits(const vector<int>& secret_number, const vector<int>& user_input) {
    int count = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            if (i != j && secret_number[i] == user_input[j]) {
                count++;
            }
        }
    }
    return count;
}

int main() {
    srand(time(0));

    cout << "3桁の数字当てゲーム" << endl;

    vector<int> secret_number = generate_random_number();
    int attempts = 0;

    while (attempts < 10) {
        attempts++;
        cout << "試行回数: " << attempts << endl;

        vector<int> user_input = get_user_input();

        int correct_digits = count_correct_digits(secret_number, user_input);
        int incorrect_digits = count_incorrect_digits(secret_number, user_input);

        cout << "正解: " << correct_digits << "桁" << endl;
        cout << "ニアミス: " << incorrect_digits << "桁" << endl;

        if (correct_digits == 3) {
            cout << "おめでとうございます!" << endl;
            cout << "正解は ";
            for (int digit : secret_number) {
                cout << digit;
            }
            cout << " でした。" << endl;
            return 0;
        }
    }

    cout << "ゲームオーバー" << endl;
    cout << "正解は ";
    for (int digit : secret_number) {
        cout << digit;
    }
    cout << " でした。" << endl;

    return 0;
}

このコードでは、まず3桁のランダムな数字を生成します。次に、ユーザーに数字を入力させ、入力された数字と正解の数字を比較します。数字と桁が一致している数と、数字は含まれているが桁が一致していない数をカウントし、結果を表示します。これを10回繰り返します。もし10回以内に正解できれば「おめでとうございます!」と表示し、10回以内に正解できなければ「ゲームオーバー」と表示します。

このコードは、C++の基本的な文法とアルゴリズムを使用しており、プログラミングの学習にも役立つと思います。

0 件のコメント:

コメントを投稿