实验五 继承和多态
实验任务4
.hpp
1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 6 using namespace std; 7 8 class MachinePets { 9 public: 10 MatinePets(const string nickname0) { 11 this->nickname = nickname0; 12 }; 13 string get_nickname() const { return nickname; }; 14 virtual string talk() = 0; 15 16 private: 17 string nickname; 18 }; 19 20 class PetCats:public MachinePets { 21 public: 22 PetCats(const string nickname0){ 23 MatinePets(nickname0); 24 }; 25 string talk() { return "miao wu~"; }; 26 27 private: 28 string nickname; 29 }; 30 31 class PetDogs:public MachinePets { 32 public: 33 PetDogs(const string nickname0) { 34 MatinePets(nickname0); 35 }; 36 string talk() { return "wang wang~"; }; 37 38 private: 39 string nickname; 40 };
.cpp
1 #include <iostream> 2 #include "pets.hpp" 3 4 void play(MachinePets &obj) { 5 std::cout << obj.get_nickname() << " says " << obj.talk() << std::endl; 6 } 7 8 void test() { 9 PetCats cat("miku"); 10 PetDogs dog("da huang"); 11 12 play( cat ); 13 play( dog ); 14 } 15 16 int main() { 17 test(); 18 }
实验任务5
.hpp
1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 #include <iomanip> 6 #include <fstream> 7 8 using namespace std; 9 10 class Person { 11 public: 12 Person() {}; 13 Person(string name0, string phone0, string email0): name{name0}, phone{phone0}, email{email0} {}; 14 Person(const Person &p): name{p.name}, phone{p.phone}, email{p.email} {}; 15 void update_email(); 16 void update_telephone() ; 17 18 friend ostream& operator<<(ostream &out, const Person &p); 19 friend istream& operator>>(istream &in, Person &p); 20 friend bool operator==(const Person p1, const Person p2); 21 22 private: 23 string name, email, phone; 24 }; 25 26 void Person::update_email() { 27 cout << "Enter the email adress: "; 28 cin.clear(); 29 cin >> email; 30 cout << "email adress has been update...\n"; 31 } 32 33 void Person::update_telephone() { 34 cout << "Enter the telephone number: "; 35 cin.clear(); 36 cin >> phone; 37 cout << "telephone number has been updated...\n"; 38 } 39 40 ostream& operator<<(ostream &out, const Person &p) { 41 out << left << setw(10) << p.name << setw(10) << p.phone << setw(10) << p.email; 42 return out; 43 } 44 45 istream& operator>>(istream &in, Person &p) { 46 getline(in, p.name); 47 getline(in, p.phone); 48 getline(in, p.email); 49 cout << "\n"; 50 return in; 51 } 52 53 bool operator==(Person p1, Person p2) { 54 return (p1.name == p2.name && p1.phone == p2.phone && p1.email == p2.email); 55 }
.cpp
1 #include <iostream> 2 #include <fstream> 3 #include <vector> 4 #include "Person.hpp" 5 6 void test() { 7 using namespace std; 8 9 vector<Person> phone_book; 10 Person p; 11 12 cout << "Enter person's contact until press Ctrl + Z" << endl; 13 while(cin >> p) 14 phone_book.push_back(p); 15 16 cout << "\nupdate someone's contact: \n"; 17 phone_book.at(0).update_telephone(); 18 phone_book.at(0).update_email(); 19 20 cout << "\ndisplay all contacts' info\n"; 21 for(auto &phone:phone_book) 22 cout << phone << endl; 23 24 cout << "\ntest whether the same contact\n"; 25 cout << boolalpha <<(phone_book.at(0) == phone_book.at(1)) << endl; 26 } 27 28 int main() { 29 test(); 30 }
实验任务6
container
.hpp
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 class container // Inventory 12 { 13 protected: 14 int numOfHeal; // number of heal 15 int numOfMW; // number of magic water 16 public: 17 container(); // constuctor 18 void set(int heal_n, int mw_n); // set the items numbers 19 int nOfHeal(); // get the number of heal 20 int nOfMW(); // get the number of magic water 21 void display(); // display the items; 22 bool useHeal(); // use heal 23 bool useMW(); // use magic water 24 }; 25 26 #endif
.cpp
1 //======================= 2 // container.cpp 3 //======================= 4 #include <iostream> 5 #include "container.h" 6 7 using namespace std; 8 9 // default constructor initialise the inventory as empty 10 container::container() 11 { 12 set(0,0); 13 } 14 15 // set the item numbers 16 void container::set(int heal_n, int mw_n) 17 { 18 numOfHeal=heal_n; 19 numOfMW=mw_n; 20 } 21 22 // get the number of heal 23 int container::nOfHeal() 24 { 25 return numOfHeal; 26 } 27 28 // get the number of magic water 29 int container::nOfMW() 30 { 31 return numOfMW; 32 } 33 34 // display the items; 35 void container::display() 36 { 37 cout<<"Your bag contains: "<<endl; 38 cout<<"Heal(HP+100): "<<numOfHeal<<endl; 39 cout<<"Magic Water (MP+80): "<<numOfMW<<endl; 40 } 41 42 //use heal 43 bool container::useHeal() 44 { 45 numOfHeal--; 46 return 1; // use heal successfully 47 } 48 49 //use magic water 50 bool container::useMW() 51 { 52 numOfMW--; 53 return 1; // use magic water successfully 54 }
player
.hpp
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 15 using namespace std; 16 17 enum job {sw, ar, mg}; /* define 3 jobs by enumerate type 18 sword man, archer, mage */ 19 class player 20 { 21 friend void showinfo(player &p1, player &p2); 22 friend class swordsman; 23 24 protected: 25 int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV; 26 // General properties of all characters 27 string name; // character name 28 job role; /* character's job, one of swordman, archer and mage, 29 as defined by the enumerate type */ 30 container bag; // character's inventory 31 32 public: 33 virtual bool attack(player &p)=0; // normal attack 34 virtual bool specialatt(player &p)=0; //special attack 35 virtual void isLevelUp()=0; // level up judgement 36 /* Attention! 37 These three methods are called "Pure virtual functions". 38 They have only declaration, but no definition. 39 The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 40 The detailed definition of these pure virtual functions will be given in subclasses. */ 41 42 void reFill(); // character's HP and MP resume 43 bool death(); // report whether character is dead 44 void isDead(); // check whether character is dead 45 bool useHeal(); // consume heal, irrelevant to job 46 bool useMW(); // consume magic water, irrelevant to job 47 void transfer(player &p); // possess opponent's items after victory 48 void showRole(); // display character's job 49 50 private: 51 bool playerdeath; // whether character is dead, doesn't need to be accessed or inherited 52 }; 53 54 #endif
.cpp
1 //======================= 2 // player.cpp 3 //======================= 4 #include <iostream> 5 #include "player.h" 6 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(p.bag.nOfHeal()+bag.nOfHeal(),p.bag.nOfMW()+bag.nOfMW()); 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) 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 }
swardsman
.hpp
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 };
.cpp
1 //======================= 2 // swordsman.cpp 3 //======================= 4 #include <iostream> 5 #include "swordsman.h" 6 7 // constructor. default values don't need to be repeated here 8 swordsman::swordsman(int lv_in, string name_in) 9 { 10 role=sw; // enumerate type of job 11 LV=lv_in; 12 name=name_in; 13 14 // Initialising the character's properties, based on his level 15 HPmax=150+8*(LV-1); // HP increases 8 point2 per level 16 HP=HPmax; 17 MPmax=75+2*(LV-1); // MP increases 2 points per level 18 MP=MPmax; 19 AP=25+4*(LV-1); // AP increases 4 points per level 20 DP=25+4*(LV-1); // DP increases 4 points per level 21 speed=25+2*(LV-1); // speed increases 2 points per level 22 23 playerdeath=0; 24 EXP=LV*LV*75; 25 bag.set(lv_in, lv_in); 26 } 27 28 void swordsman::isLevelUp() 29 { 30 if(EXP>=LV*LV*75) 31 { 32 LV++; 33 AP+=4; 34 DP+=4; 35 HPmax+=8; 36 MPmax+=2; 37 speed+=2; 38 cout<<name<<" Level UP!"<<endl; 39 cout<<"HP improved 8 points to "<<HPmax<<endl; 40 cout<<"MP improved 2 points to "<<MPmax<<endl; 41 cout<<"Speed improved 2 points to "<<speed<<endl; 42 cout<<"AP improved 4 points to "<<AP<<endl; 43 cout<<"DP improved 5 points to "<<DP<<endl; 44 system("pause"); 45 isLevelUp(); // recursively call this function, so the character can level up multiple times if got enough exp 46 } 47 } 48 49 bool swordsman::attack(player &p) 50 { 51 double HPtemp=0; // opponent's HP decrement 52 double EXPtemp=0; // player obtained exp 53 double hit=1; // attach factor, probably give critical attack 54 srand((unsigned)time(NULL)); // generating random seed based on system time 55 56 // If speed greater than opponent, you have some possibility to do double attack 57 if ((speed>p.speed) && (rand()%100<(speed-p.speed))) // rand()%100 means generates a number no greater than 100 58 { 59 HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10)); // opponent's HP decrement calculated based their AP/DP, and uncertain chance 60 cout<<name<<"'s quick strike hit "<<p.name<<", "<<p.name<<"'s HP decreased "<<HPtemp<<endl; 61 p.HP=int(p.HP-HPtemp); 62 EXPtemp=(int)(HPtemp*1.2); 63 } 64 65 // If speed smaller than opponent, the opponent has possibility to evade 66 if ((speed<p.speed) && (rand()%50<1)) 67 { 68 cout<<name<<"'s attack has been evaded by "<<p.name<<endl; 69 system("pause"); 70 return 1; 71 } 72 73 // 10% chance give critical attack 74 if (rand()%100<=10) 75 { 76 hit=1.5; 77 cout<<"Critical attack: "; 78 } 79 80 // Normal attack 81 HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10)); 82 cout<<name<<" uses bash, "<<p.name<<"'s HP decreases "<<HPtemp<<endl; 83 EXPtemp=(int)(EXPtemp+HPtemp*1.2); 84 p.HP=(int)(p.HP-HPtemp); 85 cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl; 86 EXP=(int)(EXP+EXPtemp); 87 system("pause"); 88 return 1; // Attack success 89 } 90 91 bool swordsman::specialatt(player &p) 92 { 93 if(MP<40) 94 { 95 cout<<"You don't have enough magic points!"<<endl; 96 system("pause"); 97 return 0; // Attack failed 98 } 99 else 100 { 101 MP-=40; // consume 40 MP to do special attack 102 103 //10% chance opponent evades 104 if(rand()%100<=10) 105 { 106 cout<<name<<"'s leap attack has been evaded by "<<p.name<<endl; 107 system("pause"); 108 return 1; 109 } 110 111 double HPtemp=0; 112 double EXPtemp=0; 113 //double hit=1; 114 //srand(time(NULL)); 115 HPtemp=(int)(AP*1.2+20); // not related to opponent's DP 116 EXPtemp=(int)(HPtemp*1.5); // special attack provides more experience 117 cout<<name<<" uses leap attack, "<<p.name<<"'s HP decreases "<<HPtemp<<endl; 118 cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl; 119 p.HP=(int)(p.HP-HPtemp); 120 EXP=(int)(EXP+EXPtemp); 121 system("pause"); 122 } 123 return 1; // special attack succeed 124 } 125 126 // Computer opponent 127 void swordsman::AI(player &p) 128 { 129 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))) 130 // AI's HP cannot sustain 3 rounds && not too lavish && still has heal && won't be killed in next round 131 { 132 useHeal(); 133 } 134 else 135 { 136 if(MP>=40 && HP>0.5*HPmax && rand()%100<=30) 137 // AI has enough MP, it has 30% to make special attack 138 { 139 specialatt(p); 140 p.isDead(); // check whether player is dead 141 } 142 else 143 { 144 if (MP<40 && HP>0.5*HPmax && bag.nOfMW()) 145 // Not enough MP && HP is safe && still has magic water 146 { 147 useMW(); 148 } 149 else 150 { 151 attack(p); // normal attack 152 p.isDead(); 153 } 154 } 155 } 156 }
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 } 112
//=======================//main.cpp//=======================
// main function for the RPG style game
#include <iostream>#include <string>using namespace std;
#include "swordsman.h"
int main(){string tempName;bool success=0;//flag for storing whether operation is successfulcout <<"Please input player's name: ";cin >>tempName;// get player's name from keyboard inputplayer *human;// use pointer of base class, convenience for polymorphismint tempJob;// temp choice for job selectiondo{cout <<"Please choose a job: 1 Swordsman, 2 Archer, 3 Mage"<<endl;cin>>tempJob;system("cls");// clear the screenswitch(tempJob){case 1:human=new swordsman(1,tempName);// create the character with user inputted name and jobsuccess=1;// operation succeedbreak;default:break;// In this case, success=0, character creation failed}}while(success!=1);// so the loop will ask user to re-create a character
int tempCom;// temp command inputted by userint nOpp=0;// the Nth opponentfor(int i=1;nOpp<5;i+=2)// i is opponent's level{nOpp++;system("cls");cout<<"STAGE" <<nOpp<<endl;cout<<"Your opponent, a Level "<<i<<" Swordsman."<<endl;system("pause");swordsman enemy(i, "Warrior");// Initialise an opponent, level i, name "Junior"human->reFill();// get HP/MP refill before start fightwhile(!human->death() && !enemy.death())// no died{success=0;while (success!=1){showinfo(*human,enemy);// show fighter's informationcout<<"Please give command: "<<endl;cout<<"1 Attack; 2 Special Attack; 3 Use Heal; 4 Use Magic Water; 0 Exit Game"<<endl;cin>>tempCom;switch(tempCom){case 0:cout<<"Are you sure to exit? Y/N"<<endl;char temp;cin>>temp;if(temp=='Y'||temp=='y')return 0;elsebreak;case 1:success=human->attack(enemy);human->isLevelUp();enemy.isDead();break;case 2:success=human->specialatt(enemy);human->isLevelUp();enemy.isDead();break;case 3:success=human->useHeal();break;case 4:success=human->useMW();break;default:break;}}if(!enemy.death())// If AI still aliveenemy.AI(*human);else// AI died{cout<<"YOU WIN"<<endl;human->transfer(enemy);// player got all AI's items}if (human->death()){system("cls");cout<<endl<<setw(50)<<"GAME OVER"<<endl;delete human;// player is dead, program is getting to its end, what should we do here?system("pause");return 0;}}}delete human;// You win, program is getting to its end, what should we do here?system("cls");cout<<"Congratulations! You defeated all opponents!!"<<endl;system("pause");return 0;}