3.7.2 选择单词
接下来的任务是选择一个单词来打乱顺序,玩家将要猜的就是这个单词。首先,程序创建了一个单词列表以及提示:
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Do you feel you’re banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it?"},
{"persistent", "Keep at it."},
{"jumble", "It’s what the game is all about."}
};
程序用单词和相应的提示声明并初始化了一个二维数组。枚举类型定义了用于访问数组的枚举数。例如,WORDS[x][WORD]总是表示单词的string对象,而WORDS[x][HINT]则是相应的提示。
技巧
还可以很方便地在枚举类型中最后添加一个枚举数,用来存储元素的个数,如下例所示:
enum difficulty {EASY, MEDIUM, HARD, NUM_DIFF_LEVELS};
cout << "There are " << NUM_DIFF_LEVELS << " difficulty levels.";
上面的代码中NUM_DIFF_LEVELS为3,恰好是枚举类型中难度等级的数目。因此,代码第二行显示消息“There are 3 difficulty levels.”。
接下来随机地选择一个单词。
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][WORD]; // word to guess
string theHint = WORDS[choice][HINT]; // hint for word
上面的代码基于数组中单词的数目生成了一个随机索引号,然后将该索引处的单词和相应提示赋值给了变量theWord和theHint。
3.7.3 单词乱序
有了给玩家猜测的单词后,现在需要生成一个该单词的乱序版本。
string jumble = theWord; // jumbled version of word
int length = jumble.size();
for (int i = 0; i < length; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
上面的代码将单词复制到jumble用于乱序。程序生成了string对象中的两个随机位置,并交换这两个位置的字符。交换操作的次数等于单词的长度。