实验五 模板与多态

实验任务二

#main_task2.cpp

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

#Person_task.hpp

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

 

 实验任务三

  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 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;    // 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;        // 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         
 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 using namespace std;
11 #include<iostream>
12 #include<string>
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
 1 //=======================
 2 //        container.cpp
 3 //=======================
 4 
 5 // default constructor initialise the inventory as empty
 6 #include "container.h"
 7 using namespace std;
 8 #include<iostream>
 9 #include<string>
10 
11 
12 container::container()
13 {
14     set(0,0);
15 }
16 
17 // set the item numbers
18 void container::set(int heal_n, int mw_n)
19 {
20     numOfHeal=heal_n;
21     numOfMW=mw_n;
22 }
23 
24 // get the number of heal
25 int container::nOfHeal()
26 {
27     return numOfHeal;
28 }
29 
30 // get the number of magic water
31 int container::nOfMW()
32 {
33     return numOfMW;
34 }
35 
36 // display the items;
37 void container::display()
38 {
39     cout<<"Your bag contains: "<<endl;
40     cout<<"Heal(HP+100): "<<numOfHeal<<endl;
41     cout<<"Magic Water (MP+80): "<<numOfMW<<endl;
42 }
43 
44 //use heal
45 bool container::useHeal()
46 {
47     numOfHeal--;
48     return 1;        // use heal successfully
49 }
50 
51 //use magic water
52 bool container::useMW()
53 {
54     numOfMW--;
55     return 1;        // use magic water successfully
56 }
 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 #include<iostream>
16 #include<string>
17 
18 
19 enum job {sw, ar, mg};    /* define 3 jobs by enumerate type
20                                sword man, archer, mage */
21 class player
22 {
23     friend void showinfo(player &p1, player &p2);
24     friend class swordsman;
25 
26 protected:
27     int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV;
28     // General properties of all characters
29     string name;    // character name
30     job role;        /* character's job, one of swordman, archer and mage,
31                        as defined by the enumerate type */
32     container bag;    // character's inventory
33 
34 public:
35     virtual bool attack(player &p)=0;    // normal attack
36     virtual bool specialatt(player &p)=0;    //special attack
37     virtual void isLevelUp()=0;            // level up judgement
38     /* Attention!
39     These three methods are called "Pure virtual functions".
40     They have only declaration, but no definition.
41     The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 
42     The detailed definition of these pure virtual functions will be given in subclasses. */
43 
44     void reFill();        // character's HP and MP resume
45     bool death();        // report whether character is dead
46     void isDead();        // check whether character is dead
47     bool useHeal();        // consume heal, irrelevant to job
48     bool useMW();        // consume magic water, irrelevant to job
49     void transfer(player &p);    // possess opponent's items after victory
50     void showRole();    // display character's job
51     
52 private:
53     bool playerdeath;            // whether character is dead, doesn't need to be accessed or inherited
54 };
55 
56 #endif
  1 //=======================
  2 //        player.cpp
  3 //=======================
  4 #include "player.h"
  5 using namespace std;
  6 #include<iostream>
  7 #include<string>
  8 
  9 // character's HP and MP resume
 10 void player::reFill()
 11 {
 12     HP=HPmax;        // HP and MP fully recovered
 13     MP=MPmax;
 14 }
 15 
 16 // report whether character is dead
 17 bool player::death()
 18 {
 19     return playerdeath;
 20 }
 21 
 22 // check whether character is dead
 23 void player::isDead()
 24 {
 25     if(HP<=0)        // HP less than 0, character is dead
 26     {
 27         cout<<name<<" is Dead." <<endl;
 28         system("pause");
 29         playerdeath=1;    // give the label of death value 1
 30     }
 31 }
 32 
 33 // consume heal, irrelevant to job
 34 bool player::useHeal()
 35 {
 36     if(bag.nOfHeal()>0)
 37     {
 38         HP=HP+100;
 39         if(HP>HPmax)        // HP cannot be larger than maximum value
 40             HP=HPmax;        // so assign it to HPmax, if necessary
 41         cout<<name<<" used Heal, HP increased by 100."<<endl;
 42         bag.useHeal();        // use heal
 43         system("pause");
 44         return 1;    // usage of heal succeed
 45     }
 46     else                // If no more heal in bag, cannot use
 47     {
 48         cout<<"Sorry, you don't have heal to use."<<endl;
 49         system("pause");
 50         return 0;    // usage of heal failed
 51     }
 52 }
 53 
 54 // consume magic water, irrelevant to job
 55 bool player::useMW()
 56 {
 57     if(bag.nOfMW()>0)
 58     {
 59         MP=MP+100;
 60         if(MP>MPmax)
 61             MP=MPmax;
 62         cout<<name<<" used Magic Water, MP increased by 100."<<endl;
 63         bag.useMW();
 64         system("pause");
 65         return 1;    // usage of magic water succeed
 66     }
 67     else
 68     {
 69         cout<<"Sorry, you don't have magic water to use."<<endl;
 70         system("pause");
 71         return 0;    // usage of magic water failed
 72     }
 73 }
 74 
 75 // possess opponent's items after victory
 76 void player::transfer(player &p)
 77 {
 78     cout<<name<<" got"<<p.bag.nOfHeal()<<" Heal, and "<<p.bag.nOfMW()<<" Magic Water."<<endl;
 79     system("pause");
 80 //    3_???????????
 81     bag.set(bag.nOfHeal() + p.bag.nOfHeal(), bag.nOfMW() + p.bag.nOfMW());
 82     // set the character's bag, get opponent's items
 83 }
 84 
 85 // display character's job
 86 void player::showRole()
 87 {
 88     switch(role)
 89     {
 90     case sw:
 91         cout<<"Swordsman";
 92         break;
 93     case ar:
 94         cout<<"Archer";
 95         break;
 96     case mg:
 97         cout<<"Mage";
 98         break;
 99     default:
100         break;
101     }
102 }
103 
104 
105 // display character's job
106 //4_??????????????    
107 void showinfo(player &p1, player &p2)
108 {
109     system("cls");
110     cout<<"##############################################################"<<endl;
111     cout<<"# Player"<<setw(10)<<p1.name<<"   LV. "<<setw(3) <<p1.LV
112         <<"  # Opponent"<<setw(10)<<p2.name<<"   LV. "<<setw(3) <<p2.LV<<" #"<<endl;
113     cout<<"# HP "<<setw(3)<<(p1.HP<=999?p1.HP:999)<<'/'<<setw(3)<<(p1.HPmax<=999?p1.HPmax:999)
114         <<" | MP "<<setw(3)<<(p1.MP<=999?p1.MP:999)<<'/'<<setw(3)<<(p1.MPmax<=999?p1.MPmax:999)
115         <<"     # HP "<<setw(3)<<(p2.HP<=999?p2.HP:999)<<'/'<<setw(3)<<(p2.HPmax<=999?p2.HPmax:999)
116         <<" | MP "<<setw(3)<<(p2.MP<=999?p2.MP:999)<<'/'<<setw(3)<<(p2.MPmax<=999?p2.MPmax:999)<<"      #"<<endl;
117     cout<<"# AP "<<setw(3)<<(p1.AP<=999?p1.AP:999)
118         <<" | DP "<<setw(3)<<(p1.DP<=999?p1.DP:999)
119         <<" | speed "<<setw(3)<<(p1.speed<=999?p1.speed:999)
120         <<" # AP "<<setw(3)<<(p2.AP<=999?p2.AP:999)
121         <<" | DP "<<setw(3)<<(p2.DP<=999?p2.DP:999)
122         <<" | speed "<<setw(3)<<(p2.speed<=999?p2.speed:999)<<"  #"<<endl;
123     cout<<"# EXP"<<setw(7)<<p1.EXP<<" Job: "<<setw(7);
124     p1.showRole();
125     cout<<"   # EXP"<<setw(7)<<p2.EXP<<" Job: "<<setw(7);
126     p2.showRole();
127     cout<<"    #"<<endl;
128     cout<<"--------------------------------------------------------------"<<endl;
129     p1.bag.display();
130     cout<<"##############################################################"<<endl;
131 }
//=======================
//        swordsman.h
//=======================

// Derived from base class player
// For the job Swordsman
#ifndef _SWORDSMAN
#define _SWORDSMAN
#include<string>
#include "player.h"
class swordsman : public player        // subclass swordsman publicly inherited from base player
{
public:
    swordsman(int lv_in=1, string name_in="Not Given");    
        // constructor with default level of 1 and name of "Not given"
    void isLevelUp();
    bool attack (player &p);
    bool specialatt(player &p);
        /* These three are derived from the pure virtual functions of base class
           The definition of them will be given in this subclass. */
    void AI(player &p);                // Computer opponent
};

#endif
  1 //=======================
  2 //        swordsman.cpp
  3 //=======================
  4 #include "swordsman.h"
  5 using namespace std;
  6 #include<iostream>
  7 #include<string>
  8 
  9 
 10 // constructor. default values don't need to be repeated here
 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 }

 

 

 

 

posted @ 2021-12-09 22:34  曾经蜡笔没有小新i  阅读(61)  评论(2)    收藏  举报