zoukankan      html  css  js  c++  java
  • 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:

          请自己写。 

  • 相关阅读:
    第16章 行为型模式—命令模式
    第15章 行为型模式—职责链模式
    第14章 结构型模式—代理模式
    第12章 结构型模式—外观模式
    第11章 结构型模式—装饰模式
    第10章 结构型模式—组合模式
    第9章 结构型模式—桥接模式
    第8章 结构型模式—适配器模式
    Qt中Qstring,char,int,QByteArray之间到转换(转)
    QT:QByteArray和QByteArray、char *(转)
  • 原文地址:https://www.cnblogs.com/F-itachi/p/9974347.html
Copyright © 2011-2022 走看看