4.8.3 变量与常量的初始化
接下来是程序的main()函数,并且为游戏初始化一些变量和常量。
- 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代表允许玩家猜错的最多次数。words是包含可能猜测的单词的向量。程序使用random_shuffle()算法打乱words,然后将向量中的第一个单词赋值给THE_WORD,它就是玩家必须猜的那个神秘的单词。wrong代表玩家已经猜错的次数。soFar代表玩家目前所猜的单词。soFar以一系列短横线开头,每个短横线代表神秘单词中的一个字母。当玩家猜中单词中的某个字母时,程序将相应位置的短横线替换成该字母。