• 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:

          请自己写。 

  • 相关阅读:
    SpringBoot 官方文档中文版
    SpringBoot 官方文档中文版
    SpringBoot 官方文档中文版
    RK 打包脚本 make_ext4fs system.img
    Linux安装docker-compose
    Linux使用docker安装Jenkins 并进行jar包发布
    JAVA把InputStream 转 字节数组(byte[])
    SpringBoot简单整合分布式任务调度平台(XXL-JOB)
    SpringBoot项目bootstrap.yml配置文件不加载
    JAVA中Base64和byte数组(byte[]) 相互转换
  • 原文地址:https://www.cnblogs.com/F-itachi/p/9974347.html
Copyright © 2020-2023  润新知