C++已知游戏中常见人物状态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" int main() { State *s; s->idle(); s->attack(); s->run(); s->dead(); return 1; }
时间: 2024-02-17 20:03:09 浏览: 115
首先,需要定义State抽象类,包括idle、attack、run、dead四个纯虚函数:
```cpp
class State {
public:
virtual void idle() = 0;
virtual void attack() = 0;
virtual void run() = 0;
virtual void dead() = 0;
};
```
然后,定义Hero和Monster两个类,分别继承State类,并且拥有各自的属性:
```cpp
class Hero : public State {
public:
int hp;
int attack;
int defence;
void idle() {
cout << "Hero is idling." << endl;
}
void attack() {
cout << "Hero is attacking." << endl;
}
void run() {
cout << "Hero is running." << endl;
}
void dead() {
cout << "Hero is dead." << endl;
}
};
class Monster : public State {
public:
int hp;
int attack;
int defence;
string type;
void idle() {
cout << "Monster is idling." << endl;
}
void attack() {
cout << "Monster is attacking." << endl;
}
void run() {
cout << "Monster is running." << endl;
}
void dead() {
cout << "Monster is dead." << endl;
}
};
```
最后,在main函数中,根据用户输入的情况,创建相应的对象,并调用对象的函数:
```cpp
int main() {
srand(time(NULL));
int choice;
cout << "Enter 1 for hero, 2 for monster: ";
cin >> choice;
State *s;
if (choice == 1) {
Hero hero;
hero.hp = rand() % 100 + 1;
hero.attack = rand() % 10 + 1;
hero.defence = rand() % 10 + 1;
s = &hero;
}
else if (choice == 2) {
Monster monster;
monster.hp = rand() % 100 + 1;
monster.attack = rand() % 10 + 1;
monster.defence = rand() % 10 + 1;
monster.type = "Spider";
s = &monster;
}
s->idle();
s->attack();
s->run();
s->dead();
return 0;
}
```
需要注意的是,如果要让角色能够变身为怪物,需要在Hero类中添加一个函数,将Hero对象的状态改变为Monster对象:
```cpp
void transform() {
Monster monster;
monster.hp = rand() % 100 + 1;
monster.attack = rand() % 10 + 1;
monster.defence = rand() % 10 + 1;
monster.type = "Spider";
*this = monster;
}
```
然后,可以在main函数中添加如下代码,实现角色变身:
```cpp
if (choice == 1) {
Hero hero;
hero.hp = rand() % 100 + 1;
hero.attack = rand() % 10 + 1;
hero.defence = rand() % 10 + 1;
s = &hero;
cout << "Enter 1 for normal, 2 for transform: ";
cin >> choice;
if (choice == 2) {
hero.transform();
}
}
```
阅读全文