From 1bfdb2e2a23927eaf9287c3bcef9b49c8b8d8945 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Wed, 24 Apr 2024 22:02:17 +0800 Subject: [PATCH] Add player_v2.cpp --- player_v2.cpp | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 player_v2.cpp diff --git a/player_v2.cpp b/player_v2.cpp new file mode 100644 index 0000000..775271d --- /dev/null +++ b/player_v2.cpp @@ -0,0 +1,81 @@ +#include +#include +using std::cout, std::string, std::endl; + +class Player +{ +public: + string name; + int attack, defence, HP; + +public: + Player(string _name, int _attack, int _defence, int _HP) + : name{_name}, attack{_attack}, defence{_defence}, HP{_HP} + { + } + virtual void pk(Player *p) + { + while (HP > 0) + { + hit(p); + if (p->HP <= 0) + { + std::cout << p->name << "死亡!\n"; + return; + } + p->hit(this); + } + std::cout << name << "死亡!\n"; + } + + virtual void hit(Player *p) = 0; // 纯虚函数 +}; + +class Demon : public Player +{ +public: + using Player::Player; + virtual void hit(Player *p) + { + p->HP -= attack - p->defence; + HP += attack - p->defence; + std::cout << name << "砍了" << p->name << "一刀,并吸了一口血\n"; + } +}; + +class Angel : public Player +{ +public: + using Player::Player; + void hit(Player *p) + { + p->HP -= attack - p->defence; + p->HP -= attack - p->defence; + std::cout << name << "砍了" << p->name << "两刀\n"; + if (dynamic_cast(p)) // 向下转型 + { + std::cout << "天使遇到了恶魔,再砍一刀!\n"; + p->HP -= attack - p->defence; + } + } +}; + +class Ghost : public Player +{ +public: + using Player::Player; + virtual void hit(Player *p) + { + p->HP -= (attack - p->defence) * 1.5; + HP += (attack - p->defence) * 0.5; + std::cout << name << "砍了" << p->name << "一大刀,并吸了一小口血\n"; + } +}; + +int main() +{ + Angel a{"孙悟空", 100, 20, 1000}; + Demon d{"牛魔王", 100, 20, 1000}; + Ghost g{"白骨精", 100, 20, 1000}; + a.pk(&d); +} \ No newline at end of file