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 108 109 110 111 112 113 114 115 116 117
|
// hangman_2.0_chapter5.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <ctime>
#include <cctype>
using namespace std;
void prompt();
char getguess();
void yesorno(const string, char, string, int);
int main()
{
//set up
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 the word to be guessed
random_shuffle(words.begin(), words.end());
const string THE_WORD = words[0]; /* words is a vector of possible words to guess.
THE_WORD has been assigned the first word in the
word to be guessed */
int wrong = 0; // number of incorrect guesses
string soFar(THE_WORD.size(), '_'); // word guessed so far.. each letter in word rep by '_'
string used = ""; // letters already guessed
cout << "Welcome to Hangman 2.0. Good Luck!\n";
// main loop
while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n\nYou have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used;
cout << "\nSo far the word is: \n " << soFar;
// Getting the Players' Guess
prompt();
char guess = getguess();
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed " << guess;
prompt();
char guess = getguess();
//guess = toupper(guess);
}
used += guess;
yesorno(THE_WORD, guess, soFar, wrong); //calling function yesorno(const, char, string, int);
} //End the Game
//shut down
if (wrong == MAX_WRONG)
{
cout << "\nYou've used you're last guess! GAME OVER";
}
else
{
cout << "\nYou guessed it!";
}
cout << "\nThe word was " << THE_WORD;
return 0;
}
void prompt()
{
cout << "Enter your guess: ";
}
char getguess()
{
char guess;
cin >> guess; //getting character / answer from user
guess = toupper(guess); //make uppercase since secret word is uppercase
return guess; // returning the answer to main;
}
void yesorno(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";
//update soFar to include newly guessed letter
for (unsigned 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;
}
}
|