【问题标题】:I have a hangman game I'm making, and I need help figuring out why it's not fully working我正在制作一个刽子手游戏,我需要帮助找出它为什么不能完全运行
【发布时间】:2019-03-29 03:28:51
【问题描述】:

我正在用 C++ 制作一个刽子手游戏,我即将完成,但是我有一个主要问题。我必须让游戏只允许用户 4 次猜测,但我的程序没有记录正确的猜测次数。

我尝试更改变量以及 if 和 else 语句中关于猜测的条件。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
cout << "Welcome to hangman!" << endl;

char choice = 'y';

while (choice == 'y') {
    string word;
    cout << "Enter a word to guess: ";
    getline(cin, word);

    if (word.empty()) {
        cout << "The word should not be blank.\n";
        continue;
    }

    bool contain_space = false;
    for (char c : word) {
        if (isspace(c)) {
            contain_space = true;
            break;
        }
    }

    if (contain_space) {
        cout << "The word cannot contain spaces.\n";
        continue;
    }

    vector <bool> index;
    for (int i = 0; i < word.size(); i++) {
        index.push_back(false);
    }

    **int guess_correct = 0;**
    int guess_wrong = 4;
    char letter;

    while (guess_wrong >= 0 && guess_correct < word.size()) {
        bool valid_guess = true;
        cout << "Guess a letter." << endl;
        cin >> letter;
        for (int i = 0;i < word.size(); i++) {
            if (word[i] == letter) {
                valid_guess = true;
                index[i] = true;
                guess_correct++;
                break;

            }
            else {
                guess_wrong = guess_wrong - 1;
            }

        }

        for (int i = 0; i < word.size(); i++) {
            if (index[i] == true) {
                cout << word[i] << "\t";
            }
            else {
                cout << "___\t";
            }
        }
        cout << endl;
    }


    cout << "Would you like to play again? (y/n)" << endl;
    cin >> choice;
    cin.ignore();
}
return 0;
}

黑色勾号显示我卡住的代码部分的开头。每次我运行它,它都会让我以正确的猜测完成游戏,但错误的猜测不允许 4。

【问题讨论】:

  • bool valid_guess = true; 您可能希望将其初始化为 false 。如果在你的for (int i = 0;i &lt; word.size(); i++) { } 之后它仍然是错误的,那么只有这样才能减少guess_wrong

标签: c++


【解决方案1】:

您正在为单词中不匹配的每个字母递减guess_wrong,而不是为“整个猜测”递减一次。

您可能希望将 guess_wrong = guess_wrong - 1; // aka guess_wrong-- 移出 for 循环,并且只执行 if (!valid_guess)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多