zoukankan      html  css  js  c++  java
  • C++实现另一个猜数字游戏

    C语言实现一个简单的猜数字游戏 中,我们用C语言实现了一个简单的猜数字游戏,但是整个逻辑都在main()函数中,这种一个main函数从头到尾的方式很不好,今天我们用C++来将这个程序改写一下。 整个程序的大部分工作,实际上是由主持人这个角色完成的,包括确定最初的目标数字,判断猜测的数字大小,因此,我们可以将主持人抽象成Judge这个类,让这个类来负责这些工作,而主函数则负责与之交互,完成游戏过程。

    #include <iostream>
    #include <random>
    using namespace std;
     
    class Judge
    {
    public:
        Judge()
        {
            max = 100;
            min = 0;
            
            default_random_engine eng;
            random_device rnd_device;
            eng.seed(rnd_device());
            uniform_int_distribution<int> nums(min,max);
            target = nums(eng);
        }
        bool judge(int guess)
        {
            ++count;
            if(target == guess)
            {
                return true;
            }
            else if(target > guess)
            {
                cout<<"the target is greater than "<<guess<<endl;
                min = guess;
                return false;
            }
            else
            {
                cout<<"the target is less than "<<guess<<endl;
                max = guess;
                return false;
            }
        }
        int getmin()
        {
            return min;
        }
        int getmax()
        {
            return max;
        }
        int getcount()
        {
            return count;
        }
    private:
        int target;
        int max;
        int min;
        int count;
    };
     
    int main()
    {
        cout<<"WELCOME"<<endl;
        while(true)
        {
            Judge j;
            while(true)
            {
                cout<<"please guess a number between "
                    <<j.getmin()<<" - "<<j.getmax()<<endl;
                int guess = 0;
                
                cin.sync();
                cin>>guess;
                if(cin.fail())
                {
                    cin.clear();
                    continue;
                }
                if(j.judge(guess))
                {
                    cout<<"You WIN!"<<endl;
                    break;
                }
            }
            cout<<"Do you want to play again?(Y-yes,N-no)";
            char c = 'Y';
            cin>>c;
            
            if('Y'!=toupper(c))
                break;
        }
     
        return 0;
    } 

    这里,主要用到了C++中类的封装机制以及C++11中随机数的生成方式 其实,在这个程序中还有不完善的地方,比如对输入的处理,对用户提示等,有兴趣的朋友,可以自己完善,锻炼自己的动手能力。

    转自:http://www.howzhi.com/course/3387/lesson/42391

  • 相关阅读:
    Android KeyCode列表
    贪吃蛇游戏
    二叉树的深度
    二叉树的层次遍历
    二叉树的后序遍历
    二叉树的中序遍历
    《算法》第四版随笔
    踏上计算机网络学习之路
    二叉树的前序遍历
    登上刷题之路
  • 原文地址:https://www.cnblogs.com/kingshow123/p/cplusngame.html
Copyright © 2011-2022 走看看