3.7.2 選擇單詞
接下來的任務(wù)是選擇一個(gè)單詞來打亂順序,玩家將要猜的就是這個(gè)單詞。首先,程序創(chuàng)建了一個(gè)單詞列表以及提示:
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."}
};
程序用單詞和相應(yīng)的提示聲明并初始化了一個(gè)二維數(shù)組。枚舉類型定義了用于訪問數(shù)組的枚舉數(shù)。例如,WORDS[x][WORD]總是表示單詞的string對(duì)象,而WORDS[x][HINT]則是相應(yīng)的提示。
技巧
還可以很方便地在枚舉類型中最后添加一個(gè)枚舉數(shù),用來存儲(chǔ)元素的個(gè)數(shù),如下例所示:
enum difficulty {EASY, MEDIUM, HARD, NUM_DIFF_LEVELS};
cout << "There are " << NUM_DIFF_LEVELS << " difficulty levels.";
上面的代碼中NUM_DIFF_LEVELS為3,恰好是枚舉類型中難度等級(jí)的數(shù)目。因此,代碼第二行顯示消息“There are 3 difficulty levels.”。
接下來隨機(jī)地選擇一個(gè)單詞。
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
上面的代碼基于數(shù)組中單詞的數(shù)目生成了一個(gè)隨機(jī)索引號(hào),然后將該索引處的單詞和相應(yīng)提示賦值給了變量theWord和theHint。
3.7.3 單詞亂序
有了給玩家猜測(cè)的單詞后,現(xiàn)在需要生成一個(gè)該單詞的亂序版本。
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;
}
上面的代碼將單詞復(fù)制到j(luò)umble用于亂序。程序生成了string對(duì)象中的兩個(gè)隨機(jī)位置,并交換這兩個(gè)位置的字符。交換操作的次數(shù)等于單詞的長度。