已知游戏中常见人物状态State抽象类,包括站立(Idle),行走(Run),攻击(Attack),死亡(Dead)等动作。在游戏中有角色hero类,拥有人物状态同时还拥有血量,攻击力,防御力等属性,有怪物类Monster,怪物有血量,攻击力,防御力,怪物类型等属性。 已知角色可以变身为怪物,现在main函数中,模拟某个角色在正常情况下以及在变身状态下的各种状态操作(输入1为正常hero,输入2则变身为monster)。 要求,使用抽象类及的基类指针实现。 #include <iostream> using namespace std; #include<string> #include"time.h" #include"math.h" //请在begin和end之间完成完成代码编写 /*************begin***********/ /*************end**********/ int main() { State *s; /*************begin*****************/ /**************end***************/ s->idle(); s->attack(); s->run(); s->dead(); return 1; }
时间: 2023-07-01 15:18:42 浏览: 171
根据你的要求,我给你提供一个实现:
首先,我们需要定义一个State抽象类,包含一些纯虚函数:
```
class State {
public:
virtual void idle() = 0;
virtual void run() = 0;
virtual void attack() = 0;
virtual void dead() = 0;
};
```
然后,我们定义一个基类Character,包含血量、攻击力、防御力和当前状态的成员变量:
```
class Character {
protected:
int hp;
int attack;
int defense;
State* state;
public:
Character(int h, int a, int d) : hp(h), attack(a), defense(d), state(nullptr) {}
void setState(State* s) {
if (state) {
delete state;
}
state = s;
}
void idle() {
state->idle();
}
void run() {
state->run();
}
void attack() {
state->attack();
}
void dead() {
state->dead();
}
};
```
接着,我们定义一个角色类Hero,继承自Character,并实现State的四个纯虚函数:
```
class Hero : public Character, public State {
public:
Hero(int h, int a, int d) : Character(h, a, d) {}
void idle() override {
cout << "Hero is idle" << endl;
}
void run() override {
cout << "Hero is running" << endl;
}
void attack() override {
cout << "Hero is attacking" << endl;
}
void dead() override {
cout << "Hero is dead" << endl;
}
};
```
再定义一个怪物类Monster,也继承自Character,并实现State的四个纯虚函数:
```
class Monster : public Character, public State {
public:
Monster(int h, int a, int d) : Character(h, a, d) {}
void idle() override {
cout << "Monster is idle" << endl;
}
void run() override {
cout << "Monster is running" << endl;
}
void attack() override {
cout << "Monster is attacking" << endl;
}
void dead() override {
cout << "Monster is dead" << endl;
}
};
```
最后,在main函数中,我们可以根据用户的选择创建不同的角色,并将其状态设置为相应状态:
```
int main() {
int choice;
cin >> choice;
Character* character;
if (choice == 1) {
character = new Hero(100, 10, 5);
character->setState(new Hero(100, 10, 5));
} else if (choice == 2) {
character = new Monster(200, 20, 10);
character->setState(new Monster(200, 20, 10));
}
character->idle();
character->run();
character->attack();
character->dead();
delete character->state;
delete character;
return 0;
}
```
这样,我们就通过抽象类和基类指针实现了一个角色状态的模拟。
把以上代码整合在一起,如下所示:
阅读全文