Ps:
有人可能好奇我为什么大费周章的去写主函数,而不直接把所有操作放在类中,Why?类就好比骨干(存放核心的数据和功能),最好提供接口, 避免了类中的输入输出,当然,这也不是绝对的。
C++:
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
class GuessNumber {
public:
void Get();
int Guess(char);
string get_g_word() {
return g_word;
}
string get_word() {
return word;
}
int get_miss() {
return miss;
}
private:
int miss = 0;
string words[7] = { "write","that","important","transform","judge","index","run" };
string word;
string g_word;
};
void GuessNumber::Get() {
srand((unsigned int)time(0)); //随机数
word = words[rand() % 7 ]; //伪随机数?——跟运行时间有关
g_word=string(word.length(), '*');
}
int GuessNumber::Guess(char ch) {
if (word.find(ch) == string::npos) { //字母没有出现在单词中
miss++;
return 2;
}
if (g_word.find(ch) != string::npos) { //已猜过(出现在g_word中)
miss++;
return 1;
}
for (int i = 0; i < word.length(); i++) //猜中,修改g_word
if (word[i] == ch)
g_word[i] = ch;
return 0;
}
int main() {
char ch;
string str;
GuessNumber My;
int key;
while (1) {
My.Get();
while (My.get_g_word() != My.get_word()) {
cout << "(Guess) Enter a letter in word " << My.get_g_word() << " > ";
cin >> ch;
key = My.Guess(ch);
if (key == 2)
cout << " " << ch << " is not in the word" << endl;
else if (key == 1)
cout << " " << ch << " is already in the word" << endl;
}
cout << "The word is " << My.get_word() << ". You missed " << My.get_miss() << " time " << endl;
cout << "Do you want to guess another word? Enter y or n >";
cin >> str;
if (str == "n")
break;
system("cls"); //清屏
}
return 0;
}
Java:
请自己写。