Coursera課程筆記----C++程序設計----Week6

多態與虛函數(week 6)

多態與虛函數的基本概念

虛函數

  • 在類的定義中,前面有virtual關鍵字的成員函數就是虛函數ios

    class base{
      virtual int get();
    };
    int base::get(){}
  • virtual關鍵字只用在類定義裏的函數聲明中,寫函數體時不用數組

  • 構造函數和靜態成員函數不能是虛函數函數

多態的表現形式(一)

  • 派生類的指針能夠賦值給基類指針ui

  • 經過基類指針調用基類和派生類中的同名虛函數時:this

    1. 若該指針指向一個基類的對象,那麼被調用的是基類的虛函數
    2. 若該指針指向一個派生類的對象,那麼被調用的是派生類的虛函數

    這個機制就叫作「多態spa

多態的表現形式(二)

  • 派生類的對象能夠賦給基類引用設計

  • 經過基類引用調用基類和派生類中的同名虛函數時:指針

    1. 若該引用引用的是一個基類的對象,那麼被調用的是基類的虛函數
    2. 若該引用引用的是一個派生類的對象,那麼被調用的是派生類的虛函數

    這個機制就叫作「多態」code

多態的做用

在面向對象的程序設計中使用多態,可以加強程序的可擴充性,即程序須要修改或增長功能的時候,須要改動和增長的代碼較少。對象

使用多態的遊戲程序實例

基本思路

  • 爲每一個怪物類編寫 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\n";
        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\n";
            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\n";
    }
    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 << ":\n";
        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\n";
            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\n";
    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\n";
        (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;
}
相關文章
相關標籤/搜索