随机字母生成器游戏

时间:2017-03-02 20:52:47

标签: c++

警告:我是编程的新手!我正在尝试为类项目创建一个随机字母生成器游戏。我觉得我有一个不错的开始,但我有点几点困难。

该节目应该询问玩家他们想玩多少场比赛(1-5)。他们每场比赛获得的最大猜测数是5,然后如果没有猜到,它应该打印出正确的答案。事实上,我有它,以便它将运行正确数量的猜测,但不是游戏,它的剂量cout<<所有猜测完成后的正确答案。感谢任何帮助。谢谢。

#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
    char alphabet [27];
    int number_of_games;
    char guess;
    int x = 1;
    srand(time(0));
    int n = rand() % 26 + 1;  

        cout<<"Weclome to the Letter Guessing game!\n";
        cout<<"You have 5 chances to guess each letter.\n \n";
        cout<<"How many games do you want to play?\n";
        cin >> number_of_games; 

        cout<<"**************************************************\n\n";

    while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses

    {   
        if (number_of_games < 1)
        {
            cout<< "Lets play game " << number_of_games << '\n';
        }
        //cout << (char)(n+97); //cheat to make sure working
        cout<<"Enter your guess: ";
        cin >> guess;
        int guessValue = int(guess);

        if (guessValue > (n+97))
        {
            cout<<"The letter you are trying to guess is before " <<guess <<"\n"; 
        }
        else if (guessValue < (n+97))
        {
            cout<<"The letter you are trying to guess is after " <<guess << "\n";
        }
        else if(  (char)(n+97))
        {
            cout << "The answer you were looking for was " << (char)(n+97) << "\n";
        }
        else
        {
            cout<<"Your guess is correct! \n";
            break;
        }
        //if answer is not right after x tries, cout the correct answer
        x++;
    }

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

你可以使用“嵌套循环” - 游戏的外循环和转弯的内循环。我在我的例子中使用过for循环。

此外,无需将所有内容转换为intchar是一个整数类型,可以像数字一样使用:

while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
    // Select a new char (a-z) for each game
    char n = 97 + rand() % 27;
    cout << "Lets play game " << x << '\n';
    // 5 guesses
    for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
        cout << "Enter your guess: ";
        cin >> guess;
        if (guess > n)
        {
            cout << "The letter you are trying to guess is before " << guess << "\n";
        }
        else if (guess < n)
        {
            cout << "The letter you are trying to guess is after " << guess << "\n";
        }
        else
        {
            cout << "Your guess is correct! \n";
            // Break out of the inner for loop, not the while
            break;
        }
    }
    x++;
}