所以我一直在自学如何编写 C++ 代码。我购买了Michael Dawson所著的《通过游戏编程开始 C++》,第三版,其中有一章介绍了循环。在本章快结束时,您制作了一个单词混乱的游戏。我想更进一步,并随机选择了 5 个单词。但问题是,它的值总是 5,因此总是选择第五个单词。
代码如下
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
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 this game is about!"}
};
srand(time(0));
int preWord = rand() % 3;
string tempWord;
string theWord = WORDS[preWord][WORD]; //word to guess
string theHint = WORDS[preWord][HINT]; //hint for word
if (preWord = 1)
{
theWord = "wall";
tempWord = "wall";
}
if (preWord = 2)
{
theWord = "glasses";
tempWord = "glasses";
}
if (preWord = 3)
{
theWord = "labored";
tempWord = "labored";
}
if (preWord = 4)
{
theWord = "persistent";
tempWord = "persistent";
}
if (preWord = 5)
{
theWord = "jumble";
tempWord = "jumble";
}
int length = theWord.size();
for (int i = 0; i < length; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = theWord[index1];
theWord[index1] = theWord[index2];
theWord[index2] = temp;
}
cout << "\t\t\tWelcome to the Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The word is: " << theWord;
cout << "\nvariable 'preWord' is: " << preWord;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
while ((guess != tempWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
}
else
{
cout << "Sorry, that's not it.";
}
cout <<"\n\nYour guess: ";
cin >> guess;
}
if (guess == tempWord)
{
cout << "\nThat's it! You guessed it!\n";
}
cout << "\nThanks for playing!\n";
return 0;
}