Add player_v2.cpp

main
p68710245 1 year ago
parent 0ee0ee5bd7
commit 1bfdb2e2a2

@ -0,0 +1,81 @@
#include <iostream>
#include <string>
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<Demon *>(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);
}
Loading…
Cancel
Save