home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter04 / hangman.cpp next >
Encoding:
C/C++ Source or Header  |  2004-04-11  |  2.3 KB  |  79 lines

  1. // Hangman
  2. // The classic game of hangman
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <algorithm>
  8. #include <ctime>
  9. #include <cctype>
  10.  
  11. using namespace std;
  12.  
  13. int main()
  14. {
  15.     // set-up
  16.     const int MAX_WRONG = 8;  // maximum number of incorrect guesses allowed
  17.  
  18.     vector<string> words;  // collection of possible words to guess
  19.     words.push_back("GUESS");
  20.     words.push_back("HANGMAN");
  21.     words.push_back("DIFFICULT");
  22.  
  23.     srand(time(0));
  24.     random_shuffle(words.begin(), words.end());
  25.     const string THE_WORD = words[0];            // word to guess
  26.     int wrong = 0;                               // number of incorrect guesses
  27.     string soFar(THE_WORD.size(), '-');          // word guessed so far
  28.     string used = "";                            // letters already guessed
  29.  
  30.     cout << "Welcome to Hangman.  Good luck!\n";
  31.  
  32.     // main loop
  33.     while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
  34.     {
  35.         cout << "\n\nYou have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
  36.         cout << "\nYou've used the following letters:\n" << used << endl;
  37.         cout << "\nSo far, the word is:\n" << soFar << endl;
  38.  
  39.         char guess;
  40.         cout << "\n\nEnter your guess: ";
  41.         cin >> guess;
  42.         guess = toupper(guess); //make uppercase since secret word in uppercase
  43.         while (used.find(guess) != string::npos)
  44.         {
  45.             cout << "\nYou've already guessed " << guess << endl;
  46.             cout << "Enter your guess: ";
  47.             cin >> guess;
  48.             guess = toupper(guess);
  49.         }
  50.  
  51.         used += guess;
  52.  
  53.         if (THE_WORD.find(guess) != string::npos)
  54.         {
  55.             cout << "That's right! " << guess << " is in the word.\n";
  56.  
  57.             // update soFar to include newly guessed letter
  58.             for (int i = 0; i < THE_WORD.length(); ++i)
  59.                 if (THE_WORD[i] == guess)
  60.                     soFar[i] = guess;
  61.         }
  62.         else
  63.         {
  64.             cout << "Sorry, " << guess << " isn't in the word.\n";
  65.             ++wrong;
  66.         }
  67.     }
  68.  
  69.     // shut down
  70.     if (wrong == MAX_WRONG)
  71.         cout << "\nYou've been hanged!";
  72.     else
  73.         cout << "\nYou guessed it!";
  74.     
  75.     cout << "\nThe word was " << THE_WORD << endl;
  76.  
  77.     return 0;
  78. }
  79.