// Hangman
// The classic game of hangman
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
usingnamespace std;
int main()
{
// set-up
constint 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<unsignedint>(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(), '-'); // word guessed so far
string used = ""; // letters already guessed
cout << "Welcome to Hangman. 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 following letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
char guess;
cout << "\n\nEnter your guess: ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter your guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
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 (unsignedint 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;
}
This is in the book I'm learning, and I feel that seen as I am up to the point of this program I should be able to understand it.
There's bit I get, and there's bits I don't get. I am still a beginner (been learning c++ for about 2-3) with a few weeks off due exams. I personally think it was quite a hard program to get introduced to, as it is basically a game without UI and graphics. And I'm still at the point where I'm only creating basic programs.
When it comes to understanding a program, you might consider it on two levels.
One is the overall flow and structure, that is, what the program is supposed to achieve. Then at a more detailed level, you might consider some of the individual statements, or small groups of statements. You don't necessarily need to hold the entire thing in your head simultaneously.