实验五 模板类与多态

《实验任务2》

“Person.hpp”

#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;

class Person
{
    private:
        string name;
        string telephone;
        string email;
    public:
        Person(){}
        Person(string na, string te, string em):name(na), telephone(te), email(em){}
        void change_phone(string new_phone){telephone = new_phone;}
        void change_email(string new_email){email = new_email;}
        friend ostream& operator<<(ostream& out, Person& p);
        friend istream& operator>>(istream& in, Person& P);
        friend bool operator==(Person P1, Person P2);
};

ostream& operator<<(ostream& out, Person& P)
{
    out <<setiosflags(ios_base::left) << setw(20) << P.name << setw(20) << P.telephone << setw(20) << P.email;
    return out;
}
istream& operator>>(istream& in, Person& P)
{
    // in >> P.name >> P.telephone >> P.email;
    string temp;
    in >> P.name;
    in >> temp;
    P.name = P.name +" "+temp;
    in >> P.telephone >> P.email;
    return in;
}
bool operator==(Person P1, Person P2)
{
    if(P1.name==P2.name&&P1.telephone==P2.telephone)
        return true;
    return false;
}

“task2.cpp”

#include <iostream>
#include <fstream>
#include <vector>
#include "Person.hpp"

int main()
{
    using namespace std;

    vector<Person> phone_book;
    Person p;

    while(cin>>p)
        phone_book.push_back(p);
    
    for(auto &i: phone_book)
        cout << i << endl;
    
    cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl;

    ofstream fout;

    fout.open("phone_book.txt");

    if(!fout.is_open())
    {
        cerr << "fail to open file phone_book.txt\n";
        return 1;
    }

    for(auto &i: phone_book)
        fout << i << endl;
    
    fout.close();
}

“运行结果”

实验五 模板类与多态

 

实验五 模板类与多态

① cout << i

将会转化成 osteam &operator<<(ostream &cout, const Person &i)

其具体的调用形式为

ostream &operator<<(ostream &cout , const Person &i)

{

  cout <<setiosflags(ios_base::left) << setw(20) << P.name

                << setw(20) << P.telephone

                << setw(20) << P.email;

  return cout;

}

②fout << i 

将会转化成 osteam &operator<<(ostream &fout, const Person &i)

其具体的调用形式为

ostream &operator<<(ostream &fout , const Person &i)

{

  fout <<setiosflags(ios_base::left) << setw(20) << P.name

                << setw(20) << P.telephone

                << setw(20) << P.email;

  return fout;

}

 

《实验任务3》

实验五 模板类与多态
//=======================
//        container.h
//=======================

// The so-called inventory of a player in RPG games
// contains two items, heal and magic water

#ifndef _CONTAINER        // Conditional compilation
#define _CONTAINER

class container        // Inventory
{
protected:
    int numOfHeal;            // number of heal
    int numOfMW;            // number of magic water
public:
    container();            // constuctor
    void set(int heal_n, int mw_n);    // set the items numbers
    int nOfHeal();            // get the number of heal
    int nOfMW();            // get the number of magic water
    void display();            // display the items;
    bool useHeal();            // use heal
    bool useMW();            // use magic water
};

#endif
container.h 实验五 模板类与多态
//=======================
//        container.cpp
//=======================

// default constructor initialise the inventory as empty
#include <iostream>
#include "container.h"
using namespace std;

container::container()
{
    set(0,0);
}

// set the item numbers
void container::set(int heal_n, int mw_n)
{
    numOfHeal=heal_n;
    numOfMW=mw_n;
}

// get the number of heal
int container::nOfHeal()
{
    return numOfHeal;
}

// get the number of magic water
int container::nOfMW()
{
    return numOfMW;
}

// display the items;
void container::display()
{
    cout<<"Your bag contains: "<<endl;
    cout<<"Heal(HP+100): "<<numOfHeal<<endl;
    cout<<"Magic Water (MP+80): "<<numOfMW<<endl;
}

//use heal
bool container::useHeal()
{
    numOfMW++;
    return 1;        // use heal successfully
}

//use magic water
bool container::useMW()
{
    numOfMW--;
    return 1;        // use magic water successfully
}
container.cpp 实验五 模板类与多态
//=======================
//        player.h
//=======================

// The base class of player
// including the general properties and methods related to a character

#ifndef _PLAYER
#define _PLAYER

#include <iomanip>        // use for setting field width
#include <time.h>        // use for generating random factor
#include "container.h"
using namespace std;

enum job {sw, ar, mg};    /* define 3 jobs by enumerate type
                               sword man, archer, mage */
class player
{
    friend void showinfo(player &p1, player &p2);
    friend class swordsman;

protected:
    int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV;
    // General properties of all characters
    string name;    // character name
    job role;        /* character's job, one of swordman, archer and mage,
                       as defined by the enumerate type */
    container bag;    // character's inventory

public:
    virtual bool attack(player &p)=0;    // normal attack
    virtual bool specialatt(player &p)=0;    //special attack
    virtual void isLevelUp()=0;            // level up judgement
    /* Attention!
    These three methods are called "Pure virtual functions".
    They have only declaration, but no definition.
    The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 
    The detailed definition of these pure virtual functions will be given in subclasses. */

    void reFill();        // character's HP and MP resume
    bool death();        // report whether character is dead
    void isDead();        // check whether character is dead
    bool useHeal();        // consume heal, irrelevant to job
    bool useMW();        // consume magic water, irrelevant to job
    void transfer(player &p);    // possess opponent's items after victory
    void showRole();    // display character's job
    
private:
    bool playerdeath;            // whether character is dead, doesn't need to be accessed or inherited
};

#endif
player.h 实验五 模板类与多态
//=======================
//        player.cpp
//=======================
#include <iostream>
#include "player.h"

// character's HP and MP resume
void player::reFill()
{
    HP=HPmax;        // HP and MP fully recovered
    MP=MPmax;
}

// report whether character is dead
bool player::death()
{
    return playerdeath;
}

// check whether character is dead
void player::isDead()
{
    if(HP<=0)        // HP less than 0, character is dead
    {
        std::cout<<name<<" is Dead." <<endl;
        system("pause");
        playerdeath=1;    // give the label of death value 1
    }
}

// consume heal, irrelevant to job
bool player::useHeal()
{
    if(bag.nOfHeal()>0)
    {
        HP=HP+100;
        if(HP>HPmax)        // HP cannot be larger than maximum value
            HP=HPmax;        // so assign it to HPmax, if necessary
        std::cout<<name<<" used Heal, HP increased by 100."<<endl;
        bag.useHeal();        // use heal
        system("pause");
        return 1;    // usage of heal succeed
    }
    else                // If no more heal in bag, cannot use
    {
        std::cout<<"Sorry, you don't have heal to use."<<endl;
        system("pause");
        return 0;    // usage of heal failed
    }
}

// consume magic water, irrelevant to job
bool player::useMW()
{
    if(bag.nOfMW()>0)
    {
        MP=MP+100;
        if(MP>MPmax)
            MP=MPmax;
        std::cout<<name<<" used Magic Water, MP increased by 100."<<endl;
        bag.useMW();
        system("pause");
        return 1;    // usage of magic water succeed
    }
    else
    {
        std::cout<<"Sorry, you don't have magic water to use."<<endl;
        system("pause");
        return 0;    // usage of magic water failed
    }
}

// possess opponent's items after victory
void player::transfer(player &p)
{
    std::cout<<name<<" got"<<p.bag.nOfHeal()<<" Heal, and "<<p.bag.nOfMW()<<" Magic Water."<<endl;
    system("pause");
    bag.set(p.bag.nOfHeal()+bag.nOfHeal(),p.bag.nOfMW()+bag.nOfMW());
    // set the character's bag, get opponent's items
}

// display character's job
void player::showRole()
{
    switch(role)
    {
    case sw:
        std::cout<<"Swordsman";
        break;
    case ar:
        std::cout<<"Archer";
        break;
    case mg:
        std::cout<<"Mage";
        break;
    default:
        break;
    }
}


// display character's job
void showinfo(player &p1, player &p2)
{
    system("cls");
    std::cout<<"##############################################################"<<endl;
    cout<<"# Player"<<setw(10)<<p1.name<<"   LV. "<<setw(3) <<p1.LV
        <<"  # Opponent"<<setw(10)<<p2.name<<"   LV. "<<setw(3) <<p2.LV<<" #"<<endl;
    cout<<"# HP "<<setw(3)<<(p1.HP<=999?p1.HP:999)<<'/'<<setw(3)<<(p1.HPmax<=999?p1.HPmax:999)
        <<" | MP "<<setw(3)<<(p1.MP<=999?p1.MP:999)<<'/'<<setw(3)<<(p1.MPmax<=999?p1.MPmax:999)
        <<"     # HP "<<setw(3)<<(p2.HP<=999?p2.HP:999)<<'/'<<setw(3)<<(p2.HPmax<=999?p2.HPmax:999)
        <<" | MP "<<setw(3)<<(p2.MP<=999?p2.MP:999)<<'/'<<setw(3)<<(p2.MPmax<=999?p2.MPmax:999)<<"      #"<<endl;
    cout<<"# AP "<<setw(3)<<(p1.AP<=999?p1.AP:999)
        <<" | DP "<<setw(3)<<(p1.DP<=999?p1.DP:999)
        <<" | speed "<<setw(3)<<(p1.speed<=999?p1.speed:999)
        <<" # AP "<<setw(3)<<(p2.AP<=999?p2.AP:999)
        <<" | DP "<<setw(3)<<(p2.DP<=999?p2.DP:999)
        <<" | speed "<<setw(3)<<(p2.speed<=999?p2.speed:999)<<"  #"<<endl;
    cout<<"# EXP"<<setw(7)<<p1.EXP<<" Job: "<<setw(7);
    p1.showRole();
    cout<<"   # EXP"<<setw(7)<<p2.EXP<<" Job: "<<setw(7);
    p2.showRole();
    cout<<"    #"<<endl;
    cout<<"--------------------------------------------------------------"<<endl;
    p1.bag.display();
    cout<<"##############################################################"<<endl;
}
player.cpp 实验五 模板类与多态
 1 //=======================
 2 //        swordsman.h
 3 //=======================
 4 
 5 // Derived from base class player
 6 // For the job Swordsman
 7 #include <iostream>
 8 #include "player.h"
 9 
10 class swordsman : public player    // subclass swordsman publicly inherited from base player
11 {
12 public:
13     swordsman(int lv_in=1, string name_in="Not Given");    
14         // constructor with default level of 1 and name of "Not given"
15     void isLevelUp();
16     bool attack (player &p);
17     bool specialatt(player &p);
18         /* These three are derived from the pure virtual functions of base class
19            The definition of them will be given in this subclass. */
20     void AI(player &p);                // Computer opponent
21 };
swordsman.h 实验五 模板类与多态
  1 //=======================
  2 //        swordsman.cpp
  3 //=======================
  4 
  5 // constructor. default values don't need to be repeated here
  6 
  7 #include <iostream>
  8 #include <stdlib.h>
  9 #include "swordsman.h"
 10 
 11 swordsman::swordsman(int lv_in, string name_in)
 12 {
 13     role=sw;    // enumerate type of job
 14     LV=lv_in;
 15     name=name_in;
 16     
 17     // Initialising the character's properties, based on his level
 18     HPmax=150+8*(LV-1);        // HP increases 8 point2 per level
 19     HP=HPmax;
 20     MPmax=75+2*(LV-1);        // MP increases 2 points per level
 21     MP=MPmax;
 22     AP=25+4*(LV-1);            // AP increases 4 points per level
 23     DP=25+4*(LV-1);            // DP increases 4 points per level
 24     speed=25+2*(LV-1);        // speed increases 2 points per level
 25     
 26     playerdeath=0;
 27     EXP=LV*LV*75;
 28     bag.set(lv_in, lv_in);
 29 }
 30 
 31 void swordsman::isLevelUp()
 32 {
 33     if(EXP>=LV*LV*75)
 34     {
 35         LV++;
 36         AP+=4;
 37         DP+=4;
 38         HPmax+=8;
 39         MPmax+=2;
 40         speed+=2;
 41         cout<<name<<" Level UP!"<<endl;
 42         cout<<"HP improved 8 points to "<<HPmax<<endl;
 43         cout<<"MP improved 2 points to "<<MPmax<<endl;
 44         cout<<"Speed improved 2 points to "<<speed<<endl;
 45         cout<<"AP improved 4 points to "<<AP<<endl;
 46         cout<<"DP improved 5 points to "<<DP<<endl;
 47         system("pause");
 48         isLevelUp();    // recursively call this function, so the character can level up multiple times if got enough exp
 49     }
 50 }
 51 
 52 bool swordsman::attack(player &p)
 53 {
 54     double HPtemp=0;        // opponent's HP decrement
 55     double EXPtemp=0;        // player obtained exp
 56     double hit=1;            // attach factor, probably give critical attack
 57     srand((unsigned)time(NULL));        // generating random seed based on system time
 58 
 59     // If speed greater than opponent, you have some possibility to do double attack
 60     if ((speed>p.speed) && (rand()%100<(speed-p.speed)))        // rand()%100 means generates a number no greater than 100
 61     {
 62         HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10));        // opponent's HP decrement calculated based their AP/DP, and uncertain chance
 63         cout<<name<<"'s quick strike hit "<<p.name<<", "<<p.name<<"'s HP decreased "<<HPtemp<<endl;
 64         p.HP=int(p.HP-HPtemp);
 65         EXPtemp=(int)(HPtemp*1.2);
 66     }
 67 
 68     // If speed smaller than opponent, the opponent has possibility to evade
 69     if ((speed<p.speed) && (rand()%50<1))
 70     {
 71         cout<<name<<"'s attack has been evaded by "<<p.name<<endl;
 72         system("pause");
 73         return 1;
 74     }
 75 
 76     // 10% chance give critical attack
 77     if (rand()%100<=10)
 78     {
 79         hit=1.5;
 80         cout<<"Critical attack: ";
 81     }
 82 
 83     // Normal attack
 84     HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10));
 85     cout<<name<<" uses bash, "<<p.name<<"'s HP decreases "<<HPtemp<<endl;
 86     EXPtemp=(int)(EXPtemp+HPtemp*1.2);
 87     p.HP=(int)(p.HP-HPtemp);
 88     cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl;
 89     EXP=(int)(EXP+EXPtemp);
 90     system("pause");
 91     return 1;        // Attack success
 92 }
 93 
 94 bool swordsman::specialatt(player &p)
 95 {
 96     if(MP<40)
 97     {
 98         cout<<"You don't have enough magic points!"<<endl;
 99         system("pause");
100         return 0;        // Attack failed
101     }
102     else
103     {
104         MP-=40;            // consume 40 MP to do special attack
105         
106         //10% chance opponent evades
107         if(rand()%100<=10)
108         {
109             cout<<name<<"'s leap attack has been evaded by "<<p.name<<endl;
110             system("pause");
111             return 1;
112         }
113         
114         double HPtemp=0;        
115         double EXPtemp=0;        
116         //double hit=1;            
117         //srand(time(NULL));        
118         HPtemp=(int)(AP*1.2+20);        // not related to opponent's DP
119         EXPtemp=(int)(HPtemp*1.5);        // special attack provides more experience
120         cout<<name<<" uses leap attack, "<<p.name<<"'s HP decreases "<<HPtemp<<endl;
121         cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl;
122         p.HP=(int)(p.HP-HPtemp);
123         EXP=(int)(EXP+EXPtemp);
124         system("pause");
125     }
126     return 1;    // special attack succeed
127 }
128 
129 // Computer opponent
130 void swordsman::AI(player &p)
131 {
132     if ((HP<(int)((1.0*p.AP/DP)*p.AP*1.5))&&(HP+100<=1.1*HPmax)&&(bag.nOfHeal()>0)&&(HP>(int)((1.0*p.AP/DP)*p.AP*0.5)))
133         // AI's HP cannot sustain 3 rounds && not too lavish && still has heal && won't be killed in next round
134     {
135         useHeal();
136     }
137     else
138     {
139         if(MP>=40 && HP>0.5*HPmax && rand()%100<=30)
140             // AI has enough MP, it has 30% to make special attack
141         {
142             specialatt(p);
143             p.isDead();        // check whether player is dead
144         }
145         else
146         {
147             if (MP<40 && HP>0.5*HPmax && bag.nOfMW())
148                 // Not enough MP && HP is safe && still has magic water
149             {
150                 useMW();
151             }
152             else
153             {
154                 attack(p);    // normal attack
155                 p.isDead();
156             }
157         }
158     }
159 }
swordsman.cpp 实验五 模板类与多态
  1 //=======================
  2 //        main.cpp
  3 //=======================
  4 
  5 // main function for the RPG style game
  6 
  7 #include <iostream>
  8 #include <string>
  9 #include "swordsman.h"
 10 using namespace std;
 11 
 12 
 13 
 14 
 15 int main()
 16 {
 17     string tempName;
 18     bool success=0;        //flag for storing whether operation is successful
 19     cout <<"Please input player's name: ";
 20     cin >>tempName;        // get player's name from keyboard input
 21     player *human;        // use pointer of base class, convenience for polymorphism
 22     int tempJob;        // temp choice for job selection
 23     do
 24     {
 25         cout <<"Please choose a job: 1 Swordsman, 2 Archer, 3 Mage"<<endl;
 26         cin>>tempJob;
 27         system("cls");        // clear the screen
 28         switch(tempJob)
 29         {
 30         case 1:
 31             human=new swordsman(1,tempName);    // create the character with user inputted name and job
 32             success=1;        // operation succeed
 33             break;
 34         default:
 35             break;                // In this case, success=0, character creation failed
 36         }
 37     }while(success!=1);        // so the loop will ask user to re-create a character
 38 
 39     int tempCom;            // temp command inputted by user
 40     int nOpp=0;                // the Nth opponent
 41     for(int i=1;nOpp<5;i+=2)    // i is opponent's level
 42     {
 43         nOpp++;
 44         system("cls");
 45         cout<<"STAGE" <<nOpp<<endl;
 46         cout<<"Your opponent, a Level "<<i<<" Swordsman."<<endl;
 47         system("pause");
 48         swordsman enemy(i, "Warrior");    // Initialise an opponent, level i, name "Junior"
 49         human->reFill();                // get HP/MP refill before start fight
 50         
 51         while(!human->death() && !enemy.death())    // no died
 52         {
 53             success=0;
 54             while (success!=1)
 55             {
 56                 showinfo(*human,enemy);                // show fighter's information
 57                 cout<<"Please give command: "<<endl;
 58                 cout<<"1 Attack; 2 Special Attack; 3 Use Heal; 4 Use Magic Water; 0 Exit Game"<<endl;
 59                 cin>>tempCom;
 60                 switch(tempCom)
 61                 {
 62                 case 0:
 63                     cout<<"Are you sure to exit? Y/N"<<endl;
 64                     char temp;
 65                     cin>>temp;
 66                     if(temp=='Y'||temp=='y')
 67                         return 0;
 68                     else
 69                         break;
 70                 case 1:
 71                     success=human->attack(enemy);
 72                     human->isLevelUp();
 73                     enemy.isDead();
 74                     break;
 75                 case 2:
 76                     success=human->specialatt(enemy);
 77                     human->isLevelUp();
 78                     enemy.isDead();
 79                     break;
 80                 case 3:
 81                     success=human->useHeal();
 82                     break;
 83                 case 4:
 84                     success=human->useMW();
 85                     break;
 86                 default:
 87                     break;
 88                 }
 89             }
 90             if(!enemy.death())        // If AI still alive
 91                 enemy.AI(*human);
 92             else                            // AI died
 93             {
 94                 cout<<"YOU WIN"<<endl;
 95                 human->transfer(enemy);        // player got all AI's items
 96             }
 97             if (human->death())
 98             {
 99                 system("cls");
100                 cout<<endl<<setw(50)<<"GAME OVER"<<endl;
101                 human->isDead();        // player is dead, program is getting to its end, what should we do here?
102                 system("pause");
103                 return 0;
104             }
105         }
106     }
107     cout << endl << "Clear" <<endl;        // You win, program is getting to its end, what should we do here?
108     system("cls");
109     cout<<"Congratulations! You defeated all opponents!!"<<endl;
110     system("pause");
111     return 0;
112 }
113     
main.cpp

“运行截图”

实验五 模板类与多态

 

 

 

 

 

上一篇:实验五 模板类与多态


下一篇:数据结构之【堆的实现】