< Previous | Contents | Next >
Next I start the main() function and initialize variables and constants for the game.
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(), ’-’); //word guessed so far
string used = ""; //letters already guessed
cout << "Welcome to Hangman. Good luck!\n";
MAX_WRONG is the maximum number of incorrect guesses the player can make. words is a vector of possible words to guess. I randomize words using the random_shuffle() algorithm, and then I assign the first word in the vector to THE_WORD, which is the secret word the player must guess. wrong is the number of incorrect guesses the player has made. soFar is the word guessed so far by the player. soFar starts out as a series of dashes—one for each letter in the secret word. When the player guesses a letter that’s in the secret word, I replace the dash at the corresponding position with the letter.