首页 > 其他分享 >实验五

实验五

时间:2023-12-02 17:45:44浏览次数:26  
标签:const string int double void 实验 date

任务一 publisher.hpp

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 using std::cout;
 7 using std::endl;
 8 using std::string;
 9 
10 // 发行/出版物类:Publisher (抽象类)
11 class Publisher {
12 public:
13     Publisher(const string &s = "");            // 构造函数
14 
15 public:
16     virtual void publish() = 0;                 // 纯虚函数,作为接口继承
17 
18 protected:
19     string name;    // 发行/出版物名称
20 };
21 
22 Publisher::Publisher(const string &s): name {s} {
23 }
24 
25 
26 // 图书类: Book
27 class Book: public Publisher {
28 public:
29     Book(const string &s = "", const string &a = "");  // 构造函数
30 
31 public:
32     void publish() override;        // 接口
33     void read();                    // 派生类新增接口
34 
35 private:
36     string author;          // 作者
37 };
38 
39 Book::Book(const string &s, const string &a): Publisher{s}, author{a} {
40 }
41 
42 void Book::publish() {
43     cout << "Publishing book: " << name << " by " << author << endl;
44 }
45 
46 void Book::read() {
47     cout << "Reading book: " << name << " by " << author << endl;
48 }
49 
50 
51 // 电影类: Film
52 class Film: public Publisher {
53 public:
54     Film(const string &s = "", const string &d = "");   // 构造函数
55 
56 public:
57     void publish() override;    // 接口
58     void watch();               // 派生类新增接口
59 
60 private:
61     string director;        // 导演
62 };
63 
64 Film::Film(const string &s, const string &d): Publisher{s}, director{s} {
65 }
66 
67 void Film::publish() {
68     cout << "Publishing film: " << name << " directed by " << director << endl;
69 }
70 
71 void Film::watch() {
72     cout << "Watching film: " << name << " directed by " << director << endl;
73 }
74 
75 
76 // 音乐类:Music
77 class Music: public Publisher {
78 public:
79     Music(const string &s = "", const string &a = "");
80 
81 public:
82     void publish() override;        // 接口
83     void listen();                  // 派生类新增接口
84 
85 private:
86     string artist;      // 音乐艺术家名称
87 };
88 
89 Music::Music(const string &s, const string &a): Publisher{s}, artist{a} {
90 }
91 
92 void Music::publish() {
93     cout << "Publishing music " << name << " by " << artist << endl;
94 }
95 
96 void Music::listen() {
97     cout << "Listening to music: " << name << " by " << artist << endl;
98 }
View Code task1.cpp
 1 #include "publisher.hpp"
 2 #include <vector>
 3 #include <typeinfo>
 4 
 5 using std::vector;
 6 
 7 void func(Publisher *ptr) {
 8     cout << "pointer type: " << typeid(ptr).name() << endl;
 9     cout << "RTTI type: " << typeid(*ptr).name() << endl;
10     
11     ptr->publish();
12 }
13 
14 void test() {
15     Publisher *ptr;
16 
17     cout << "测试1: \n";
18     Book book{"Harry Potter", "J.K. Rowling"};
19     ptr = &book;
20     func(ptr);
21     book.read();
22 
23     cout << "\n测试2: \n";
24     Film film{"The Godfather", "Francis Ford Coppola"};
25     ptr = &film;
26     func(ptr);
27     film.watch();
28 
29     cout << "\n测试3: \n";
30     Music music{"Blowing in the wind", "Bob Dylan"};
31     ptr = &music;
32     func(ptr);
33     music.listen();
34 }
35 
36 int main() {
37     test();
38 }
View Code

任务二

complex.hpp
 1 #pragma once
 2 
 3 #include <iostream>
 4 
 5 class Complex {
 6 public:
 7     Complex(double r = 0, double i = 0): real{r}, imag{i} {}
 8     Complex(const Complex &c): real{c.real}, imag{c.imag} {}
 9     ~Complex() = default;
10 
11 public:
12     double get_real() const { return real; }
13     double get_imag() const { return imag; }
14 
15     Complex& operator+=(const Complex &c);
16 
17     friend Complex operator+(const Complex &c1, const Complex &c2);
18     friend bool operator==(const Complex &c1, const Complex &c2);
19     
20     friend std::ostream& operator<<(std::ostream &os, const Complex &c);
21     friend std::istream& operator>>(std::istream &is, Complex &c);
22 
23 private:
24     double real, imag;
25 };
26 
27 //=====================成员函数=================
28 // 重载运算符+=为成员函数, 支持c1 += c2这样的操作
29 Complex& Complex::operator+=(const Complex &c) {
30     real += c.real;
31     imag += c.imag;
32 
33     return *this;
34 }
35 
36 // =====================普通函数=====================
37 // 重载运算符+为普通函数,支持c1 + c2这样的操作
38 Complex operator+(const Complex &c1, const Complex &c2) {
39     return Complex(c1.get_real() + c2.get_real(),
40                    c1.get_imag() + c2.get_imag());
41 }
42 
43 // 重载运算符==为普通函数,支持c1 == c2这样的操作
44 bool operator==(const Complex &c1, const Complex &c2) {
45     return (c1.get_real() == c2.get_real() && c1.get_imag() == c2.get_imag());
46 }
47 
48 // =====================友元函数=====================
49 // 重载插入运算符<<为友元函数,支持类似cout << c1 << c2这样的操作
50 std::ostream& operator<<(std::ostream &os, const Complex &c) {
51     if(c.imag >= 0)
52         os << c.real << " + " << c.imag << "i";
53     else
54         os << c.real << " - " << -c.imag << "i";
55 
56     return os;
57 } 
58 
59 // 重载提取运算符>>为友元函数,支持类似cin >> c1 >> c2这样的操作
60 std::istream& operator>>(std::istream &is, Complex &c) {
61     is >> c.real >> c.imag;
62 
63     return is;
64 }
View Code task2.cpp
 1 #include <iostream>
 2 #include "complex.hpp"
 3 
 4 void test() {
 5     using namespace std;
 6 
 7     Complex c1;
 8     cout << "Enter c1: ";
 9     cin >> c1;
10     cout << "c1 = " << c1 << endl;
11 
12     Complex c2{1.5}, c3{1.5, 3}, c4{c3};
13     cout << "c2 = " << c2 << endl;
14     cout << "c3 = " << c3 << endl;
15     cout << "c4 = " << c4 << endl;
16     cout << "c3 == c4: " << boolalpha << (c3 == c4) << endl;
17 
18     cout << "c1 + c2 = " << c1 + c2 << endl;
19     c1 += c2;
20     cout << "c1 = " << c1 << endl;
21     cout << c1.get_real() << " " << c1.get_imag() << endl;
22 }
23 
24 int main() {
25     test();
26 }
View Code

任务三

pets.hpp
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class MachinePets
 5 {
 6 private:
 7     string nickname;
 8 public:
 9     MachinePets(const string s) :nickname{ s } {}
10     string get_nickname() const { return nickname; }
11     virtual string talk() = 0;
12 };
13 class PetCats :public MachinePets
14 {
15 public:
16     PetCats(const string s) :MachinePets{ s } {}
17     string talk()
18     {
19         return "miao wu~";
20     }
21 
22 
23 };
24 class PetDogs:public MachinePets
25 {
26 public:
27     PetDogs(const string s) :MachinePets{ s } {}
28     string talk()
29     {
30         return "wang wang~";
31     }
32 
33 };
View Code task3.cpp
 1 #include <iostream>
 2 #include"machinepets.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 }
View Code

任务四

task4.cpp
 1 #include<iostream>
 2 #include<string>
 3 #include <iomanip>
 4 using namespace std;
 5 class Person
 6 {
 7 private:
 8     string name;
 9     string telephone;
10     string email;
11 public:
12     Person(string name, string telephone)
13     {
14         this->name = name;
15         this->telephone = telephone;
16     }
17     Person()
18     {
19         this->name = name; this->telephone = telephone; this->email = email;
20     }
21     Person(const Person &s);
22     void update_telephone()
23     {
24             cout << "输入电话号码:";
25             cout<< telephone;
26             cout << endl << "电话号码更新成功" << endl;
27     }
28     void update_email();
29     friend  std::ostream& operator<<(std::ostream& out, const Person& t)
30     {
31             out << "name:" << t.name << endl;
32             out << "telephone:" << t.telephone << endl;
33             out << "email:" << t.email << endl;
34             return out;    
35     }
36     friend std::istream& operator>>(std::istream& in,  Person& t)
37     {
38         in >> t.name >> t.telephone >> t.email;
39         cout << endl;
40         return in;
41     }
42     friend bool operator==(const Person& s1, const Person& s2)
43     {
44         if (s1.name == s2.name && s1.telephone == s2.telephone && s1.email == s2.email)
45             return 1;
46         else
47             return 0;
48     }
49 };
50 Person::Person(const Person &s)
51 {
52     name = s.name; telephone =s.telephone; email = s.email;
53 }
View Code Person.hpp
 1 #include <iostream>
 2 #include <vector>
 3 #include "Person.hpp"
 4 
 5 void test() {
 6     using namespace std;
 7 
 8     vector<Person> phone_book;
 9     Person p;
10 
11     cout << "输入一组联系人的联系方式,E直至按下Ctrl+Z终止\n";
12     while(cin >> p) 
13         phone_book.push_back(p);
14     
15     cout << "\n更新phone_book中索引为0的联系人的手机号、邮箱:\n";
16     phone_book.at(0).update_telephone();
17     phone_book.at(0).update_email();
18 
19     cout << "\n测试两个联系人是否是同一个:\n";
20     cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl;
21 }
22 
23 int main() {
24     test();
25 }
View Code

任务五

date.h

 1 class Date
 2 {
 3 private:
 4     int year;
 5     int month;
 6     int day;
 7     int totalDays;
 8 public:
 9     Date(int year, int month, int day);
10     int getYear() const { return year; }
11     int getMonth() const { return month; }
12     int getDay() const { return day; }
13     int getMaxDay() const;
14     bool isLeapYear() const
15     {
16         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
17     }
18     void show() const;
19     int operator-(const Date& date) const
20     {
21         return totalDays - date.totalDays;
22     }
23 };
View Code

account.h

 1 #include"date.h"
 2 #include"accumulator.h"
 3 #include<string>
 4 class Account
 5 {
 6 private:
 7     std::string id;
 8     double balance;
 9     static double total;
10 protected:
11     Account(const Date& date, const std::string& id);
12     void record(const Date& date, double amount, const std::string& desc);
13     void error(const std::string& msg) const;
14 public:
15     const std::string& getId() const { return id; }
16     double getBalance() const { return balance; }
17     static double getToal() { return total; }
18     virtual void deposit(const Date& date, double amount, const std::string& desc) = 0;
19     virtual void withdraw(const Date& date, double amount, const std::string& desc) = 0;
20     virtual void settle(const Date& date);
21     virtual void show() const;
22 };
23 class SavingsAccount :public Account
24 {
25 private:
26     Accumulator acc;
27     double rate;
28 public:
29     SavingsAccount(const Date& date, const std::string& id, double rate);
30     double getRate() const { return rate; }
31     void deposit(const Date& date, double amount, const std::string& desc);
32     void withdraw(const Date& date, double amount, const std::string& desc);
33     void settle(const Date& date);
34 };
35 class CreditAccount :public Account
36 {
37 private:
38     Accumulator acc;
39     double credit;
40     double rate;
41     double fee;
42     double getDebt() const
43     {
44         double balance = getBalance();
45         return(balance < 0 ? balance : 0);
46     }
47 public:
48     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
49     double getCredit() const { return credit; }
50     double getRate() const { return rate; }
51     double getFee() const { return fee; }
52     double getAvailableCredit() const {
53         if (getBalance() < 0)
54             return credit + getBalance();
55         else
56             return credit;
57     }
58     void deposit(const Date& date, double amount, const std::string& desc);
59     void withdraw(const Date& date, double amount, const std::string& desc);
60     void settle(const Date& date);
61     void show() const;
62 };
View Code

accumulator.h

 1 #include"date.h"
 2 class Accumulator
 3 {
 4 private:
 5     Date lastDate;
 6     double value;
 7     double sum;
 8 public:
 9     Accumulator(const Date& date, double value) :lastDate(date), value(value), sum(0) {}
10     double getSum(const Date& date) const
11     {
12         return sum + value * (date - lastDate);
13     }
14     void change(const Date& date, double value)
15     {
16         sum = getSum(date);
17         lastDate = date; this->value = value; sum = 0;
18     }
19     void reset(const Date& date, double value)
20     {
21         lastDate = date; this->value = value;
22     }
23 };
View Code

date.cpp

 1 #include"date.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 using namespace std;
 5 namespace
 6 {
 7     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
 8 }
 9 Date::Date(int year, int month, int day) :year(year), month(month), day(day)
10 {
11     if (day <= 0 || day > getMaxDay())
12     {
13         cout << "INvalid date:";
14         show();
15         cout << endl;
16         exit(1);
17     }
18     int years = year - 1;
19     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
20     if (isLeapYear() && month > 2) totalDays++;
21 }
22 int Date::getMaxDay() const
23 {
24     if (isLeapYear() && month == 2)
25         return 29;
26     else
27         return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
28 }
29 void Date::show() const
30 {
31     cout << getYear() << "-" << getMonth() << "-" << getDay();
32 }
View Code

account.cpp

 1 #include"account.h"
 2 #include<cmath>
 3 #include<iostream>
 4 using namespace std;
 5 double Account::total = 0;
 6 Account::Account(const Date& date, const std::string& id) :id(id), balance(0)
 7 {
 8     date.show(); cout << "\t#" << id << "created" << endl;
 9 }
10 void Account::record(const Date& date, double amount, const string& desc)
11 {
12     amount = floor(amount * 100 + 0.5) / 100;
13     balance += amount; total += amount;
14     date.show();
15     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
16 }
17 void Account::show() const { cout << id << "\tBalance:" << balance; }
18 void Account::error(const string& msg) const
19 {
20     cout << "Error(#" << id << "):" << msg << endl;
21 }
22 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {
23 }
24 void SavingsAccount::deposit(const Date& date, double amount, const string& desc)
25 {
26     record(date, amount, desc);
27     acc.change(date, getBalance());
28 }
29 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc)
30 {
31     if (amount > getBalance())
32     {
33         error("not enough money");
34     }
35     else
36     {
37         record(date, -amount, desc);
38         acc.change(date, getBalance());
39     }
40 }
41 void SavingsAccount::settle(const Date& date)
42 {
43     if (date.getMonth() == 1)
44     {
45         double interest = acc.getSum(date) * rate / (date - Date(date.getYear() - 1, 1, 1));
46         if (interest != 0) record(date, interest, "interest");
47         acc.reset(date, getBalance());
48     }
49 }
50 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) :Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {
51 }
52 void CreditAccount::deposit(const Date& date, double amount, const string& desc)
53 {
54     record(date, amount, desc);
55     acc.change(date, getDebt());
56 }
57 void CreditAccount::withdraw(const Date& date, double amount, const string& desc)
58 {
59     if (amount - getBalance() > credit)
60     {
61         error("not enough credit");
62     }
63     else
64     {
65         record(date, -amount, desc);
66         acc.change(date, getDebt());
67     }
68 }
69 void CreditAccount::settle(const Date& date)
70 {
71     double interest = acc.getSum(date) * rate;
72     if (interest != 0) record(date, interest, "interest");
73     if (date.getMonth() == 1) record(date, -fee, "annual fee");
74     acc.reset(date, getDebt());
75 }
76 void CreditAccount::show() const
77 {
78     Account::show();
79     cout << "\tAvailable credit:" << getAvailableCredit();
80 }
View Code

8.8.cpp

 1 #include"account.h"
 2 #include<iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     Date date(2008, 11, 1);
 7     SavingsAccount sa1(date, "s3755217", 0.015);
 8     SavingsAccount sa2(date, "02342342", 0.015);
 9     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
10     Account* accounts[] = { &sa1,&sa2,&ca };
11     const int n = sizeof(accounts) / sizeof(Account*);
12     cout << "(d)deposit(w)withdraw(s)show(c)change day(n) next month(e) exit" << endl;
13     char cmd;
14     do {
15         date.show();
16         cout << "\tTotal:" << Account::getToal() << "\tcommand";
17         int index, day;
18         double amount; string desc;
19         cin >> cmd;
20         switch (cmd)
21         {
22         case'd':
23             cin >> index >> amount;
24             getline(cin, desc);
25             accounts[index]->deposit(date, amount, desc);
26             break;
27         case'w':
28             cin >> index >> amount;
29             getline(cin, desc);
30             accounts[index]->withdraw(date, amount, desc);
31             break;
32         case's':
33             for (int i = 0; i < n; i++)
34             {
35                 cout << "[" << i << "]";
36                 accounts[i]->show();
37                 cout << endl;
38             }
39             break;
40         case'c':
41             cin >> day;
42             if (day << date.getDay())
43                 cout << "You cannot specify a previous day";
44             else if (day > date.getMaxDay())
45                 cout << "Invalid day";
46             else
47                 date = Date(date.getYear(), date.getMonth(), day);
48             break;
49         case'n':
50             if (date.getMonth() == 12)
51                 date = Date(date.getYear() + 1, 1, 1);
52             else
53                 date = Date(date.getYear(), date.getMonth() + 1, 1);
54             for (int i = 0; i < n; i++)
55                 accounts[i]->settle(date);
56             break;
57         }
58     } while (cmd != 'e');
59     return 0;
60 }
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 
15 enum job
16 {
17     sw,//jianke
18     ar,//gongjian
19     mg//fashi
20 }; /* define 3 jobs by enumerate type
21           sword man, archer, mage */
22 class player
23 {
24     friend void showinfo(player &p1, player &p2);
25     friend class swordsman;
26 
27 protected:
28     int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV;
29     // General properties of all characters
30     string name;   // character name
31     job role;       /* character's job, one of swordman, archer and mage,
32                       as defined by the enumerate type */
33     container bag; // character's inventory
34 
35 public:
36     virtual bool attack(player &p) = 0;        // normal attack
37     virtual bool specialatt(player &p) = 0; // special attack
38     virtual void isLevelUp() = 0;            // level up judgement
39     /* Attention!
40     These three methods are called "Pure virtual functions".
41     They have only declaration, but no definition.
42     The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects.
43     The detailed definition of these pure virtual functions will be given in subclasses. */
44 
45     void reFill();              // character's HP and MP resume
46     bool death();              // report whether character is dead
47     void isDead();              // check whether character is dead
48     bool useHeal();              // consume heal, irrelevant to job
49     bool useMW();              // consume magic water, irrelevant to job
50     void transfer(player &p); // possess opponent's items after victory
51     void showRole();          // display character's job
52 
53 private:
54     bool playerdeath; // whether character is dead, doesn't need to be accessed or inherited
55 };
56 
57 #endif
View Code player.cpp
  1 //=======================
  2 //        player.cpp
  3 //=======================
  4 #include<player.h>
  5 // character's HP and MP resume
  6 void player::reFill()
  7 {
  8     HP = HPmax; // HP and MP fully recovered
  9     MP = MPmax;
 10 }
 11 
 12 // report whether character is dead
 13 bool player::death()
 14 {
 15     return playerdeath;
 16 }
 17 
 18 // check whether character is dead
 19 void player::isDead()
 20 {
 21     if (HP <= 0) // HP less than 0, character is dead
 22     {
 23         cout << name << " is Dead." << endl;
 24         system("pause");
 25         playerdeath = 1; // give the label of death value 1
 26     }
 27 }
 28 
 29 // consume heal, irrelevant to job
 30 bool player::useHeal()
 31 {
 32     if (bag.nOfHeal() > 0)
 33     {
 34         HP = HP + 100;
 35         if (HP > HPmax) // HP cannot be larger than maximum value
 36             HP = HPmax; // so assign it to HPmax, if necessary
 37         cout << name << " used Heal, HP increased by 100." << endl;
 38         bag.useHeal(); // use heal
 39         system("pause");
 40         return 1; // usage of heal succeed
 41     }
 42     else // If no more heal in bag, cannot use
 43     {
 44         cout << "Sorry, you don't have heal to use." << endl;
 45         system("pause");
 46         return 0; // usage of heal failed
 47     }
 48 }
 49 
 50 // consume magic water, irrelevant to job
 51 bool player::useMW()
 52 {
 53     if (bag.nOfMW() > 0)
 54     {
 55         MP = MP + 100;
 56         if (MP > MPmax)
 57             MP = MPmax;
 58         cout << name << " used Magic Water, MP increased by 100." << endl;
 59         bag.useMW();
 60         system("pause");
 61         return 1; // usage of magic water succeed
 62     }
 63     else
 64     {
 65         cout << "Sorry, you don't have magic water to use." << endl;
 66         system("pause");
 67         return 0; // usage of magic water failed
 68     }
 69 }
 70 
 71 // possess opponent's items after victory
 72 void player::transfer(player &p)
 73 {
 74     cout << name << " got" << p.bag.nOfHeal() << " Heal, and " << p.bag.nOfMW() << " Magic Water." << endl;
 75     system("pause");
 76     // set the character's bag, get opponent's items
 77     //3_ ? ? ? ? ? ? ? ? ? ? ?
 78     bag.set(bag.nOfHeal()+p.bag.nOfHeal(),bag.nOfMW()+p.bag.nOfMW());
 79     
 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 // display character's job
102 void showinfo(player &p1, player &p2)//4_ ? ? ? ? ? ? ? ? ? ? ? ? ? ?
103 {
104     system("cls");
105     cout << "##############################################################" << endl;
106     cout << "# Player" << setw(10) << p1.name << "   LV. " << setw(3) << p1.LV
107          << "  # Opponent" << setw(10) << p2.name << "   LV. " << setw(3) << p2.LV << " #" << endl;
108     cout << "# HP " << setw(3) << (p1.HP <= 999 ? p1.HP : 999) << '/' << setw(3) << (p1.HPmax <= 999 ? p1.HPmax : 999)
109          << " | MP " << setw(3) << (p1.MP <= 999 ? p1.MP : 999) << '/' << setw(3) << (p1.MPmax <= 999 ? p1.MPmax : 999)
110          << "     # HP " << setw(3) << (p2.HP <= 999 ? p2.HP : 999) << '/' << setw(3) << (p2.HPmax <= 999 ? p2.HPmax : 999)
111          << " | MP " << setw(3) << (p2.MP <= 999 ? p2.MP : 999) << '/' << setw(3) << (p2.MPmax <= 999 ? p2.MPmax : 999) << "      #" << endl;
112     cout << "# AP " << setw(3) << (p1.AP <= 999 ? p1.AP : 999)
113          << " | DP " << setw(3) << (p1.DP <= 999 ? p1.DP : 999)
114          << " | speed " << setw(3) << (p1.speed <= 999 ? p1.speed : 999)
115          << " # AP " << setw(3) << (p2.AP <= 999 ? p2.AP : 999)
116          << " | DP " << setw(3) << (p2.DP <= 999 ? p2.DP : 999)
117          << " | speed " << setw(3) << (p2.speed <= 999 ? p2.speed : 999) << "  #" << endl;
118     cout << "# EXP" << setw(7) << p1.EXP << " Job: " << setw(7);
119     p1.showRole();
120     cout << "   # EXP" << setw(7) << p2.EXP << " Job: " << setw(7);
121     p2.showRole();
122     cout << "    #" << endl;
123     cout << "--------------------------------------------------------------" << endl;
124     p1.bag.display();
125     cout << "##############################################################" << endl;
126 }
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 class swordsman :public player// 5_ ? ? ? ? ? ? ? ? ? // 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 };
View Code swordsman.cpp
  1 //=======================
  2 //        swordsman.cpp
  3 //=======================
  4 
  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 }
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//1_ ? ? ? ? ? ? ? ? ? ? ? ? ? // 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
View Code container.cpp
 1 //=======================
 2 //        container.cpp
 3 //=======================
 4 
 5 // default constructor initialise the inventory as empty
 6 container::container()
 7 {
 8     set(0, 0);
 9 }
10 
11 // set the item numbers
12 void container::set(int heal_n, int mw_n)
13 {
14     numOfHeal = heal_n;
15     numOfMW = mw_n;
16 }
17 
18 // get the number of heal
19 int container::nOfHeal()
20 {
21     return numOfHeal;
22 }
23 
24 // get the number of magic water
25 int container::nOfMW()
26 {
27     return numOfMW;
28 }
29 
30 // display the items;
31 void container::display()
32 {
33     cout << "Your bag contains: " << endl;
34     cout << "Heal(HP+100): " << numOfHeal << endl;
35     cout << "Magic Water (MP+80): " << numOfMW << endl;
36 }
37 
38 // use heal
39 bool container::useHeal()
40 {
41     numOfHeal--;//2_ ? ? ? ? ? ? ? ? 
42     return 1; // use heal successfully
43 }
44 
45 // use magic water
46 bool container::useMW()
47 {
48     numOfMW--;
49     return 1; // use magic water successfully
50 }
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 "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
 99                      << setw(50) << "GAME OVER" << endl;
100                 human->death();//6_ ? ? ? ? ? ? ? ? ? ? ? // player is dead, program is getting to its end, what should we do here?
101                 system("pause");
102                 return 0;
103             }
104         }
105     }
106     human->isLevelUp();//7_ ? ? ? ? ? ? ? ? ? // 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

 

 

标签:const,string,int,double,void,实验,date
From: https://www.cnblogs.com/dmsx/p/17871914.html

相关文章

  • .Net实验一 语言基础
    一、实验目的熟悉VisualStido.NET实验环境;掌握控制台程序的编写方法;掌握C#程序设计语言的语法基础;掌握控制语句和数组的使用。二、实验要求根据题目要求,编写C#程序,并将程序代码和运行结果写入实验报告。三、实验内容编写一个控制台应用程序,输入三角形或者长方形边长,计......
  • 软件设计实验 24:模板方法模式
      实验24:模板方法模式本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:1、理解模板方法模式的动机,掌握该模式的结构;2、能够利用模板方法模式解决实际问题。 [实验任务一]:数据库连接对数据库的操作一般包括连接、打开、使用、关闭等步骤,在数据库操作模板类中我......
  • 第五次实验
    任务1-1//验证性实验:指针变量作为函数参数,指针变量作为函数的返回值#include<stdio.h>#defineN5voidinput(intx[],intn);voidoutput(intx[],intn);voidfind_min_max(intx[],intn,int*pmin,int*pamx);intmain(){ inta[N]; intmin,max; printf("录入%d......
  • 实验5 继承和多态
    实验任务3pets.hpp源码1#include<iostream>2usingstd::string;3classMachinePets{4private:5stringnickname;6public:7MachinePets(conststrings);8stringget_nickname()const;9virtualstrin......
  • 实验5
    #programonce#include<iostream>#include<string>usingnamespacestd;classTextCoder{private:stringtext;voidencoder();#include"textcoder.hpp"#include<iostream>#include<string>voidtest(){us......
  • 实验四-现代C++标准库与类模板
    1#include<iostream>23usingstd::cout;4usingstd::endl;56classA{7public:8A(intx0,inty0):x{x0},y{y0}{}9voidshow()const{cout<<x<<","<<y<<endl;}10private:11......
  • 实验4
    实验任务5#include<iostream>#include<string>usingnamespacestd;classTextCoder{public:TextCoder()=default;TextCoder(stringstr);stringget_ciphertext();stringget_deciphertext();~TextCoder()=default;private:......
  • 实验四
    #programonce#include<iostream>#include<string>usingnamespacestd;classTextCoder{private:stringtext;voidencoder();voiddecoder();public:TextCoder(string&str);stringget_ciphertext();stringget_dec......
  • 实验四 现代C++标准库类与模板
    实验任务1task1.cpp源码task1_1.cpp:#include<iostream>usingstd::cout;usingstd::endl;//类A的定义classA{public:A(intx0,inty0):x{x0},y{y0}{}voidshow()const{cout<<x<<","<<y<<endl;}......
  • 实验4 现代C++标准库与类模板
    实验任务5textcoder.hpp#programonce#include<iostream>#include<string>usingnamespacestd;classTextCoder{private:stringtext;voidencoder();voiddecoder();public:TextCoder(string&str);stringget_ciphertext(......