实验5 模板类与多态

实验任务2

"Person.hpp"

 1 #ifndef _PERSON
 2 #define _PERSON
 3 
 4 #include <iostream>
 5 #include <string>
 6 #include <iomanip>
 7 using namespace std;
 8 
 9 class Person {
10     public:
11         Person();
12         Person(string na, string tel, string ema);
13         void change_tel(string new_tel);
14         void change_ema(string new_ema);
15         friend ostream &operator << (ostream &out, const Person &x);
16         friend istream &operator >> (istream &in, Person &x);
17         friend bool operator == (const Person &a, const Person &b);
18     private:
19         string name;
20         string telephone;
21         string email;
22 };
23 
24 Person::Person() {
25     name = "";
26     telephone = "";
27     email = "";
28 }
29 
30 Person::Person(string na, string tel, string ema) {
31     name = na;
32     telephone = tel;
33     email = ema;
34 }
35 
36 void Person::change_tel(string new_tel) {
37     telephone = new_tel;
38 }
39 
40 void Person::change_ema(string new_ema) {
41     email = new_ema;
42 }
43 
44 ostream &operator << (ostream &out, const Person &x) {
45     out << left << setw(20) << x.name << setw(20) << x.telephone << x.email;
46 
47     return out;
48 }
49 
50 istream &operator >> (istream &in, Person &x) {
51     getline(in >> ws, x.name);
52     in >> x.telephone >> x.email;
53 
54     return in;
55 }
56 
57 bool operator == (const Person &a, const Person &b) {
58     if (a.name == b.name && a.telephone == b.telephone)
59         return true;
60     else
61         return false;
62 }
63 
64 #endif
View Code

"task2.cpp"

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

运行结果

 

 

实验任务3

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

"container.cpp"

 1 //=======================
 2 //        container.cpp
 3 //=======================
 4 
 5 // default constructor initialise the inventory as empty
 6 #include "container.h"
 7 
 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--;
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 }
View Code

"container.h"

 1 //=======================
 2 //        container.h
 3 //=======================
 4 
 5 // The so-called inventory of a player in RPG games
 6 // contains two items, heal and magic water
 7 
 8 #ifndef _CONTAINER    // Conditional compilation
 9 #define _CONTAINER
10 
11 #include <iostream>
12 using namespace std;
13 
14 class container        // Inventory
15 {
16 protected:
17     int numOfHeal;            // number of heal
18     int numOfMW;            // number of magic water
19 public:
20     container();            // constuctor
21     void set(int heal_n, int mw_n);    // set the items numbers
22     int nOfHeal();            // get the number of heal
23     int nOfMW();            // get the number of magic water
24     void display();            // display the items;
25     bool useHeal();            // use heal
26     bool useMW();            // use magic water
27 };
28 
29 #endif
View Code

"player.cpp"

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

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

"swordsman.cpp"

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

"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 #include <string>
10 using namespace std;
11 
12 class swordsman: public player    // subclass swordsman publicly inherited from base player
13 {
14 public:
15     swordsman(int lv_in=1, string name_in="Not Given");    
16         // constructor with default level of 1 and name of "Not given"
17     void isLevelUp();
18     bool attack (player &p);
19     bool specialatt(player &p);
20         /* These three are derived from the pure virtual functions of base class
21            The definition of them will be given in this subclass. */
22     void AI(player &p);                // Computer opponent
23 };
View Code

运行结果

 

 

 

posted on 2021-12-11 22:12  Yukito0209  阅读(25)  评论(2)    收藏  举报