我正在用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。
答案 0 :(得分:1)
对于不匹配单词中的每个字母,您要递减guess_wrong
,对于“整体猜测”,请不要递减一次。
您可能想将guess_wrong = guess_wrong - 1; // aka guess_wrong--
移出for循环,而只进行if (!valid_guess)
。