实验5 模板类与多态

实验任务2

  • Person.hpp源码

 1 #include <iostream>
 2 #include <fstream>
 3 #include <vector>
 4 #include "Person.hpp"
 5 
 6 int main()
 7 {
 8     using namespace std;
 9 
10     vector<Person> phone_book;
11     Person p;
12 
13     while(cin>>p)
14         phone_book.push_back(p);
15     
16     for(auto &i: phone_book)
17         cout << i << endl;
18     
19     cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl;
20 
21     ofstream fout;
22 
23     fout.open("phone_book.txt");
24 
25     if(!fout.is_open())
26     {
27         cerr << "fail to open file phone_book.txt\n";
28         return 1;
29     }
30 
31     for(auto &i: phone_book)
32         fout << i << endl;
33     
34     fout.close();
35 }

 

  • task2.cpp源码

 1 #ifndef PERSON_HPP
 2 #define PERSON_HPP
 3 #include <iostream>
 4 #include <iomanip>
 5 using namespace std;
 6 class Person
 7 {
 8 private:
 9     string name;
10     string telephone;
11     string email;
12 public :
13     Person(){
14     };
15     Person(string n,string t,string e=" "):name(n),telephone(t),email(e){
16     };
17     void reset_telephone(string t){
18         telephone = t;
19     }
20     void reset_email(string e){
21         email = e;
22     }    
23     friend ostream & operator<<(ostream & out,const Person &p);
24     friend istream & operator>>(istream & in, Person &p) ;
25     friend bool operator==(const Person &p1, const Person &p2);
26 };
27 
28 ostream & operator<<(ostream & out,const Person &p)
29 {
30     out<<setiosflags(ios::left);
31     out<<setw(20)<<p.name<<setw(15)<<p.telephone<<p.email<<endl;
32 }
33 
34 istream & operator>>(istream & in, Person &p)
35 {
36     char ch;
37     getline(in,p.name);
38     getline(in,p.telephone);
39     getline(in,p.email);
40     in.get(ch);
41 }
42 
43 bool operator==(const Person &p1, const Person &p2)
44 {
45     if(p1.name==p2.name&&p1.telephone==p2.telephone)
46     {
47         return true;
48     }
49     else
50     {
51         return false;
52     }
53 }
54 #endif 

 

  • 行结果截图

    • 屏幕截图

      

    • 数据文件

      

  • 回答问题

    • 在测试代码中, cout << i ,编译器会将这个表达式转换成:
operator<<(cout,i)
    • 在测试代码中, fout << i ,编译器会将这个表达式转换成:
operator<<(fout,i)

 实验任务3

container.h

//=======================
//        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.cpp

 1 //=======================
 2 //        container.cpp
 3 //=======================
 4 #include "container.h"
 5 #include <iostream>
 6 using namespace std;
 7 // default constructor initialise the inventory as empty
 8 container::container()
 9 {
10     set(0,0);
11 }
12 
13 // set the item numbers
14 void container::set(int heal_n, int mw_n)
15 {
16     numOfHeal=heal_n;
17     numOfMW=mw_n;
18 }
19 
20 // get the number of heal
21 int container::nOfHeal()
22 {
23     return numOfHeal;
24 }
25 
26 // get the number of magic water
27 int container::nOfMW()
28 {
29     return numOfMW;
30 }
31 
32 // display the items;
33 void container::display()
34 {
35     cout<<"Your bag contains: "<<endl;
36     cout<<"Heal(HP+100): "<<numOfHeal<<endl;
37     cout<<"Magic Water (MP+80): "<<numOfMW<<endl;
38 }
39 
40 //use heal
41 bool container::useHeal()
42 {
43     numOfHeal--;//2_????????
44     return 1;        // use heal successfully
45 }
46 
47 //use magic water
48 bool container::useMW()
49 {
50     numOfMW--;
51     return 1;        // use magic water successfully
52 }

 

player.h

 1 //=======================
 2 //        player.h
 3 //=======================
 4 
 5 // The base class of player
 6 // including the general properties and methods related to a character
 7 
 8 #ifndef _PLAYER
 9 #define _PLAYER
10 #include <iostream>
11 #include <iomanip>        // use for setting field width
12 #include <time.h>        // use for generating random factor
13 #include "container.h"
14 using namespace std;
15 enum job {sw, ar, mg};    /* define 3 jobs by enumerate type
16                                sword man, archer, mage */
17 class player
18 {
19     friend void showinfo(player &p1, player &p2);
20     friend class swordsman;
21 
22 protected:
23     int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV;
24     // General properties of all characters
25     string name;    // character name
26     job role;        /* character's job, one of swordman, archer and mage,
27                        as defined by the enumerate type */
28     container bag;    // character's inventory
29 
30 public:
31     virtual bool attack(player &p)=0;    // normal attack
32     virtual bool specialatt(player &p)=0;    //special attack
33     virtual void isLevelUp()=0;            // level up judgement
34     /* Attention!
35     These three methods are called "Pure virtual functions".
36     They have only declaration, but no definition.
37     The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 
38     The detailed definition of these pure virtual functions will be given in subclasses. */
39 
40     void reFill();        // character's HP and MP resume
41     bool death();        // report whether character is dead
42     void isDead();        // check whether character is dead
43     bool useHeal();        // consume heal, irrelevant to job
44     bool useMW();        // consume magic water, irrelevant to job
45     void transfer(player &p);    // possess opponent's items after victory
46     void showRole();    // display character's job
47     
48 private:
49     bool playerdeath;            // whether character is dead, doesn't need to be accessed or inherited
50 };
51 
52 #endif

 

player.cpp

  1 //=======================
  2 //        player.cpp
  3 //=======================
  4 #include "player.h"
  5 #include <iostream>
  6 using namespace std;
  7 // character's HP and MP resume
  8 void player::reFill()
  9 {
 10     HP=HPmax;        // HP and MP fully recovered
 11     MP=MPmax;
 12 }
 13 
 14 // report whether character is dead
 15 bool player::death()
 16 {
 17     return playerdeath;
 18 }
 19 
 20 // check whether character is dead
 21 void player::isDead()
 22 {
 23     if(HP<=0)        // HP less than 0, character is dead
 24     {
 25         cout<<name<<" is Dead." <<endl;
 26         system("pause");
 27         playerdeath=1;    // give the label of death value 1
 28     }
 29 }
 30 
 31 // consume heal, irrelevant to job
 32 bool player::useHeal()
 33 {
 34     if(bag.nOfHeal()>0)
 35     {
 36         HP=HP+100;
 37         if(HP>HPmax)        // HP cannot be larger than maximum value
 38             HP=HPmax;        // so assign it to HPmax, if necessary
 39         cout<<name<<" used Heal, HP increased by 100."<<endl;
 40         bag.useHeal();        // use heal
 41         system("pause");
 42         return 1;    // usage of heal succeed
 43     }
 44     else                // If no more heal in bag, cannot use
 45     {
 46         cout<<"Sorry, you don't have heal to use."<<endl;
 47         system("pause");
 48         return 0;    // usage of heal failed
 49     }
 50 }
 51 
 52 // consume magic water, irrelevant to job
 53 bool player::useMW()
 54 {
 55     if(bag.nOfMW()>0)
 56     {
 57         MP=MP+100;
 58         if(MP>MPmax)
 59             MP=MPmax;
 60         cout<<name<<" used Magic Water, MP increased by 100."<<endl;
 61         bag.useMW();
 62         system("pause");
 63         return 1;    // usage of magic water succeed
 64     }
 65     else
 66     {
 67         cout<<"Sorry, you don't have magic water to use."<<endl;
 68         system("pause");
 69         return 0;    // usage of magic water failed
 70     }
 71 }
 72 
 73 // possess opponent's items after victory
 74 void player::transfer(player &p)
 75 {
 76     cout<<name<<" got"<<p.bag.nOfHeal()<<" Heal, and "<<p.bag.nOfMW()<<" Magic Water."<<endl;
 77     system("pause");
 78     bag.set(bag.nOfHeal()+p.bag.nOfHeal(), bag.nOfMW() + bag.nOfMW());//3_???????????
 79     // set the character's bag, get opponent's items
 80 }
 81 
 82 // display character's job
 83 void player::showRole()
 84 {
 85     switch(role)
 86     {
 87     case sw:
 88         cout<<"Swordsman";
 89         break;
 90     case ar:
 91         cout<<"Archer";
 92         break;
 93     case mg:
 94         cout<<"Mage";
 95         break;
 96     default:
 97         break;
 98     }
 99 }
100 
101 
102 // display character's job
103 void showinfo(player& p1, player& p2)//4_??????????????    
104 {
105     system("cls");
106     cout<<"##############################################################"<<endl;
107     cout<<"# Player"<<setw(10)<<p1.name<<"   LV. "<<setw(3) <<p1.LV
108         <<"  # Opponent"<<setw(10)<<p2.name<<"   LV. "<<setw(3) <<p2.LV<<" #"<<endl;
109     cout<<"# HP "<<setw(3)<<(p1.HP<=999?p1.HP:999)<<'/'<<setw(3)<<(p1.HPmax<=999?p1.HPmax:999)
110         <<" | MP "<<setw(3)<<(p1.MP<=999?p1.MP:999)<<'/'<<setw(3)<<(p1.MPmax<=999?p1.MPmax:999)
111         <<"     # HP "<<setw(3)<<(p2.HP<=999?p2.HP:999)<<'/'<<setw(3)<<(p2.HPmax<=999?p2.HPmax:999)
112         <<" | MP "<<setw(3)<<(p2.MP<=999?p2.MP:999)<<'/'<<setw(3)<<(p2.MPmax<=999?p2.MPmax:999)<<"      #"<<endl;
113     cout<<"# AP "<<setw(3)<<(p1.AP<=999?p1.AP:999)
114         <<" | DP "<<setw(3)<<(p1.DP<=999?p1.DP:999)
115         <<" | speed "<<setw(3)<<(p1.speed<=999?p1.speed:999)
116         <<" # AP "<<setw(3)<<(p2.AP<=999?p2.AP:999)
117         <<" | DP "<<setw(3)<<(p2.DP<=999?p2.DP:999)
118         <<" | speed "<<setw(3)<<(p2.speed<=999?p2.speed:999)<<"  #"<<endl;
119     cout<<"# EXP"<<setw(7)<<p1.EXP<<" Job: "<<setw(7);
120     p1.showRole();
121     cout<<"   # EXP"<<setw(7)<<p2.EXP<<" Job: "<<setw(7);
122     p2.showRole();
123     cout<<"    #"<<endl;
124     cout<<"--------------------------------------------------------------"<<endl;
125     p1.bag.display();
126     cout<<"##############################################################"<<endl;
127 }

 

swordsman.h

 1 //=======================
 2 //        swordsman.h
 3 //=======================
 4 
 5 // Derived from base class player
 6 // For the job Swordsman
 7 
 8 #include "player.h"
 9 class swordsman : public player        // subclass swordsman publicly inherited from base player
10 {
11 public:
12     swordsman(int lv_in=1, string name_in="Not Given");    
13         // constructor with default level of 1 and name of "Not given"
14     void isLevelUp();
15     bool attack (player &p);
16     bool specialatt(player &p);
17         /* These three are derived from the pure virtual functions of base class
18            The definition of them will be given in this subclass. */
19     void AI(player &p);                // Computer opponent
20 };

 

swordsman.cpp

  1 //=======================
  2 //        swordsman.cpp
  3 //=======================
  4 #include "swordsman.h"
  5 // constructor. default values don't need to be repeated here
  6 swordsman::swordsman(int lv_in, string name_in)
  7 {
  8     role=sw;    // enumerate type of job
  9     LV=lv_in;
 10     name=name_in;
 11     
 12     // Initialising the character's properties, based on his level
 13     HPmax=150+8*(LV-1);        // HP increases 8 point2 per level
 14     HP=HPmax;
 15     MPmax=75+2*(LV-1);        // MP increases 2 points per level
 16     MP=MPmax;
 17     AP=25+4*(LV-1);            // AP increases 4 points per level
 18     DP=25+4*(LV-1);            // DP increases 4 points per level
 19     speed=25+2*(LV-1);        // speed increases 2 points per level
 20     
 21     playerdeath=0;
 22     EXP=LV*LV*75;
 23     bag.set(lv_in, lv_in);
 24 }
 25 
 26 void swordsman::isLevelUp()
 27 {
 28     if(EXP>=LV*LV*75)
 29     {
 30         LV++;
 31         AP+=4;
 32         DP+=4;
 33         HPmax+=8;
 34         MPmax+=2;
 35         speed+=2;
 36         cout<<name<<" Level UP!"<<endl;
 37         cout<<"HP improved 8 points to "<<HPmax<<endl;
 38         cout<<"MP improved 2 points to "<<MPmax<<endl;
 39         cout<<"Speed improved 2 points to "<<speed<<endl;
 40         cout<<"AP improved 4 points to "<<AP<<endl;
 41         cout<<"DP improved 5 points to "<<DP<<endl;
 42         system("pause");
 43         isLevelUp();    // recursively call this function, so the character can level up multiple times if got enough exp
 44     }
 45 }
 46 
 47 bool swordsman::attack(player &p)
 48 {
 49     double HPtemp=0;        // opponent's HP decrement
 50     double EXPtemp=0;        // player obtained exp
 51     double hit=1;            // attach factor, probably give critical attack
 52     srand((unsigned)time(NULL));        // generating random seed based on system time
 53 
 54     // If speed greater than opponent, you have some possibility to do double attack
 55     if ((speed>p.speed) && (rand()%100<(speed-p.speed)))        // rand()%100 means generates a number no greater than 100
 56     {
 57         HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10));        // opponent's HP decrement calculated based their AP/DP, and uncertain chance
 58         cout<<name<<"'s quick strike hit "<<p.name<<", "<<p.name<<"'s HP decreased "<<HPtemp<<endl;
 59         p.HP=int(p.HP-HPtemp);
 60         EXPtemp=(int)(HPtemp*1.2);
 61     }
 62 
 63     // If speed smaller than opponent, the opponent has possibility to evade
 64     if ((speed<p.speed) && (rand()%50<1))
 65     {
 66         cout<<name<<"'s attack has been evaded by "<<p.name<<endl;
 67         system("pause");
 68         return 1;
 69     }
 70 
 71     // 10% chance give critical attack
 72     if (rand()%100<=10)
 73     {
 74         hit=1.5;
 75         cout<<"Critical attack: ";
 76     }
 77 
 78     // Normal attack
 79     HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10));
 80     cout<<name<<" uses bash, "<<p.name<<"'s HP decreases "<<HPtemp<<endl;
 81     EXPtemp=(int)(EXPtemp+HPtemp*1.2);
 82     p.HP=(int)(p.HP-HPtemp);
 83     cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl;
 84     EXP=(int)(EXP+EXPtemp);
 85     system("pause");
 86     return 1;        // Attack success
 87 }
 88 
 89 bool swordsman::specialatt(player &p)
 90 {
 91     if(MP<40)
 92     {
 93         cout<<"You don't have enough magic points!"<<endl;
 94         system("pause");
 95         return 0;        // Attack failed
 96     }
 97     else
 98     {
 99         MP-=40;            // consume 40 MP to do special attack
100         
101         //10% chance opponent evades
102         if(rand()%100<=10)
103         {
104             cout<<name<<"'s leap attack has been evaded by "<<p.name<<endl;
105             system("pause");
106             return 1;
107         }
108         
109         double HPtemp=0;        
110         double EXPtemp=0;        
111         //double hit=1;            
112         //srand(time(NULL));        
113         HPtemp=(int)(AP*1.2+20);        // not related to opponent's DP
114         EXPtemp=(int)(HPtemp*1.5);        // special attack provides more experience
115         cout<<name<<" uses leap attack, "<<p.name<<"'s HP decreases "<<HPtemp<<endl;
116         cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl;
117         p.HP=(int)(p.HP-HPtemp);
118         EXP=(int)(EXP+EXPtemp);
119         system("pause");
120     }
121     return 1;    // special attack succeed
122 }
123 
124 // Computer opponent
125 void swordsman::AI(player &p)
126 {
127     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)))
128         // AI's HP cannot sustain 3 rounds && not too lavish && still has heal && won't be killed in next round
129     {
130         useHeal();
131     }
132     else
133     {
134         if(MP>=40 && HP>0.5*HPmax && rand()%100<=30)
135             // AI has enough MP, it has 30% to make special attack
136         {
137             specialatt(p);
138             p.isDead();        // check whether player is dead
139         }
140         else
141         {
142             if (MP<40 && HP>0.5*HPmax && bag.nOfMW())
143                 // Not enough MP && HP is safe && still has magic water
144             {
145                 useMW();
146             }
147             else
148             {
149                 attack(p);    // normal attack
150                 p.isDead();
151             }
152         }
153     }
154 }

 

main.cpp

  1 //=======================
  2 //        main.cpp
  3 //=======================
  4 
  5 // main function for the RPG style game
  6 
  7 #include <iostream>
  8 #include <string>
  9 using namespace std;
 10 #include "swordsman.h"
 11 
 12 
 13 int main()
 14 {
 15     string tempName;
 16     bool success=0;        //flag for storing whether operation is successful
 17     cout <<"Please input player's name: ";
 18     cin >>tempName;        // get player's name from keyboard input
 19     player *human;        // use pointer of base class, convenience for polymorphism
 20     int tempJob;        // temp choice for job selection
 21     do
 22     {
 23         cout <<"Please choose a job: 1 Swordsman, 2 Archer, 3 Mage"<<endl;
 24         cin>>tempJob;
 25         system("cls");        // clear the screen
 26         switch(tempJob)
 27         {
 28         case 1:
 29             human=new swordsman(1,tempName);    // create the character with user inputted name and job
 30             success=1;        // operation succeed
 31             break;
 32         default:
 33             break;                // In this case, success=0, character creation failed
 34         }
 35     }while(success!=1);        // so the loop will ask user to re-create a character
 36 
 37     int tempCom;            // temp command inputted by user
 38     int nOpp=0;                // the Nth opponent
 39     for(int i=1;nOpp<5;i+=2)    // i is opponent's level
 40     {
 41         nOpp++;
 42         system("cls");
 43         cout<<"STAGE" <<nOpp<<endl;
 44         cout<<"Your opponent, a Level "<<i<<" Swordsman."<<endl;
 45         system("pause");
 46         swordsman enemy(i, "Warrior");    // Initialise an opponent, level i, name "Junior"
 47         human->reFill();                // get HP/MP refill before start fight
 48         
 49         while(!human->death() && !enemy.death())    // no died
 50         {
 51             success=0;
 52             while (success!=1)
 53             {
 54                 showinfo(*human,enemy);                // show fighter's information
 55                 cout<<"Please give command: "<<endl;
 56                 cout<<"1 Attack; 2 Special Attack; 3 Use Heal; 4 Use Magic Water; 0 Exit Game"<<endl;
 57                 cin>>tempCom;
 58                 switch(tempCom)
 59                 {
 60                 case 0:
 61                     cout<<"Are you sure to exit? Y/N"<<endl;
 62                     char temp;
 63                     cin>>temp;
 64                     if(temp=='Y'||temp=='y')
 65                         return 0;
 66                     else
 67                         break;
 68                 case 1:
 69                     success=human->attack(enemy);
 70                     human->isLevelUp();
 71                     enemy.isDead();
 72                     break;
 73                 case 2:
 74                     success=human->specialatt(enemy);
 75                     human->isLevelUp();
 76                     enemy.isDead();
 77                     break;
 78                 case 3:
 79                     success=human->useHeal();
 80                     break;
 81                 case 4:
 82                     success=human->useMW();
 83                     break;
 84                 default:
 85                     break;
 86                 }
 87             }
 88             if(!enemy.death())        // If AI still alive
 89                 enemy.AI(*human);
 90             else                            // AI died
 91             {
 92                 cout<<"YOU WIN"<<endl;
 93                 human->transfer(enemy);        // player got all AI's items
 94             }
 95             if (human->death())
 96             {
 97                 system("cls");
 98                 cout<<endl<<setw(50)<<"GAME OVER"<<endl;
 99                 delete human;//6_???????????        // player is dead, program is getting to its end, what should we do here?
100                 system("pause");
101                 return 0;
102             }
103         }
104     }
105     delete human;//7_?????????            // You win, program is getting to its end, what should we do here?
106     system("cls");
107     cout<<"Congratulations! You defeated all opponents!!"<<endl;
108     system("pause");
109     return 0;
110 }
111         

运行结果截图:

 

 

 

 

 

 

 

 

 

 总结:

 

 

 

posted @ 2021-12-11 00:13  敲代码的喵  阅读(39)  评论(5编辑  收藏  举报