• Coursera课程笔记----C++程序设计----Week6


    多态与虚函数(week 6)

    多态与虚函数的基本概念

    虚函数

    • 在类的定义中,前面有virtual关键字的成员函数就是虚函数

      class base{
        virtual int get();
      };
      int base::get(){}
      
    • virtual关键字只用在类定义里的函数声明中,写函数体时不用

    • 构造函数和静态成员函数不能是虚函数

    多态的表现形式(一)

    • 派生类的指针可以赋值给基类指针

    • 通过基类指针调用基类和派生类中的同名虚函数时:

      1. 若该指针指向一个基类的对象,那么被调用的是基类的虚函数
      2. 若该指针指向一个派生类的对象,那么被调用的是派生类的虚函数

      这个机制就叫做“多态

    多态的表现形式(二)

    • 派生类的对象可以赋给基类引用

    • 通过基类引用调用基类和派生类中的同名虚函数时:

      1. 若该引用引用的是一个基类的对象,那么被调用的是基类的虚函数
      2. 若该引用引用的是一个派生类的对象,那么被调用的是派生类的虚函数

      这个机制就叫做“多态”

    多态的作用

    在面向对象的程序设计中使用多态,能够增强程序的可扩充性,即程序需要修改或增加功能的时候,需要改动和增加的代码较少。

    使用多态的游戏程序实例

    基本思路

    • 为每个怪物类编写 Attack、FightBack和Hurted成员函数

    • Attack函数表现攻击动作,攻击某个怪物,并调用被攻击怪物的Hurted函数,以减少被攻击怪物的生命值,同时也调用被攻击怪物的FightBack成员函数,遭受被攻击怪物的反击

    • Hurted函数减少自身生命值,并表现受伤动作

    • FightBack成员函数表现反击动作,并调用被反击对象的Hurted成员函数,使被反击对象受伤。

    • 设置基类CCreature,并且使CDragon,CWolf等其他类都从CCreature派生而来。

      image-20200520140701908

    非多态的实现方法

    • 有n种怪物,CDragon类中就会有n个Attack成员函数,以及n个FightBack成员函数,对其他类也是如此,非常麻烦。

    多态的实现方法

    //基类CCreature
    class CCreature{
      protected:
      int m_nLifeValue,m_nPower;
      public:
      virtual void Attack(CCreature* pCreature){};
      virtual void Hurted(int nPower){};
      virtual void FightBack(CCreature *pCreature){};
    };
    
    //派生类 CDragon
    class CDragon:public CCreature{
      public:
      virtual void Attack(CCreature* pCreature){};
      virtual void Hurted(int nPower){};
      virtual void FightBack(CCreature *pCreature){};
    };
    
    void CDragon::Attack(CCreature *p)
    {
      //省略一些代码
      p->Hurted(m_nPower);//多态
      p->FightBack(this);//多态
    }
    void CDragon::Hurted(int nPower)
    {
        //省略一些代码
      m_nLifeValue -= nPower;
    }
    void CDragon::FightBack(CCreature *p)
    {
      p->Hurted(m_nPower/2);//多态
    }
    

    多态实现方法的优势

    • 如果想要增加新的怪物种类,只需要编写新类,原有的类可以原封不动

    更多多态程序实例

    例一:几何体处理程序

    • 几何形体处理程序:输入若干个几何形体的参数,要求按面积排序输出。输出时要指明形状。

    • 输入

      • 第一行是几何形体数目n(不超过100),下面有n行,每行以一个字母c开头
      • 若c是‘R’,则代表一个矩形,本行后面跟着两个整数,分别是矩形的宽&高
      • 若c是‘C’,则代表一个圆,本行后面跟着一个整数代表其半径
      • 若c是‘T',则代表一个三角形,本行后面跟着三个整数,代表三条边的长度
    • 输出

      • 按面积从小到大依次输出每个几何形体的种类及面积。每行一个几何形体,输出格式为
        • 形体名称:面积
    #Include <iostream>
    #include <stdlib.h>
    #include <math.h>
    using namespace std;
    class CShape
    {
      public:
      virtual double Area() = 0;//纯虚函数
      virtual void PrintInfo() = 0;
    };
    
    class CRectangle:piblic CShape
    {
      public:
      int w,h;
      virtual double Area();
      virtual void PrintInfo();
    }
    
    class CCircle:piblic CShape
    {
      public:
      int r;
      virtual double Area();
      virtual void PrintInfo();
    }
    
    class CTriangle:piblic CShape
    {
      public:
      int a,b,c;
      virtual double Area();
      virtual void PrintInfo();
    }
    
    double CRectangle::Area(){
      return w*h;
    }
    void CRectangle::PrintInfo(){
      cout<<"Rectangle:"<<Area()<<endl;
    }
    
    double CCircle::Area(){
      return 3.14*r*r;
    }
    void CCircle::PrintInfo(){
      cout<<"Circle:"<<Area()<<endl;
    }
    double CTriangle::Area(){
      double p = (a+b+c)/2.0;
      return sqrt(p*(p-a)*(p-b)*(p-c));//Helen公式
    }
    void CTriangle::PrintInfo(){
      cout<<"Triangle:"<<Area()<<endl;
    }
    
    CShape *pShapes[100];
    int MyCompare(const void *s1,const void *s2);
    
    int main()
    {
      int i;int n;
      CRectangle *pr;CCircle *pc;CTriangle *pt;
      cin>>n;
      for(i = 0;i < n;i++){
        char c;
        cin>>c;
        switch(c){
            case'R':
            pr = new CRectangle();
            cin >> pr->w >> pr->h;
            pShapes[i] = pr;
            break;
            case'C':
            pc = new CCircle();
            cin >> pc->r;
            pShape[i] = pc;
            break;
            case'T':
            pt = new CTriangle();
            cin >> pt->a >> pt->b >> pt->c;
            pShapes[i] = pt;
            break;
        }
      }
      qsort(pShapes,n,sizeof(CShanpe*),MyCompare);
      for(i = 0;i < n;i++)
        pSHapes[i] ->PrintInfo();
      return 0;
    }
    
    int MyCompare(const void *s1, const void *s2)
    {
      double a1,a2;
      CShape* *p1; //s1,s2是void*,不可写“*s1”来取得s1指向的内容
      CShape* *p2;
      p1 = (CShape**)s1;//s1,s2指向pSHapes数组中的元素,数组元素的类型是CShape*
      p2 = (Cshape**)s2;//故p1,p2都是指向指针的指针,类型为CShape **
      a1 = (*p1)->Area();//*p1的类型是CShape*,是基类指针,此句为多态
      a2 = (*p2)->Area();
      if(a1 < a2)
        return -1;
      else if(a2 < a1)
        return 1;
      else
        return 0;
    }
    //如果添加新的几何形体,只需要从CShape派生出CPentagon,以及在main中的switch语句中增加一个case即可
    
    • 用基类指针数组存放指向各种派生类对象的指针,然后遍历该数组,就能对各个派生类对象做各种操作,是很常用的做法。

    例二

    class Base{
      public:
      void fun1(){this->fun2();}//this是基类指针,fun2是虚函数,所以是多态
      virtual void fun2(){cout<<"Base::fun2()"<<endl;}
    };
    class Derived:public Base{
      public:
      virtual void fun2(){cout<<"Derived:fun2()"<<endl;}
    };
    int main(){
      Derived d;
      Base* pBase = &d;
      pBase -> fun1();
      return 0;
    }
    //输出:Derived:fun2()
    
    • 在非构造函数、非析构函数的成员函数中调用虚函数,是多态
    • 在构造函数和析构函数中调用虚函数,不是多态。编译时即可确定调用的函数是自己的类或基类中定义的函数,不会等到运行时才决定调用自己的还是派生类的函数
    • 派生类中和基类中虚函数同名同参数表的函数,不加virtual也自动成为虚函数

    多态的实现原理

    思考引入

    “多态”的关键在于通过基类指针或引用调用一个虚函数时,编译时不确定到底调用的是基类还是派生类的函数,运行时才确定——这叫“动态联编”,这是如何实现的?

    多态实现的关键——虚函数表

    每一个有虚函数的类(或有虚函数的类的派生类)都有一个虚函数表,该类的任何对象中都放着虚函数表的指针。虚函数表中列出了该类的虚函数地址。多出来的4个字节就是用来放虚函数表的地址的

    多态的函数调用语句被编译成一系列根据基类指针所指向的(或基类引用所引用的)对象中存放的虚函数表的地址,在虚函数表中查找虚函数地址,并调用虚函数的指令。

    image-20200521224426719

    多态的缺点

    • 额外的时间开销(多态的函数调用语句需要执行查表过程)
    • 额外的空间开销(每一个对象都会多4个字节存储虚函数表地址)

    虚析构函数

    问题引入

    class CSon{
      public:~CSon(){ };
    };
    class CGrandson:CSon{
      public:~CGrandson(){};
    }
    int main(){
      CSon *p = new CGrandson;//基类指针指向派生类
      delete p;//会引起一些问题:编译器该执行基类析构函数还是派生类析构函数?
      return 0;
    }
    

    虚析构函数

    • 通过基类的指针删除派生类对象时,只调用了基类的析构函数
    • 删除一个派生类的对象时,先调用派生类的析构函数,再调用基类的析构函数
    • 解决办法:
      • 把基类的析构函数声明为virtual
        • 派生类的析构函数virtual可以不进行声明
        • 通过基类的指针删除派生类对象时,首先调用派生类的析构函数,再调用基类的析构函数
    • 结论:类如果定义了虚函数,则最好将析构函数也定义成虚函数
    • 提醒:不允许把构造函数定义成虚函数

    纯虚函数和抽象类

    纯虚函数

    • 没有函数体的虚函数

    抽象类

    • 包含纯虚函数的类
      • 只能作为基类来派生新类使用
      • 不能创建抽象类的对象
      • 抽象类的指针和引用指向由抽象类派生出来的类的对象
    • 在抽象类中
      • 成员函数内可以调用纯虚函数
      • 构造函数/析构函数内部不能调用纯虚函数
    • 如果一个类由抽象类派生而来
      • 它只有实现基类中所有的纯虚函数,才能称为非抽象类

    练习题

    Quiz 1

    #include <iostream>
    using namespace std;
    class A {
    private:
        int nVal;
    public:
        void Fun()
        { cout << "A::Fun" << endl; }
        void Do()
        { cout << "A::Do" << endl; }
    };
    class B:public A {
    public:
        virtual void Do()
        { cout << "B::Do" << endl; }
    };
    class C:public B {
    public:
        void Do( )
        { cout << "C::Do" <<endl; }
        void Fun()
        { cout << "C::Fun" << endl; }
    };
    void Call(
    // 在此处补充你的代码
    B& p
    ) {
        p.Fun(); p.Do();
    }
    int main() {
        C c; Call(c);
        return 0;
    }
    

    Quiz2

    #include <iostream>
    using namespace std;
    class A {
    // 在此处补充你的代码
    public:
        virtual ~A(){cout << "destructor A" << endl;}
    };
    class B:public A {
    public:
        ~B() { cout << "destructor B" << endl; }
    };
    int main() {
        A * pa;
        pa = new B;
        delete pa;
        return 0;
    }
    

    Quiz 3

    #include <iostream>
    using namespace std;
    class A {
    private:
        int nVal;
    public:
        void Fun()
        { cout << "A::Fun" << endl; }
        virtual void Do()
        { cout << "A::Do" << endl; }
    };
    class B:public A {
    public:
        virtual void Do()
        { cout << "B::Do" << endl; }
    };
    class C:public B {
    public:
        void Do( )
        { cout << "C::Do" << endl; }
        void Fun()
        { cout << "C::Fun" << endl; }
    };
    void Call(
    // 在此处补充你的代码
    A* p
    ) {
        p->Fun(); p->Do();
    }
    int main() {
        Call( new A() );
        Call( new C() );
        return 0;
    }
    

    Quiz 4 魔兽世界终极版

    //这道题实在是太可怕了Orz我题都读不太明白……
    //所以就直接搜了一版,抄上去了……等以后技术好了再回过头来看看这道题是个什么情况吧Orz
    #include<iostream>
    #include<string>
    #include<vector>
    #include<cstdio>
    using namespace std;
    enum Knight_name{dragon, ninja, iceman, lion, wolf};//武士名称
    enum Weapon_name{sword, bomb, arrow};//武器名称
    string Knight[5] = {"dragon", "ninja", "iceman", "lion", "wolf"};//武士名称,输出使用
    Knight_name Order[2][5] = {{iceman, lion, wolf, ninja, dragon},//制造顺序
                               {lion, dragon, ninja, iceman, wolf}};
    string Color[2] = {"red", "blue"};//司令部颜色,输出使用
    string Weapons_[3] = {"sword", "bomb", "arrow"};//武器名称,输出使用
    int Attack_[5];//各武士初始攻击力
    int Loyal_reduce;//lion未杀死敌人所减少士气
    int Hour, Minute;//计时器
    int Total_Minutes;//终止时间
    int Life_Make[5];//制造各种武士所需生命元
    int arrow_attack;//arrow攻击力
    void Print_time(){//输出前面时间
        cout.width(3); cout.fill('0');
        cout << Hour << ':';cout.width(2);
        cout << Minute << ' ';
    }
    class City;
    class Command;
    class Weapon{//武器
    private:
        int name, sword_attack, arrow_usetime;//武器名称,sword攻击力,arrow剩余使用次数
    public:
        Weapon(int i, int satt):name(i), sword_attack(satt),arrow_usetime(3){}//武器状态初始化
        bool sword_dull(){//sword变钝
            sword_attack = int (sword_attack * 0.8);
            return sword_attack;
        }
        int &usetime(){return arrow_usetime;}
        int sw_atk(){return sword_attack;}
    };
    class Warrior{//士兵
    private:
        int Num, Life, Attack, Loyal, Step, l_life;//编号,生命力,攻击力,忠诚度,步数
        Knight_name name;//武士名称
        double Morale;//士气
        City* City_Belong_to;//所属城市
        Command* Command_Belong_to;//所属司令部
        bool If_win,If_kill;//战斗是否获胜,是否杀死敌人
        Weapon* weapon[3];//装备
    public:
        Warrior(int n, Knight_name &name_, int &life, int &t_life,Command *COMD){//初始化士兵属性
            Num = n; name = name_; Life = life; Attack = Attack_[name]; Step = 0; l_life = 0;
            weapon[0] = NULL; weapon[1] = NULL; weapon[2] = NULL;
            switch(name){
                case dragon:case iceman: weapon[Num % 3] = new Weapon(Num % 3, int(Attack_[name] * 0.2)); break;
                case ninja: weapon[Num % 3] = new Weapon(Num % 3, int(Attack_[name] * 0.2));
                    weapon[(Num + 1) % 3] = new Weapon((Num + 1) % 3, int(Attack_[name] * 0.2)); break;
                default: break;
            };
            if (weapon[sword]) if (!weapon[sword]->sw_atk()) weapon[sword] = NULL;//若初始武器攻击为0,则delete
            Morale = double(t_life) / double(Life);
            Loyal = t_life; If_win = false; If_kill = false;
            City_Belong_to = NULL; Command_Belong_to = COMD;
            cout << Knight[name] << ' ' << Num << " born
    ";
            if (name == dragon){
                cout << "Its morale is ";
                cout.precision(2);
                cout << fixed << Morale << endl;
            }
            if (name == lion){cout << "Its loyalty is " << Loyal << endl;}
        }
        bool &IF_win(){return If_win;}
        int life(){return Life;}
        bool Minute_5();//lion是否逃跑 输出
        void Minute_10(bool );//武士前进输出
        void Minute_30(int );//获取城市生命元及输出
        void arrow_shot();//使用弓箭输出
        void Be_shoted();//被射中处理及输出
        void Change_City(City * Cp){City_Belong_to = Cp;}
        void Morale_Change(){If_win ? Morale += 0.2: Morale -=0.2;}
        bool weapon_(Weapon_name name){return weapon[name];}
        void Use_bomb(Warrior *);//使用bomb输出
        int fight(Warrior* Wp){//假设战斗,判断是否会获胜
            if (Life > 0 and Wp->Life > 0){
                int swatk = 0;
                if (weapon[sword]) swatk = weapon[sword]->sw_atk();
                if (Wp->Life - Attack- swatk > 0){
                    if (Wp->name == ninja) return 0;
                    else{
                        int E_swatk = 0;
                        if (Wp->weapon[sword]) E_swatk = (Wp->weapon[sword])->sw_atk();
                        if (Life - (Wp->Attack / 2) - E_swatk > 0) return 0;
                        else return -1;
                    }
                }else return 1;
            }
            return 0;
        }
        bool bomb(Warrior *, int);//判断是否使用bomb
        void Fight(Warrior *);//武士战斗处理及输出
        void Dead();//武士死亡输出
        void account(Warrior * Wp){//部分战后处理
            If_win = true;
            if(If_kill) {Wp->Dead();If_kill = false;}
            if (Wp->name == lion) Life += Wp->l_life;
            if (name == wolf)
                for (int i = 0; i < 3; ++i)
                    if (Wp->weapon[i] and !weapon[i]){
                        weapon[i] = Wp->weapon[i];
                        Wp->weapon[i] = NULL;
                    }
            Morale_Change();
        }
        void Reward();//战胜后获取奖励
        void ADD(int);//所属司令部增加生命元
        void Loyal_Reduce(){Loyal -= Loyal_reduce;}
        void Report_weapon();//报告武器使用情况
        ~Warrior(){
            for (int i = 0; i < 3; ++i)
                if (weapon[i]) delete weapon[i];
        }
    };
    class City{
    private:
        int Number, Life, Flag, Flag_G[2];//城市编号,生命元,旗帜,各方士兵连续胜利场次
        Warrior *Warrior_In_City[2];
    public:
        int Num(){return Number;}
        int Life_(){return Life;}
        City(int N){
            Number = N; Life = 0; Flag = -1;//-1 表示无旗城市
            Warrior_In_City[0] = NULL; Flag_G[0] = 0;
            Warrior_In_City[1] = NULL; Flag_G[1] = 0;
        }
        void Minute_5(){//处理逃跑lion
            for(int i = 0; i < 2; ++i)
                if(Warrior_In_City[i]) if (Warrior_In_City[i]->Minute_5()){
                        delete Warrior_In_City[i]; Warrior_In_City[i] = NULL;
                    }
        }
        void Move(City* Cp, int i){//warrior前进
            Warrior_In_City[i] = Cp->Warrior_In_City[i];
            if(Warrior_In_City[i]) Warrior_In_City[i]->Change_City(this);
        }
        void Move(Command *, int);//warrior进入敌方司令部
        void Move(Warrior *Wp, int i){//warrior从command进入city
            Warrior_In_City[i] = Wp;
            if (Warrior_In_City[i]) Warrior_In_City[i]->Change_City(this);
        }
        bool If_exist(int i){return Warrior_In_City[i];}
        void Minute_10(){//warrior前进输出
            if (Warrior_In_City[0]) Warrior_In_City[0]->Minute_10(false);
            if (Warrior_In_City[1]) Warrior_In_City[1]->Minute_10(false);
        }
        void Add_Life(){Life += 10;}
        void Minute_30(){//城内单独warrior获取生命元
            for (int i = 0; i < 2; ++i)
                if ((Warrior_In_City[i]) and (!Warrior_In_City[1-i])){
                    Warrior_In_City[i]->Minute_30(Life);
                    Life = 0; break;
                }
        }
        void Minute_35(City* Cp[]){//处理arrow事件
            for (int j = 0; j < 2; ++j)
                if (Warrior_In_City[j]) if (Warrior_In_City[j]->weapon_(arrow))
                        if (Cp[1-j]) if ((Cp[1-j]->Warrior_In_City[1-j])){
                                Warrior_In_City[j]->arrow_shot();
                                Cp[1-j]->Warrior_In_City[1-j]->Be_shoted();
                            }
        }
        void Minute_38(){//处理bomb事件,顺带处理35分钟时城市中两只warrior均被被射死的情况
            if (Warrior_In_City[0] and Warrior_In_City[1]){
                bool p =false;
                for (int i = 0; i < 2; ++i)
                    if (Warrior_In_City[i]->weapon_(bomb)){
                        if (Flag == -1) p = Warrior_In_City[i]->bomb(Warrior_In_City[1-i], Number);
                        else p = Warrior_In_City[i]->bomb(Warrior_In_City[1-i], Flag+1);
                        if (p){
                            delete Warrior_In_City[0]; Warrior_In_City[0] = NULL;
                            delete Warrior_In_City[1]; Warrior_In_City[1] = NULL;
                            break;
                        }
                    }
                if (!p and Warrior_In_City[0]->life() <= 0 and Warrior_In_City[1]->life() <= 0){
                    delete Warrior_In_City[0]; Warrior_In_City[0] = NULL;
                    delete Warrior_In_City[1]; Warrior_In_City[1] = NULL;
                }
            }
        }
        void Battle(){//战斗及输出,不进行生命元奖励、获取处理
            if (Warrior_In_City[0] and Warrior_In_City[1]){
                if (Flag == -1){
                    if (Number % 2) Warrior_In_City[0]->Fight(Warrior_In_City[1]);
                    else Warrior_In_City[1]->Fight(Warrior_In_City[0]);
                }else
                    Warrior_In_City[Flag]->Fight(Warrior_In_City[1-Flag]);
            }
        }
        void Flag_Set(int i){//战斗后旗帜设置
            if (i == -1){Flag_G[0] = 0; Flag_G[1] = 0;}
            else{
                ++Flag_G[i]; Flag_G[1-i] = 0;
                if (Flag_G[i] == 2 and Flag != i){
                    Flag = i;
                    Print_time();
                    cout << Color[i] << " flag raised in city " << Number << endl;}
            }
        }
        void Reward(int i){if(Warrior_In_City[i]) Warrior_In_City[i]->Reward();}
        void Warrior_report(int i){if(Warrior_In_City[i]) Warrior_In_City[i]->Report_weapon();}
        void Win_get(){//奖励获胜士兵生命元
            for (int i = 0; i < 2; ++i)
                if (Warrior_In_City[i]){
                    if (Warrior_In_City[i]->IF_win()){
                        Warrior_In_City[i]->ADD(Life);
                        Life = 0; Warrior_In_City[i]->IF_win() = false;
                    }else if (Warrior_In_City[i]->life() <=0){
                        delete Warrior_In_City[i];
                        Warrior_In_City[i] = NULL;
                    }
                }
        }
    };
    class Command{
    private:
        int Total_Life, Knights_Num, Colour, Enemy_Enter;//生命元,造士兵数量,command颜色,有多少敌人进入
        bool Weather_Enter;//是否有敌人进入
        Warrior* Enemys[2];//进入的敌人
        Warrior* Knight;//warrior
    public:
        int colour(){return Colour;}
        string colour(bool p){return p? Color[Colour]: Color[1-Colour];}
        Command(int TLife, int col){
            Total_Life = TLife;Colour = col;
            Knights_Num = 0;
            Knight = NULL; Enemy_Enter = 0;
            Weather_Enter = false;
            Enemys[0] = NULL; Enemys[1] = NULL;
        }
        void Minute_0(){//制造warrior及输出
            if (Total_Life >= Life_Make[Order[Colour][Knights_Num % 5]]){
                Total_Life -= Life_Make[Order[Colour][Knights_Num % 5]];
                Print_time();
                cout << Color[Colour] << ' ';
                Knight = new Warrior(Knights_Num+1, Order[Colour][Knights_Num % 5], Life_Make[Order[Colour][Knights_Num% 5]], Total_Life, this);
                Knights_Num++;
            }
        }
        void Minute_5(){//处理逃跑lion
            if (Knight) if (Knight->Minute_5()){delete Knight; Knight = NULL;}
        }
        void Move(City* Cp, int i){Cp->Move(Knight, i); Knight = NULL;}//warrior走出command
        void Enemy_Move_In(Warrior* enemy){//敌方warrior进入
            Enemys[Enemy_Enter] = enemy;
            Weather_Enter = true;
            ++Enemy_Enter;
        }
        void Minute_10(){//敌方warrior进入输出
            if (Weather_Enter){
                Enemys[Enemy_Enter-1]->Minute_10(true);
                Weather_Enter = false;
            }
        }
        bool If_occupied(){//command是否被占领
            if (Enemy_Enter == 2){
                Print_time();
                cout << Color[Colour] << " headquarter was taken
    ";
                return true;
            }
            return false;
        }
        void Minute_30(int Add_life){Total_Life += Add_life;}
        int &Life(){return Total_Life;}
        void Report_life(){//command报告生命元
            Print_time();
            cout << Total_Life << " elements in " << Color[Colour] << " headquarter
    ";
        }
        void Report(){if (Enemy_Enter) Enemys[Enemy_Enter-1]->Report_weapon();}//已进入command的warrior仍要report
        ~Command(){
            if (Knight) delete Knight;
            if (Enemys[0]) delete Enemys[0];
            if (Enemys[1]) delete Enemys[1];
        }
    };
    void Game_Start(){
        int times = 0;
        cin >> times;
        for (int t = 0; t < times; ++t){
            int M, N;//初始command生命元,城市数量
            cin >> M >> N >> arrow_attack >> Loyal_reduce >> Total_Minutes;
            Command COM[2] = {Command(M,0),Command(M,1)};
            vector<City> Citys;
            for (int i = 0; i < N; ++i){
                City temp(i + 1);
                Citys.push_back(temp);
            }
            for (int i = 0; i < 5; ++i)
                cin >> Life_Make[i];
            for (int i = 0; i < 5; ++i)
                cin >> Attack_[i];
            cout << "Case " << t + 1 << ":
    ";
            Hour = 0; Minute = 0;//计时开始
            while(Hour * 60 <= Total_Minutes){
                COM[0].Minute_0(); COM[1].Minute_0(); Minute = 5;//第0分钟
                if (Hour * 60 + Minute > Total_Minutes) break;//第5分钟
                else {
                    COM[0].Minute_5();
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)
                        (*i).Minute_5();
                    COM[1].Minute_5();
                    Minute = 10;
                }
                if (Hour * 60 + Minute > Total_Minutes) break;//第10分钟
                else {
                    if (Citys[0].If_exist(1)) Citys[0].Move(&COM[0], 1);//warrior前进
                    for (int i = 0; i < N - 1; ++i)
                        Citys[i].Move(&Citys[i+1], 1);
                    COM[1].Move(&Citys[N - 1], 1);
                    if (Citys[N-1].If_exist(0)) Citys[N-1].Move(&COM[1], 0);
                    for (int i = N - 1; i > 0; --i)
                        Citys[i].Move(&Citys[i-1], 0);
                    COM[0].Move(&Citys[0], 0);
                    COM[0].Minute_10();//warrior移动输出
                    bool p = COM[0].If_occupied();
                    for (int i = 0; i < N; ++i) Citys[i].Minute_10();
                    COM[1].Minute_10();
                    if (p + COM[1].If_occupied()) break;
                }
                Minute = 20;
                if (Hour * 60 + Minute > Total_Minutes) break;//第20分钟
                else
                    for (int i = 0; i < N; ++i) Citys[i].Add_Life();
                Minute = 30;
    
                if (Hour * 60 + Minute > Total_Minutes) break;//第30分钟
                else
                    for (int i = 0; i < N; ++i) Citys[i].Minute_30();
                Minute = 35;
                if (Hour * 60 + Minute > Total_Minutes) break;//第35分钟
                else
                if (N > 1){//city数大于1时才会发生arrow事件
                    City* Cp[2] = {};
                    Cp[0] = NULL; Cp[1] = &Citys[1];
                    Citys[0].Minute_35(Cp);
                    for (int i = 1; i < N-1; ++i){
                        Cp[0] = &Citys[i-1]; Cp[1] = &Citys[i+1];
                        Citys[i].Minute_35(Cp);
                    }
                    Cp[0] = &Citys[N-2]; Cp[1] = NULL;
                    Citys[N-1].Minute_35(Cp);
                }
                Minute = 38;
                if (Hour * 60 + Minute > Total_Minutes) break;//第38分钟
                else
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)
                        (*i).Minute_38();
                Minute = 40;
                if (Hour * 60 + Minute > Total_Minutes) break;//第40分钟
                else{
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)//战斗及输出
                        (*i).Battle();
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)//奖励生命元
                        (*i).Reward(0);
                    for (vector<City>::reverse_iterator i = Citys.rbegin(); i != Citys.rend(); ++i)
                        (*i).Reward(1);
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)//获取city生命元
                        (*i).Win_get();
                }
                Minute = 50;
                if (Hour * 60 + Minute > Total_Minutes) break;//第50分钟
                else
                    COM[0].Report_life();COM[1].Report_life();
                Minute = 55;
                if (Hour * 60 + Minute > Total_Minutes) break;//第55分钟
                else{
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)
                        (*i).Warrior_report(0);
                    COM[1].Report();COM[0].Report();
                    for (vector<City>::iterator i = Citys.begin(); i != Citys.end(); ++i)
                        (*i).Warrior_report(1);
                }
                Minute = 0;
                Hour++;
            }
        }
    }
    int main(){
    // freopen("d:\anser.txt", "w", stdout);
        Game_Start();
    // fclose(stdout);
        return 0;
    }
    bool Warrior::Minute_5(){
        if (name == lion) if (Loyal <= 0){
                Print_time();
                cout << Command_Belong_to->colour(true) << " lion " << Num << " ran away
    ";
                return true;
            }
        return false;
    }
    void Warrior::Minute_10(bool If_arrive){
        ++Step;
        if (name == iceman and !(Step % 2)){
            if (Life < 10) Life = 1;
            else Life -= 9;
            Attack += 20;
        }
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num;
        if (If_arrive)
            cout << " reached " << Command_Belong_to->colour(false) << " headquarter";
        else cout << " marched to city " << City_Belong_to->Num();
        cout << " with " << Life << " elements and force " << Attack << endl;
    }
    void Warrior::Minute_30(int Add_life){
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " earned " << Add_life << " elements for his headquarter
    ";
        Command_Belong_to->Minute_30(Add_life);
    }
    void Warrior::arrow_shot(){
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " shot";
        weapon[arrow]->usetime()--;
        if(!weapon[arrow]->usetime()){delete weapon[arrow]; weapon[arrow] = NULL;}
    }
    void Warrior::Be_shoted(){
        Life -= arrow_attack;
        if (Life <= 0){cout << " and killed " << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num;}
        cout << endl;
    }
    void City::Move(Command *Cp, int i){
        Cp->Enemy_Move_In(Warrior_In_City[i]);
        Warrior_In_City[i] = NULL;
    }
    void Warrior::Use_bomb(Warrior *Wp){
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " used a bomb and killed " << (Wp->Command_Belong_to)->colour(true) << ' ' << Knight[Wp->name] << ' ' << Wp->Num << endl;
    }
    bool Warrior::bomb(Warrior *Wp, int p){
        if ((p + Command_Belong_to->colour()) % 2){
            if (fight(Wp) == -1) {Use_bomb(Wp); return true;}
        }else
        if (Wp->fight(this) == 1) {Use_bomb(Wp); return true;}
        return false;
    }
    void Warrior::Dead(){
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " was killed in city " << City_Belong_to->Num() << endl;
    }
    void Warrior::Fight(Warrior *Wp){
        Warrior *Wp_win = NULL; Warrior *Wp_lose = NULL;
        l_life = Life; Wp->l_life = Wp->Life;
        if (Life > 0 and (Wp->Life) > 0){
            int swatk = 0;
            if (weapon[sword]) swatk = weapon[sword]->sw_atk();
            Print_time();
            cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " attacked " << (Wp->Command_Belong_to)->colour(true) << ' ' << Knight[Wp->name] << ' ' << Wp->Num << " in city " << City_Belong_to->Num() << " with " << Life << " elements and force " << Attack << endl;
            Wp->Life = Wp->Life - Attack - swatk;
            if (swatk) if (!weapon[sword]->sword_dull()){delete weapon[sword]; weapon[sword] = NULL;}
            if (Wp->Life > 0){
                if (Wp->name == ninja) {City_Belong_to->Flag_Set(-1);Morale_Change();Loyal_Reduce();}
                else{
                    int E_swatk = 0;
                    if (Wp->weapon[sword]) E_swatk = (Wp->weapon[sword])->sw_atk();
                    Print_time();
                    cout << (Wp->Command_Belong_to)->colour(true) << ' ' << Knight[Wp->name] << ' ' << Wp->Num << " fought back against " << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " in city " << City_Belong_to->Num() <<endl;
                    Life = Life - (Wp->Attack / 2) - E_swatk;
                    if (E_swatk) if(!(Wp->weapon[sword])->sword_dull()){delete Wp->weapon[sword]; Wp->weapon[sword] = NULL;}
                    if (Life > 0) {City_Belong_to->Flag_Set(-1);Morale_Change();Wp->Morale_Change();Loyal_Reduce();Wp->Loyal_Reduce();}
                    else{Wp->If_kill = true;Wp_lose = this;Wp_win = Wp;}
                }
            }else{If_kill = true;Wp_win = this;Wp_lose = Wp;}
        }else{
            if (Life > 0){Wp->l_life = 0;Wp_win = this;Wp_lose = Wp;}
            else {l_life = 0;Wp_lose = this;Wp_win = Wp;}
        }
        if (Wp_win){Wp_win->account(Wp_lose);}
        if (name == dragon and Life > 0 and Morale > 0.8){
            Print_time();
            cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " yelled in city " << City_Belong_to->Num() << endl;
        }
        if (Wp_win){
            Print_time();
            cout << (Wp_win->Command_Belong_to)->colour(true) << ' ' << Knight[Wp_win->name] << ' ' << Wp_win->Num << " earned " << City_Belong_to->Life_() << " elements for his headquarter
    ";
            (Wp_win->City_Belong_to)->Flag_Set((Wp_win->Command_Belong_to)->colour());
        }
    }
    void Warrior::Reward(){
        if (If_win)
            if (Command_Belong_to->Life() > 7){
                Command_Belong_to->Life() -= 8;
                Life += 8;
            }
    }
    void Warrior::ADD(int life){Command_Belong_to->Life() += life;}
    void Warrior::Report_weapon(){
        bool p = false;
        Print_time();
        cout << Command_Belong_to->colour(true) << ' ' << Knight[name] << ' ' << Num << " has ";
        for (int i = 2; i >= 0; --i)
            if (weapon[i]){
                if (p) cout << ',';else p = true;
                cout << Weapons_[i];
                if (i == 2) cout << '(' << weapon[arrow]->usetime() << ')';
                if (i == 0) cout << '(' << weapon[sword]->sw_atk() << ')';
            }
        if(!p) cout << "no weapon";
        cout << endl;
    }
    
  • 相关阅读:
    TreeView 读取 xml 显示节点
    网上流传的数据操作类
    文件上传, 打开, 删除操作
    Reflector8.5 .net反编译工具 破解教程
    asp.net c# 打开新页面或页面跳转
    UGUI 要点总结
    EventSystem
    拖拽事件
    Unity Transform
    鼠标跟随(坐标转换)
  • 原文地址:https://www.cnblogs.com/maimai-d/p/12945348.html
Copyright © 2020-2023  润新知