2017-10-06 17 views
-1

シンプルな文字の推測ゲームを作成する必要があります。これまでのところ、私はほとんどすべてを終えましたが、1つのタスクに関しては何をすべきかについてはわかりません。だから、 ゲームは、それが入力に二つのことをユーザーに尋ねる開始する前に:ユーザーの入力に応じてランダムな文字を生成する

は、別の文字の量を入力します(4は、例えば入力された場合、選択した文字が4文字からなり、唯一のAD

パターンLENG:)

は、パターンの長さを入力し入力がうまくいきましたが、生成するコード関数を変更して異なる文字の量を追加する方法を考え出すのに苦労しています。

ヒント?私ものような、事前にいくつかの検証を追加することをお勧めし

uniform_int_distribution<char> dis{'A', 'A' + amount - 1}; 

#include <iostream> 
#include <random> 
#include <string> 
using namespace std; 

size_t len; 
string str; 

void generate_code() 
{ 
    str.string::reserve(len); 

    random_device rd; 
    mt19937 gen{rd()}; 
    uniform_int_distribution<char> dis{'A', 'Z'}; 

    for (size_t i = 0; i < len; i++) 
    { 
     str += dis(gen); 
    } 
} 

void guess_checker() 
{ 
    string guess{}; 
    size_t trial_count = 0, match_count = 0; 
    do 
    { 
     cout << "Enter your guess: " << endl; 
     cin >> guess; 
     if (guess.size() != len) 
     { 
      cout << "error: invalid guess" << endl; 
     } 
     else 
     { 
      match_count = 0; 
      for (size_t i = 0; i < len; i++) 
      { 
       if (guess[i] == str[i]) 
       ++match_count; 
      } 
      cout << "You guessed " << match_count << " character" 
       << (match_count == 1 ? "" : "s") << " correctly." << endl; 
     } 
     ++trial_count; 
    } 
    while (match_count != len); 
    cout << "You guessed the pattern in " << trial_count << " guess" 
    << (trial_count == 1 ? "" : "es") << "." << endl; 
} 

int main() 
{ 
    int amount; 

    cout << "Enter the amount of different characters: "; 
    cin >> amount; 
    cout << "Enter the pattern length: "; 
    cin >> len; 
    generate_code(); 
    guess_checker(); 

    return 0; 
} 
+0

'str.string ::準備金(LEN); 'あなたは曖昧さを取り除く必要はないので、単に' str.reserve(len); 'を使う:P – Rakete1111

+0

あなたの配布の制限を変更したいならば、私はあなたの配布の上限を変更したいと思う。 「A」から「Z」の代わりに「A」から「A」+「amount」を選択します。 –

+0

変数をグローバルにするのではなく、引数を使って関数に情報を渡すことをお勧めします。 –

答えて

0

は、単にあなたの発電機のラインを変更

if (amount < 1 || amount > 26) { 
    cout << "Bad amount" << endl; 
    // exit or something 
} 
関連する問題