我一直在嘗試使用函數創建一個hang子手遊戲。一個讓用戶猜測,另一個功能是看用戶猜測是否在矢量中創建的單詞中。任何關於如何獲得玩家的幫助猜測以及如何創建一個函數來查看這個猜測是否是這個單詞將不勝感激。代碼如下。我將如何創建一個函數,以確定用戶輸入是否包含在向量中的單詞
char playersGuess();
int main()
{
//setup
const int MAX_WRONG = 8; //maximum number of incorrect guesses allowed
vector<string> words; //collection of possible words to guess
words.push_back("GUESS");
words.push_back("HANGMAN");
words.push_back("DIFFICULT");
srand(static_cast<unsigned int>(time(0)));
random_shuffle(words.begin(), words.end());
const string THE_WORD = words[0]; //word to guess
int wrong = 0; //number of incorrect guesses
string soFar(THE_WORD.size(), '-'); //words guessed so far
string used = ""; //letters already guessed
cout << "Welcome to Hangman 2. Good Luck!\n";
//main loop
while ((wrong < MAX_WRONG && soFar != THE_WORD))
{
cout << "\n\nYou have " << (MAX_WRONG - wrong);
cout << " incorrect guesses left.\n";
cout << "\nYou've used the follwoing letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
char guess = playersGuess();
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed " << guess << endl;
playersGuess();
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
//update soFra to include newly guessed letter
for (int i = 0; i < THE_WORD.length(); ++i)
{
if (THE_WORD[i] == guess)
{
soFar[i] = guess;
}
}
}
else
{
cout << "Sorry. " << guess << " isn't in the word.\n";
++wrong;
}
}
//shut down
if (wrong == MAX_WRONG)
{
cout << "\nYou've been hanged!";
}
else
{
cout << "\nYou guessed it!";
}
cout << "\nThe Word was " << THE_WORD << endl;
return 0;
}
char playersGuess()
{
char guess;
cout << "\n\nEnter your guess: ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
return guess;
}
謝謝我指派玩家猜測一個變量,它現在的作品。但是我仍然在努力創造一個函數來檢查玩家猜測哪裏是正確的。 – 2015-02-05 19:35:25