Hangman游戏 - while循环条件“包含在数组中”

时间:2014-03-13 03:33:38

标签: c++ arrays

我正在制作一个刽子手游戏。如果他们已经输入了相同的猜测(这些包含在letters []数组中),我有一个问题要求用户重新输入新的猜测(char)。我已经开始使用while循环,要求用户重新进入" guess"匹配存储在数组中的其中一个字符。感谢。

void play(string word)
{
    string copy = word;

    for(int i = 0; i < word.length(); i++)
    {
        copy[i] = ' ';
    }

    bool match = false;
    bool valid = false;
    int chance = 5;
    char letters[26];
    int counter = 0;
    char guess;
    while (chance > 0 && match == false)
    {
        int blanks = 0;
        for (int i = 0; i < word.length(); i++)
        {
            if(copy[i] == ' ')
                blanks++;
        }

        cout << '|';
        for(int i = 0; i < word.length(); i++)
        {
            cout << copy[i] << '|';
        }
        cout << "\t(There are '" << blanks << "' blanks)" << endl;
        cout << "Incorrect letters guessed: ";

        for (int i = 0; i<counter; i++)
        {
            cout << "'" << letters[i] << "' ";
        }

        cout << "\n\nEnter guess: ";
        cin >> guess;
        for(int i = 0; i < counter; i++)
        {
            if(guess == letters[i])
                valid = true;
        }

        while (valid == true)
        {

            for(int i = 0; i < counter; i++)
            {
                if(guess == letters[i])
                    valid = true;
                else
                    valid = false;
            }
            if (valid)
            {
                cout << "\n\nAlready tried that one. Enter guess: ";
                cin >> guess;
            }

        }
        long find = word.find(guess);

        if (find != string::npos)
        {
            copy[find] = word[find];
            for (int i = 0; i < word.length(); i++)
            {
                if (word[i] == word[find])
                {
                    copy[i] = word[find];
                }
            }
        }



        else
        {
            chance--;

            letters[counter] = guess;
            counter++;
            printMan(chance);
        }



        if (copy == word)
        {
            match = true;
        }
    }

    if (match == true)
        cout << "\nYou saved a life! You managed to win! Congrats, cheater." << endl;
    else
        cout << "\nThe man has been hung! You LOSE! The word was '" << word << "', you idiot." << endl;

}

1 个答案:

答案 0 :(得分:0)

 for(int i = 0; i < counter; i++)
        {
            if(guess == letters[i])
                valid = true;
            else
                valid = false;
        }

这个for循环的问题在于,在找到有效猜测之后......你不会停止循环。

你继续检查字母是否等于循环中的下一个值 - 以及下一个和下一个。并且valid一直反复覆盖,直到你到达循环结束 - 此时valid等于{{>>最后字母的检查值letters 1}}。

所以你的&#34;检查猜测&#34;仅当guessletters中的最后一个字母匹配时才会调用代码。

您需要在找到匹配的猜测时查找如何退出循环。