1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
//Chapter 5 Exercise
//Rewrite the Hangman game from Chapter 4 using functions. Include a function to get the player's guess and another function to determine whether the player's guess is in the secret word.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;
char playerGuess( string used );
void determine( const string THE_WORD, char guess, string soFar, int wrong );
void ending( int wrong, const int MAX_WRONG, const string THE_WORD );
int main( )
{
const int MAX_WRONG = 8;
vector<string> words;
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[1];
int wrong = 0;
string soFar( THE_WORD.size( ), '-');
string used = " ";
cout << "Welcome to Hangman. Good luck!\n";
while( (wrong < MAX_WRONG) && ( soFar != THE_WORD ) )
{
cout << "\nYou have " << ( MAX_WRONG - wrong );
cout << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
char guess = playerGuess( used );
used += guess;
determine( THE_WORD, guess, soFar, wrong );
}
ending( wrong, MAX_WRONG, THE_WORD );
system( "pause" );
return 0;
}
char playerGuess( string used )
{
char guess;
cout << "\n\nEnter your guess: ";
cin >> guess;
guess = toupper( guess );
while( used.find( guess ) != string::npos )
{
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter your guess: ";
cin >> guess;
guess = toupper( guess );
}
return guess;
}
void determine( const string THE_WORD, char guess, string soFar, int wrong )
{
if( THE_WORD.find( guess ) != string::npos )
{
cout << "That's right! " << guess << " is in the word.\n";
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;
}
}
void ending( int wrong, const int MAX_WRONG, const string THE_WORD )
{
if( wrong == MAX_WRONG )
{
cout << "\nYou've been hanged!";
}
else
{
cout << "\nYou guessed it!";
}
cout << "\nThe word was " << THE_WORD << endl;
cout << "\n";
}
|