实验5
1 #pragma once 2 #include<iostream> 3 using namespace std; 4 class MachinePets { 5 private: 6 string nickname; 7 public: 8 MachinePets(const string& s) :nickname(s) {} 9 virtual string talk() const = 0; 10 string get_nickname() const { return nickname; } 11 12 }; 13 class PetCats :public MachinePets { 14 public: 15 PetCats(const string & s):MachinePets(s){}; 16 string talk()const override { 17 return "miao wu~\n"; 18 }; 19 20 }; 21 class PetDogs :public MachinePets { 22 public: 23 PetDogs(const string & s); 24 string talk()const override; 25 26 }; 27 PetDogs::PetDogs(const string & s) :MachinePets{ s } {} 28 string PetDogs::talk()const { 29 return "wang wang~\n"; 30 31 } 32 33 34
1 #include <iostream> 2 #include<vector> 3 #include "pets.hpp" 4 5 void test() { 6 using namespace std; 7 8 vector<MachinePets*>pets; 9 pets.push_back(new PetCats("miku")); 10 pets.push_back(new PetDogs("da huang")); 11 12 for (auto& ptr : pets) { 13 cout << ptr->get_nickname() << " says " << ptr->talk() << endl; 14 } 15 } 16 17 int main() { 18 test(); 19 system("pause"); 20 }
1 #pragma once 2 #include<iostream> 3 #include<iomanip> 4 #include<string> 5 using namespace std; 6 7 class Film { 8 private: 9 string title; 10 string director; 11 string country; 12 int year; 13 public: 14 Film():title(""),director(""),country(""),year(0) {}; 15 Film(const string& t, const string& d, const string& c, const int& y) : 16 title(t), director(d), country(c), year(y) { 17 }; 18 friend istream& operator>>(istream& in, Film& film); 19 friend ostream& operator<<(ostream& out, Film& film); 20 int get_year()const; 21 22 }; 23 24 istream& operator>>(istream& in, Film& film) { 25 cout << "录入片名:" << endl; 26 in >> film.title; 27 cout << "录入导演:" << endl; 28 in >> film.director; 29 cout << "录入制片国家/地区:" << endl; 30 in >> film.country; 31 cout << "录入年份:" << endl; 32 in >> film.year; 33 return in; 34 } 35 36 ostream& operator<<(ostream& out, Film& film) { 37 out << std::left; 38 out << setw(15) << film.title 39 << setw(15) << film.director 40 << setw(15) << film.country 41 << setw(15) << film.year << endl; 42 return out; 43 } 44 45 int Film::get_year()const { return year; } 46 47 bool compare_by_year(const Film& a, const Film& b) { 48 return a.get_year()< b.get_year(); 49 }
1 #include"film.hpp" 2 #include<iostream> 3 #include<string> 4 #include<vector> 5 #include<algorithm> 6 7 void test() { 8 using namespace std; 9 10 int n; 11 cout << "输入电影数目:"; 12 cin >> n; 13 14 cout << "录入" << n << "部影片信息" << endl; 15 vector<Film> film_lst; 16 for (int i = 0; i < n; i++) { 17 Film f; 18 cout << string(20, '-') << "第" << i + 1 << "部影片录入" << string(20, '-') << endl; 19 cin >> f; 20 film_lst.push_back(f); 21 } 22 23 //按发行年份升序排序 24 sort(film_lst.begin(), film_lst.end(), compare_by_year); 25 26 cout << string(20, '=') + "电影信息(按发行年份)" + string(20, '=') << endl; 27 for (auto& f : film_lst) 28 cout << f << endl; 29 } 30 31 int main() { 32 test(); 33 }
1 #pragma once 2 #include<iostream> 3 using namespace std; 4 5 template <typename T> 6 class Complex 7 { 8 private: 9 T real; 10 T imag; 11 public: 12 Complex(T shi =0, T xu =0 ); 13 Complex(const Complex& c); 14 15 T get_real(); 16 T get_imag(); 17 18 friend istream& operator>>(istream& in, Complex& c) 19 { 20 in >> c.real >> c.imag; 21 return in; 22 } 23 friend ostream& operator<<(ostream& out, const Complex& c) 24 { 25 if (c.imag >0 ) 26 { 27 out << c.real << " + " << c.imag << "i"; 28 return out; 29 } 30 else 31 { 32 out << c.real << " - " << -c.imag << "i"; 33 return out; 34 } 35 } 36 37 Complex& operator+=(const Complex& c) 38 { 39 real += c.real; 40 imag += c.imag; 41 return *this; 42 43 } 44 45 Complex operator+(const Complex& c) 46 { 47 return Complex(real + c.real, imag + c.imag); 48 } 49 50 bool operator==(const Complex& c) 51 { 52 if (real == c.real) 53 { 54 return true; 55 } 56 else 57 { 58 return false; 59 } 60 } 61 62 }; 63 64 template <typename T> 65 Complex<T>::Complex(T shi, T xu) :real(shi), imag(xu) {} 66 67 template <typename T> 68 Complex<T>::Complex(const Complex& c) 69 { 70 real = c.real; 71 imag = c.imag; 72 } 73 74 template <typename T> 75 T Complex<T>::get_real() 76 { 77 return real; 78 } 79 80 template <typename T> 81 T Complex<T>::get_imag() 82 { 83 return imag; 84 }
1 #include "Complex.hpp" 2 #include <iostream> 3 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::boolalpha; 8 9 void test1() { 10 Complex<int> c1(2, -5), c2(c1); 11 12 cout << "c1 = " << c1 << endl; 13 cout << "c2 = " << c2 << endl; 14 cout << "c1 + c2 = " << c1 + c2 << endl; 15 16 c1 += c2; 17 cout << "c1 = " << c1 << endl; 18 cout << boolalpha << (c1 == c2) << endl; 19 } 20 21 void test2() { 22 Complex<double> c1, c2; 23 cout << "Enter c1 and c2: "; 24 cin >> c1 >> c2; 25 cout << "c1 = " << c1 << endl; 26 cout << "c2 = " << c2 << endl; 27 28 cout << "c1.real = " << c1.get_real() << endl; 29 cout << "c1.imag = " << c1.get_imag() << endl; 30 } 31 32 int main() { 33 cout << "自定义类模板Complex测试1: " << endl; 34 test1(); 35 36 cout << endl; 37 38 cout << "自定义类模板Complex测试2: " << endl; 39 test2(); 40 system("pause"); 41 }
1 #include<iostream> 2 #include"account.h" 3 #include<cmath> 4 //Account类的实现 5 Account::Account(const Date& date, const string& id) :id(id), balance(0) { 6 date.show(); 7 cout << "\t#" << id << "created" << endl; 8 } 9 10 void Account::record(const Date& date, double amount, const string& desc) { 11 amount = floor(amount * 100 + 0.5) / 100;//保留小数点后两位 12 balance += amount; 13 total += amount; 14 date.show(); 15 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 16 } 17 void Account::show()const { 18 cout << id << "\tBalance:" << balance; 19 } 20 void Account::error(const string &msg)const { 21 cout << "Error(#" << id << "):" << msg << endl; 22 } 23 //SavingsAccount类相关成员函数的实现: 24 SavingsAccount::SavingsAccount(const Date&date,const string &id,double rate):Account(date,id),rate(rate),acc(date,0){} 25 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 26 record(date, amount, desc); 27 acc.change(date, getBalance()); 28 } 29 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 30 if (amount > getBalance()) { 31 error("not enough money"); 32 } 33 else { 34 record(date, -amount, desc); 35 acc.change(date, getBalance()); 36 } 37 } 38 void SavingsAccount::settle(const Date& date) { 39 if (date.getMonth() == 1) {//每年的1月计算一次利息 40 double interest = acc.getSum(date) * rate / (date - Date(date.getYear() - 1, 1, 1)); 41 if (interest != 0) 42 record(date, interest, "interest"); 43 acc.reset(date, getBalance()); 44 } 45 } 46 //CreditAccount类相关成员函数的实现 47 CreditAccount::CreditAccount(const Date &date,const string &id,double credit,double rate,double fee): 48 Account(date,id),credit(credit),rate(rate),fee(fee),acc(date,0){ } 49 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 50 record(date, amount, desc); 51 acc.change(date, getDebt()); 52 } 53 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { 54 if (amount - getBalance() > credit) 55 error("not enough credit"); 56 else { 57 record(date, -amount, desc); 58 acc.change(date, getDebt()); 59 } 60 } 61 62 void CreditAccount::settle(const Date& date) { 63 double interest = acc.getSum(date) * rate; 64 if (interest != 0)record(date, interest, "interest"); 65 if (date.getMonth() == 1) 66 record(date, -fee, "annual fee"); 67 acc.reset(date, getDebt()); 68 } 69 70 void CreditAccount::show()const{ 71 Account::show(); 72 cout << "\tAvailable credit:" <<getAvailableCredit(); 73 74 }
1 #pragma once 2 #include"date.h" 3 #include"accumulator.h" 4 #include<string> 5 using namespace std; 6 7 class Account { 8 private: 9 string id; 10 double balance; 11 static double total; 12 protected: 13 //供派生类调用的构造函数,id为账户 14 Account(const Date& date, const string& id); 15 //记录一笔账,date为日期,amount为金额,desc为说明 16 void record(const Date& date, double amount, const string& desc); 17 //报告错误信息 18 void error(const string& msg)const; 19 public: 20 const string& getId()const { return id; } 21 double getBalance()const { return balance; } 22 static double getTotal() { return total; } 23 //存入现金,date为日期,amount为金额,desc为款项说明 24 virtual void deposit(const Date& date, double amount, const string& desc) = 0; 25 //取出现金,date为日期,amount为金额,desc为款项说明 26 virtual void withdraw(const Date& date, double amount, const string& desc) = 0; 27 //结算(计算利息,年费等),每月接算一次,date为结算日期 28 virtual void settle(const Date& date) = 0; 29 //显示账户信息 30 virtual void show() const; 31 }; 32 33 class SavingsAccount :public Account { 34 private: 35 Accumulator acc; 36 double rate; 37 public: 38 //构造函数 39 SavingsAccount(const Date& date, const string& id, double rate); 40 double getRate()const { return rate; } 41 //存入现金 42 void deposit(const Date& date, double amount, const string& desc); 43 //取出现金 44 void withdraw(const Date& date, double amount, const string& desc); 45 void settle(const Date& date);//结算利息,每年1月1日调用一次该函数 46 }; 47 class CreditAccount :public Account {//信用账户类 48 private: 49 Accumulator acc;//辅助计算利息的累加器 50 double credit;//信用额度 51 double rate;//欠款的日利率 52 double fee;//信用卡年费 53 double getDebt() const{ 54 double balance = getBalance(); 55 return(balance < 0 ? balance : 0); 56 } 57 public: 58 //构造函数 59 CreditAccount(const Date& date, const string& id, double credit, double rate, double fee); 60 double getCredit()const {return credit;} 61 double getRate()const { return rate; } 62 double getFee()const { return fee; } 63 double getAvailableCredit()const {//获得可用信用 64 if (getBalance() < 0) 65 return credit + getBalance(); 66 else 67 return credit; 68 } 69 //存入现金 70 void deposit(const Date& date, double amount, const string& desc); 71 //取出现金 72 void withdraw(const Date& date, double amount, const std::string& desc); 73 void settle(const Date& date);//计算利息和年费,每月1日调用一次该函数 74 void show()const; 75 };
1 #pragma once 2 #include"date.h" 3 class Accumulator { 4 private: 5 Date lastDate;//上次变更数值的时期 6 double value;//数值的当前值 7 double sum;//数值按日累加之和 8 public: 9 //构造函数,date为累加开始的日期,value为初始值 10 Accumulator(const Date& date, double value) : 11 lastDate(date), value(value), sum(0) { 12 } 13 double getSum(const Date& date)const { 14 return sum + value * (date - lastDate); 15 } 16 17 void change(const Date& date, double value) { 18 sum = getSum(date); 19 lastDate = date; this->value = value; 20 } 21 //初始化,将日期变为date,数值变为value,累加器清零 22 void reset(const Date& date, double value) { 23 lastDate = date; 24 this->value = value; 25 sum = 0; 26 } 27 };
1 #include"date.h" 2 #include<iostream> 3 #include<cstdlib> 4 using namespace std; 5 namespace { 6 const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 }; 7 } 8 Date::Date(int year, int month, int day) :year(year), month(month), day(day) { 9 if (day <= 0 || day > getMaxDay()) { 10 cout << "Invalid date:"; 11 show(); 12 cout << endl; 13 exit(1); 14 } 15 int years = year - 1; 16 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day; 17 if (isLeapYear() && month > 2)totalDays++; 18 } 19 int Date::getMaxDay()const { 20 if (isLeapYear() && month == 2) 21 return 29; 22 else 23 return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1]; 24 } 25 void Date::show()const { 26 cout << getYear() << "-" << getMonth() << "-" << getDay(); 27 }
1 #pragma once 2 class Date {//日期类 3 private: 4 int year; 5 int month; 6 int day; 7 int totalDays;//该日期是从公元元年1月1日开始的第几天 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 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 16 } 17 void show()const;//输出当前日期 18 //计算两个日期之间差多少天 19 int operator-(const Date& date)const { 20 return totalDays - date.totalDays; 21 } 22 };
1 #include"account.h" 2 #include<iostream> 3 #include<string> 4 using namespace std; 5 int main() { 6 Date date(2008, 1, 1);//起始日期 7 //建立几个账户 8 SavingsAccount sa1(date, "s3755217", 0.015); 9 SavingsAccount sa2(date, "02342342", 0.015); 10 CreditAccount sa3(date, "C5392394", 10000,0.0005,50); 11 Account* accounts[] = { &sa1,&sa2,&ca }; 12 const int n = sizeof(accounts) / sizeof(Account*);//账户总数 13 cout << "(d)deposit(w)withdraw(s)show(c)change day(n)next month(e)exit" << endl; 14 char cmd; 15 do { 16 //显示日期和总金额 17 date.show(); 18 cout << "\tTotal:" << Account::getTotal() << "\tcommand>"; 19 int index, day; 20 double amount; 21 string sec; 22 cin >> cmd; 23 switch (cmd) { 24 case'd'://存入现金 25 cin >> index >> amount; 26 getline(cin, desc); 27 accounts[index]->deposit(date, amount, desc); 28 break; 29 case'w'://取出现金 30 cin >> index >> amount; 31 getline(cin, desc); 32 accounts[index]->withdraw(date, amount, desc); 33 break; 34 case's'://查询各账户信息 35 for (int i = 0; i < n; i++) { 36 cout << "[" << i << "]"; 37 accounts[i]->show(); 38 cout << endl; 39 } 40 break; 41 case'c'://改变日期 42 cin >> day; 43 if (day < date.getDay()) 44 cout << "You cannot specify a previous day"; 45 else if (day > date.getMaxDay()) 46 cout << "Invalid day"; 47 else 48 date = Date(date.getYear(), date.getMonth(), day); 49 break; 50 case'n'://进入下个月 51 if (date.getMonth() == 12) 52 date = Date(date.getYear() + 1, 1, 1); 53 else 54 date = Date(date.getYear(), date.getMonth() + 1, 1); 55 for (int i = 0; i < n; i++) 56 { 57 accounts[i]->settle(date); 58 break; 59 } 60 }while{cmd != 'e'}; 61 return 0; 62 } 63 64 }
1 //改进:1.运算符重载,更加具有灵活性; 2 //2.所有公共操作皆声明为虚函数,实现运行时多态,各种类型的账户对象可以通过一个基类指//针的数组来访问,方便快捷; 3 //缺陷:1.UI可以更加美观;2.与真正的银行功能还有很多差异,比如预约,兑奖之类
1 //======================= 2 // container.cpp 3 //======================= 4 5 // default constructor initialise the inventory as empty 6 #include"container.h" 7 #include<iostream> 8 using namespace std; 9 10 container::container() 11 { 12 set(0, 0); 13 } 14 void container::set(int heal_n, int mw_n) 15 { 16 numOfHeal = heal_n; 17 numOfMW = mw_n; 18 } 19 20 // get the number of heal 21 int container::nOfHeal() 22 { 23 return numOfHeal; 24 } 25 26 // get the number of magic water 27 int container::nOfMW() 28 { 29 return numOfMW; 30 } 31 32 // display the items; 33 void container::display() 34 { 35 cout << "Your bag contains: " << endl; 36 cout << "Heal(HP+100): " << numOfHeal << endl; 37 cout << "Magic Water (MP+80): " << numOfMW << endl; 38 } 39 40 // use heal 41 bool container::useHeal() 42 { 43 numOfHeal--; 44 return 1; // use heal successfully 45 } 46 47 // use magic water 48 bool container::useMW() 49 { 50 numOfMW--; 51 return 1; // use magic water successfully 52 }
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_H_// 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 #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=0; // 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 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 }
1 //======================= 2 // player.cpp 3 //======================= 4 5 // character's HP and MP resume 6 #include<iostream> 7 #include"player.h" 8 #include<iomanip> 9 using namespace std; 10 11 void player::reFill() 12 { 13 HP = HPmax; // HP and MP fully recovered 14 MP = MPmax; 15 } 16 17 // report whether character is dead 18 bool player::death() 19 { 20 return playerdeath; 21 } 22 23 // check whether character is dead 24 void player::isDead() 25 { 26 if (HP <= 0) // HP less than 0, character is dead 27 { 28 cout << name << " is Dead." << endl; 29 system("pause"); 30 playerdeath = 1; // give the label of death value 1 31 } 32 } 33 34 // consume heal, irrelevant to job 35 bool player::useHeal() 36 { 37 if (bag.nOfHeal() > 0) 38 { 39 HP = HP + 100; 40 if (HP > HPmax) // HP cannot be larger than maximum value 41 HP = HPmax; // so assign it to HPmax, if necessary 42 cout << name << " used Heal, HP increased by 100." << endl; 43 bag.useHeal(); // use heal 44 system("pause"); 45 return 1; // usage of heal succeed 46 } 47 else // If no more heal in bag, cannot use 48 { 49 cout << "Sorry, you don't have heal to use." << endl; 50 system("pause"); 51 return 0; // usage of heal failed 52 } 53 } 54 55 // consume magic water, irrelevant to job 56 bool player::useMW() 57 { 58 if (bag.nOfMW() > 0) 59 { 60 MP = MP + 100; 61 if (MP > MPmax) 62 MP = MPmax; 63 cout << name << " used Magic Water, MP increased by 100." << endl; 64 bag.useMW(); 65 system("pause"); 66 return 1; // usage of magic water succeed 67 } 68 else 69 { 70 cout << "Sorry, you don't have magic water to use." << endl; 71 system("pause"); 72 return 0; // usage of magic water failed 73 } 74 } 75 76 // possess opponent's items after victory 77 void player::transfer(player& p) 78 { 79 cout << name << " got" << p.bag.nOfHeal() << " Heal, and " << p.bag.nOfMW() << " Magic Water." << endl; 80 system("pause"); 81 // set the character's bag, get opponent's items 82 bag.set(bag.nOfHeal() + p.bag.nOfHeal(), bag.nOfMW() + p.bag.nOfMW()); 83 84 } 85 86 // display character's job 87 void player::showRole() 88 { 89 switch (role) 90 { 91 case sw: 92 cout << "Swordsman"; 93 break; 94 case ar: 95 cout << "Archer"; 96 break; 97 case mg: 98 cout << "Mage"; 99 break; 100 default: 101 break; 102 } 103 } 104 105 // display character's job 106 void showinfo(player& p1, player& p2) 107 { 108 system("cls"); 109 cout << "##############################################################" << endl; 110 cout << "# Player" << setw(10) << p1.name << " LV. " << setw(3) << p1.LV 111 << " # Opponent" << setw(10) << p2.name << " LV. " << setw(3) << p2.LV << " #" << endl; 112 cout << "# HP " << setw(3) << (p1.HP <= 999 ? p1.HP : 999) << '/' << setw(3) << (p1.HPmax <= 999 ? p1.HPmax : 999) 113 << " | MP " << setw(3) << (p1.MP <= 999 ? p1.MP : 999) << '/' << setw(3) << (p1.MPmax <= 999 ? p1.MPmax : 999) 114 << " # HP " << setw(3) << (p2.HP <= 999 ? p2.HP : 999) << '/' << setw(3) << (p2.HPmax <= 999 ? p2.HPmax : 999) 115 << " | MP " << setw(3) << (p2.MP <= 999 ? p2.MP : 999) << '/' << setw(3) << (p2.MPmax <= 999 ? p2.MPmax : 999) << " #" << endl; 116 cout << "# AP " << setw(3) << (p1.AP <= 999 ? p1.AP : 999) 117 << " | DP " << setw(3) << (p1.DP <= 999 ? p1.DP : 999) 118 << " | speed " << setw(3) << (p1.speed <= 999 ? p1.speed : 999) 119 << " # AP " << setw(3) << (p2.AP <= 999 ? p2.AP : 999) 120 << " | DP " << setw(3) << (p2.DP <= 999 ? p2.DP : 999) 121 << " | speed " << setw(3) << (p2.speed <= 999 ? p2.speed : 999) << " #" << endl; 122 cout << "# EXP" << setw(7) << p1.EXP << " Job: " << setw(7); 123 p1.showRole(); 124 cout << " # EXP" << setw(7) << p2.EXP << " Job: " << setw(7); 125 p2.showRole(); 126 cout << " #" << endl; 127 cout << "--------------------------------------------------------------" << endl; 128 p1.bag.display(); 129 cout << "##############################################################" << endl; 130 }
1 #pragma once 2 //======================= 3 // player.h 4 //======================= 5 6 // The base class of player 7 // including the general properties and methods related to a character 8 9 #ifndef _PLAYER 10 #define _PLAYER 11 12 #include <iomanip> // use for setting field width 13 #include <time.h> // use for generating random factor 14 #include "container.h" 15 #include<string> 16 using namespace std; 17 18 enum job 19 { 20 sw, 21 ar, 22 mg 23 }; /* define 3 jobs by enumerate type 24 sword man, archer, mage */ 25 class player 26 { 27 friend void showinfo(player& p1, player& p2); 28 friend class swordsman; 29 30 protected: 31 int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV; 32 // General properties of all characters 33 string name; // character name 34 job role; /* character's job, one of swordman, archer and mage, 35 as defined by the enumerate type */ 36 container bag; // character's inventory 37 38 public: 39 virtual bool attack(player& p) = 0; // normal attack 40 virtual bool specialatt(player& p) = 0; // special attack 41 virtual void isLevelUp() = 0; // level up judgement 42 /* Attention! 43 These three methods are called "Pure virtual functions". 44 They have only declaration, but no definition. 45 The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 46 The detailed definition of these pure virtual functions will be given in subclasses. */ 47 48 void reFill(); // character's HP and MP resume 49 bool death(); // report whether character is dead 50 void isDead(); // check whether character is dead 51 bool useHeal(); // consume heal, irrelevant to job 52 bool useMW(); // consume magic water, irrelevant to job 53 void transfer(player& p); // possess opponent's items after victory 54 void showRole(); // display character's job 55 56 private: 57 bool playerdeath; // whether character is dead, doesn't need to be accessed or inherited 58 }; 59 60 #endif
1 //======================= 2 // swordsman.cpp 3 //======================= 4 5 // constructor. default values don't need to be repeated here 6 #include"swordsman.h" 7 #include<string.h> 8 #include<iostream> 9 #include<iomanip> 10 using namespace std; 11 12 swordsman::swordsman(int lv_in, string name_in) 13 { 14 role = sw; // enumerate type of job 15 LV = lv_in; 16 name = name_in; 17 18 // Initialising the character's properties, based on his level 19 HPmax = 150 + 8 * (LV - 1); // HP increases 8 point2 per level 20 HP = HPmax; 21 MPmax = 75 + 2 * (LV - 1); // MP increases 2 points per level 22 MP = MPmax; 23 AP = 25 + 4 * (LV - 1); // AP increases 4 points per level 24 DP = 25 + 4 * (LV - 1); // DP increases 4 points per level 25 speed = 25 + 2 * (LV - 1); // speed increases 2 points per level 26 27 playerdeath = 0; 28 EXP = LV * LV * 75; 29 bag.set(lv_in, lv_in); 30 } 31 32 void swordsman::isLevelUp() 33 { 34 if (EXP >= LV * LV * 75) 35 { 36 LV++; 37 AP += 4; 38 DP += 4; 39 HPmax += 8; 40 MPmax += 2; 41 speed += 2; 42 cout << name << " Level UP!" << endl; 43 cout << "HP improved 8 points to " << HPmax << endl; 44 cout << "MP improved 2 points to " << MPmax << endl; 45 cout << "Speed improved 2 points to " << speed << endl; 46 cout << "AP improved 4 points to " << AP << endl; 47 cout << "DP improved 5 points to " << DP << endl; 48 system("pause"); 49 isLevelUp(); // recursively call this function, so the character can level up multiple times if got enough exp 50 } 51 } 52 53 bool swordsman::attack(player& p) 54 { 55 double HPtemp = 0; // opponent's HP decrement 56 double EXPtemp = 0; // player obtained exp 57 double hit = 1; // attach factor, probably give critical attack 58 srand((unsigned)time(NULL)); // generating random seed based on system time 59 60 // If speed greater than opponent, you have some possibility to do double attack 61 if ((speed > p.speed) && (rand() % 100 < (speed - p.speed))) // rand()%100 means generates a number no greater than 100 62 { 63 HPtemp = (int)((1.0 * AP / p.DP) * AP * 5 / (rand() % 4 + 10)); // opponent's HP decrement calculated based their AP/DP, and uncertain chance 64 cout << name << "'s quick strike hit " << p.name << ", " << p.name << "'s HP decreased " << HPtemp << endl; 65 p.HP = int(p.HP - HPtemp); 66 EXPtemp = (int)(HPtemp * 1.2); 67 } 68 69 // If speed smaller than opponent, the opponent has possibility to evade 70 if ((speed < p.speed) && (rand() % 50 < 1)) 71 { 72 cout << name << "'s attack has been evaded by " << p.name << endl; 73 system("pause"); 74 return 1; 75 } 76 77 // 10% chance give critical attack 78 if (rand() % 100 <= 10) 79 { 80 hit = 1.5; 81 cout << "Critical attack: "; 82 } 83 84 // Normal attack 85 HPtemp = (int)((1.0 * AP / p.DP) * AP * 5 / (rand() % 4 + 10)); 86 cout << name << " uses bash, " << p.name << "'s HP decreases " << HPtemp << endl; 87 EXPtemp = (int)(EXPtemp + HPtemp * 1.2); 88 p.HP = (int)(p.HP - HPtemp); 89 cout << name << " obtained " << EXPtemp << " experience." << endl; 90 EXP = (int)(EXP + EXPtemp); 91 system("pause"); 92 return 1; // Attack success 93 } 94 95 bool swordsman::specialatt(player& p) 96 { 97 if (MP < 40) 98 { 99 cout << "You don't have enough magic points!" << endl; 100 system("pause"); 101 return 0; // Attack failed 102 } 103 else 104 { 105 MP -= 40; // consume 40 MP to do special attack 106 107 // 10% chance opponent evades 108 if (rand() % 100 <= 10) 109 { 110 cout << name << "'s leap attack has been evaded by " << p.name << endl; 111 system("pause"); 112 return 1; 113 } 114 115 double HPtemp = 0; 116 double EXPtemp = 0; 117 // double hit=1; 118 // srand(time(NULL)); 119 HPtemp = (int)(AP * 1.2 + 20); // not related to opponent's DP 120 EXPtemp = (int)(HPtemp * 1.5); // special attack provides more experience 121 cout << name << " uses leap attack, " << p.name << "'s HP decreases " << HPtemp << endl; 122 cout << name << " obtained " << EXPtemp << " experience." << endl; 123 p.HP = (int)(p.HP - HPtemp); 124 EXP = (int)(EXP + EXPtemp); 125 system("pause"); 126 } 127 return 1; // special attack succeed 128 } 129 130 // Computer opponent 131 void swordsman::AI(player& p) 132 { 133 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))) 134 // AI's HP cannot sustain 3 rounds && not too lavish && still has heal && won't be killed in next round 135 { 136 useHeal(); 137 } 138 else 139 { 140 if (MP >= 40 && HP > 0.5 * HPmax && rand() % 100 <= 30) 141 // AI has enough MP, it has 30% to make special attack 142 { 143 specialatt(p); 144 p.isDead(); // check whether player is dead 145 } 146 else 147 { 148 if (MP < 40 && HP > 0.5 * HPmax && bag.nOfMW()) 149 // Not enough MP && HP is safe && still has magic water 150 { 151 useMW(); 152 } 153 else 154 { 155 attack(p); // normal attack 156 p.isDead(); 157 } 158 } 159 } 160 }
1 #pragma once 2 //======================= 3 // swordsman.h 4 //======================= 5 6 // Derived from base class player 7 // For the job Swordsman 8 9 #include "player.h" 10 #include<string.h> 11 class swordsman :public player// subclass swordsman publicly inherited from base player 12 { 13 public: 14 swordsman(int lv_in = 1, string name_in = "Not Given"); 15 // constructor with default level of 1 and name of "Not given" 16 void isLevelUp(); 17 bool attack(player& p); 18 bool specialatt(player& p); 19 /* These three are derived from the pure virtual functions of base class 20 The definition of them will be given in this subclass. */ 21 void AI(player& p); // Computer opponent 22 };