实验五


实验结论

实验1

模板类实现Complex

  1 #include <iostream>
  2 
  3 using namespace std;
  4 template <typename T>
  5 class Complex;
  6 
  7 template<typename T>
  8 ostream& operator<<(ostream& out, Complex<T>& complex);
  9 
 10 template <typename T>
 11 class Complex {
 12 public:
 13     Complex(T real = 0, T imag = 0);
 14     Complex(const Complex<T>& complex);
 15 
 16     T get_real() const;
 17     T get_imag() const;
 18 
 19     Complex<T>& operator+(const Complex<T>& complex);
 20     
 21     template<typename T1>
 22     friend bool operator==(const Complex<T1> c1, const Complex<T1> c2);
 23     template<typename T1>
 24     friend Complex<T1> operator+=(const Complex<T1>& c1, const Complex<T1>& c2);
 25     template<typename T1>
 26     friend istream& operator>>(istream &in, Complex<T1>& complex);
 27 
 28 private:
 29     T real, imag;
 30 };
 31 
 32 int main() {
 33 
 34     Complex<double> c1{ 2, 4 };
 35     Complex<double> c2;
 36     cin >> c2;
 37     cout << c2.get_real() << " " << c2.get_imag() << endl;
 38 
 39     cout << c1 << endl;
 40     cout << c2 << endl;
 41     cout << c1 + c2 << endl;
 42     c1 += c2;
 43     cout << c2 << endl;
 44     cout << boolalpha << (c1 == c2) << endl;
 45 }
 46 
 47 template<typename T>
 48 Complex<T> operator+=(const Complex<T>& c1, const Complex<T>& c2) {
 49     T real, imag;
 50     real = c1.get_real() + c2.get_real();
 51     imag = c1.get_imag() + c2.get_imag();
 52     return Complex<T>(real, imag);
 53 }
 54 
 55 template<typename T>
 56 bool operator==(const Complex<T> c1, const Complex<T> c2)
 57 {
 58     return c1.get_real() == c2.get_real() &&
 59         c1.get_imag() == c2.get_imag();
 60 }
 61 
 62 template<typename T>
 63 istream& operator>>(istream& in, Complex<T>& complex) {
 64     in >> complex.real >> complex.imag;
 65 
 66     return in;
 67 }
 68 
 69 template<typename T>
 70 Complex<T>::Complex(T real, T imag) : real(real), imag(imag) {
 71 
 72 }
 73 
 74 template<typename T>
 75 Complex<T>::Complex(const Complex<T>& complex) {
 76     imag = complex.imag;
 77     real = complex.real;
 78 }
 79 
 80 template<typename T>
 81 T Complex<T>::get_real() const {
 82     return real;
 83 }
 84 
 85 template<typename T>
 86 T Complex<T>::get_imag() const {
 87     return imag;
 88 }
 89 
 90 template<typename T>
 91 Complex<T>& Complex<T>::operator+(const Complex<T>& complex) {
 92     real += complex.real;
 93     imag += complex.imag;
 94     return *this;
 95 }
 96 
 97 
 98 
 99 template<typename T>
100 ostream& operator<<(ostream& out, Complex<T>& complex) {
101     out << "(" << complex.get_real() << "," << complex.get_imag() << ")";
102     return out;
103 }
View Code

 

不得不说,在这里栽跟头了,一开始纯手撸,然后各种报错。。。

很多书写格式不太清楚

 

实验2

Person.hpp

 1 #pragma once
 2 #include <iostream>
 3 #include <string>
 4 #include <iomanip>
 5 
 6 using namespace std;
 7 
 8 class Person
 9 {
10 public:
11     Person();
12     Person(string name, string telephone, string eamil = "NULL");
13     void set_phonenumber(string phone_number);
14     void set_email(string _email);
15     friend ostream& operator<<(ostream& out, const Person& person);
16     friend istream& operator>>(istream& in, Person& person);
17     friend bool operator==(const Person& p1, const Person& p2);
18 
19 private:
20     string name;
21     string telephone;
22     string email;
23 };
24 
25 Person::Person() {
26 
27 }
28 
29 Person::Person(string name, string telephone, string email) {
30     name = name;
31     telephone = telephone;
32     email = email;
33 }
34 void Person::set_phonenumber(string phone_number) {
35     telephone = phone_number;
36 }
37 
38 void Person::set_email(string _email) {
39     email = _email;
40 }
41 
42 ostream& operator<<(ostream& out, const Person& person) {
43     
44     out << std::left << setw(15) << person.name  << setw(15) << person.telephone << setw(20) << person.email << endl;
45     return out;
46 }
47 
48 istream& operator>>(istream& in, Person& person) {
49     string str;
50     getline(cin, str);
51     person.name = str;
52     cin >> person.telephone >> person.email;
53     return in;
54 }
55 
56 bool operator==(const Person& p1, const Person& p2) {
57     return p1.email == p2.email && p1.name == p2.name
58         && p1.telephone == p2.telephone;
59 }
View Code

 

Main.cpp

 1 #include "Person.h"
 2 #include <vector>
 3 #include <fstream>
 4 
 5 int main() {
 6 
 7     vector<Person> person_list;
 8 
 9     Person p;
10     while (cin >> p) {
11         person_list.push_back(p);
12         cin.clear();
13         cin.ignore();
14     }
15 
16     for (auto& i : person_list) {
17         cout << i << endl;
18     }
19 
20     cout << boolalpha << (person_list[0] == person_list[1]) << endl;
21 
22     ofstream outFile;
23     outFile.open("person.txt");
24 
25     if (!outFile.is_open()) {
26         cerr << "fail to open file person.txt" << endl;
27         return 1;
28     }
29 
30     for (auto& i : person_list) {
31         outFile << i << endl;
32     }
33     outFile.close();
34 }
View Code

 

运行截图展示如下

 

 

文件如下

 

除了多了个endl基本浮现了输出样例

 

实验3

Contianer.h

 1 #pragma once
 2 #include <iostream>
 3 
 4 class Container
 5 {
 6 protected:
 7     int healCount;
 8     int magicWaterCount;
 9 public:
10     Container();
11     void set(int _heal, int _mw);
12     int getHealCount();
13     int getMagicWaterCount();
14     void display();
15     bool useHeal();
16     bool useMW();
17 };
View Code

Container.cpp

 1 #include "Container.h"
 2 
 3 Container::Container() {
 4     magicWaterCount = 0;
 5     healCount = 0;
 6 }
 7 void Container::set(int _heal, int _mw) {
 8     healCount = _heal;
 9     magicWaterCount = _mw;
10 }
11 int Container::getHealCount() {
12     return healCount;
13 }
14 int Container::getMagicWaterCount() {
15     return magicWaterCount;
16 
17 }
18 void Container::display() {
19     std::cout << "Your bag contains: \n"
20         "Heal(HP+100): " << healCount << "\n"
21         "Magic Water (MP+80): " << magicWaterCount;
22 }
23 bool Container::useHeal() {
24     return healCount > 0 ? healCount-- : false;
25 }
26 
27 bool Container::useMW() {
28     return magicWaterCount > 0 ? magicWaterCount-- : false;
29 }
View Code

Player.h

 1 #pragma once
 2 #include "Container.h"
 3 #include <iomanip>
 4 #include <time.h>
 5 #include <string>
 6 using namespace std;
 7 
 8 enum job {SWORDMAN, ARCHER, MAGE};
 9 class Player
10 {
11     friend void showInfo(Player& p1, Player& p2);
12     friend class SwordMan;
13 
14 protected:
15     int HP, maxHP, MP, maxMP, AP, DP, speed, EXP, LV;
16     std::string name;
17     job role;
18     Container bag;
19 public:
20     virtual bool attack(Player& p) = 0;
21     virtual bool specialAttack(Player& p) = 0;
22     virtual void isLevelUp() = 0;
23 
24     void reFill();
25     bool death();
26     void isDead();
27     bool useHeal();
28     bool useMW();
29     void transfer(Player& p);
30     void showRole();
31 
32 private:
33     bool isDeath;
34 };
View Code

Player.cpp

#include "Player.h"

void Player::reFill() {
    HP = maxHP;
    MP = maxMP;
}
bool Player::death() {
    return isDeath;
}
void Player::isDead() {
    if (HP <= 0) {
        std::cout << name << "is dead." << std::endl;
        system("pause");
        isDeath = true;
    }
}
bool Player::useHeal() {
    if (bag.getHealCount()) {
        bag.useHeal();
        HP = HP + 100 > maxHP ? maxHP : HP + 100;
        std::cout << name << "use Heal, HP increased by 100." << std::endl;
        system("pause");
        return true;
    }
    std::cout << "Sorry, you don't have heal to use." << std::endl;
    system("pause");
    return false;
}
bool Player::useMW() {
    if (bag.getMagicWaterCount()) {
        bag.useMW();
        MP = MP + 100 > maxMP ? maxMP : MP + 100;
        std::cout << name << "use magic water, MP increased by 100." << std::endl;
        system("pause");
        return true;
    }
    std::cout << "Sorry, you don't have magic water to use." << std::endl;
    system("pause");
    return false;
}
void Player::transfer(Player& p) {
    int heal = p.bag.getHealCount();
    int magicWater = p.bag.getMagicWaterCount();
    std::cout << name << "got " << heal << "Heal, and " << magicWater << "Magic Water." << std::endl;
    system("pause");
    p.bag.set(bag.getHealCount() + heal, bag.getMagicWaterCount() + magicWater);
}
void Player::showRole() {
    switch (role)
    {
    case SWORDMAN:
        std::cout << "Swordsman";
        break;
    case ARCHER:
        std::cout << "Archer";
        break;
    case MAGE:
        std::cout << "Mage";
        break;
    default:
        break;
    }
}

void showInfo(Player& p1, Player& p2) {
    {
        using namespace std;
        system("cls");
        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.maxHP <= 999 ? p1.maxHP : 999)
            << " | MP " << setw(3) << (p1.MP <= 999 ? p1.MP : 999) << '/' << setw(3) << (p1.maxMP <= 999 ? p1.maxMP : 999)
            << "     # HP " << setw(3) << (p2.HP <= 999 ? p2.HP : 999) << '/' << setw(3) << (p2.maxHP <= 999 ? p2.maxHP : 999)
            << " | MP " << setw(3) << (p2.MP <= 999 ? p2.MP : 999) << '/' << setw(3) << (p2.maxMP <= 999 ? p2.maxMP : 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;
    }
}
View Code

SwordMan.h

#pragma once
#include "Player.h"
class SwordMan : public Player
{
public:
    SwordMan(int lv_in = 1, std::string name_in = "Not Given");
    void isLevelUp();
    bool attack(Player& p);
    bool specialAttack(Player& p);
    void AI(Player& p);
};
View Code

SwordMan.cpp

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

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 "SwordMan.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 = nullptr;        // 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 SwordMan(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         SwordMan 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->specialAttack(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                 enemy.transfer(*human);
101                 cout << "Please try again" << endl;// player is dead, program is getting to its end, what should we do here?
102                 system("pause");
103                 return 0;
104             }
105         }
106     }
107     delete human;            // 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 }
View Code

题外话:游戏结束当然的把humanfree掉了哈哈哈哈哈

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

从头到尾跑完应该问题不大

实验总结

实验1

构造函数的书写有些生疏了

1.3想自己试一试,但是苦于语法(甚至一开始想故意试试不按照前面1.2的经验会发生什么

emm报错更多了哈哈哈哈哈

实验2

ws还得研究一下,不过通过设计字段

如姓名最多20位?电话号码在国内最多14位(+86),可以用setw把空白预留下

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM