• Java 7.35 游戏:猜字游戏(C++&Java)


     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:

          请自己写。 

  • 相关阅读:
    GROUP BY及GROUP BY的高阶用法
    触发器基本语法
    按标识符截取字符串 管道型函数
    delphi try except语句 和 try finally语句用法
    Qt 文件的操作
    c++ string 转double
    结构体变量的 extern 使用方法,转--
    c++ 生成dll文件并调用-转
    基2时域抽取FFT、IFFT的C++实现代码,另附DFT与IDFT的原始实现--转1
    c++ 生成dll文件并调用
  • 原文地址:https://www.cnblogs.com/F-itachi/p/9974347.html
Copyright © 2020-2023  润新知