我正在用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。
对于不匹配的单词中的每个字母递减guess_wrong
,而不是“整个猜测”一次。
你可能想把guess_wrong = guess_wrong - 1; // aka guess_wrong--
移出for循环,只做if (!valid_guess)
。