完善下列代码要求如下已知游戏中常见人物状态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; }
时间: 2024-02-29 21:55:21 浏览: 62
#include <iostream>
#include <string>
#include <time.h>
#include <math.h>
using namespace std;
// 人物状态抽象类
class State {
public:
virtual void idle() = 0;
virtual void run() = 0;
virtual void attack() = 0;
virtual void dead() = 0;
};
// 人物类
class Hero : public State {
private:
int hp;
int attack;
int defense;
public:
Hero(int h, int a, int d) : hp(h), attack(a), defense(d) {}
virtual void idle() { cout << "Hero is idling." << endl; }
virtual void run() { cout << "Hero is running." << endl; }
virtual void attack() { cout << "Hero is attacking." << endl; }
virtual void dead() { cout << "Hero is dead." << endl; }
};
// 怪物类
class Monster : public State {
private:
int hp;
int attack;
int defense;
string type;
public:
Monster(int h, int a, int d, string t) : hp(h), attack(a), defense(d), type(t) {}
virtual void idle() { cout << "Monster is idling." << endl; }
virtual void run() { cout << "Monster is running." << endl; }
virtual void attack() { cout << "Monster is attacking." << endl; }
virtual void dead() { cout << "Monster is dead." << endl; }
};
int main() {
State *s;
int input;
cout << "Please input 1 for Hero or 2 for Monster: ";
cin >> input;
if (input == 1) {
Hero hero(100, 10, 5);
s = &hero;
}
else if (input == 2) {
Monster monster(80, 15, 3, "Dragon");
s = &monster;
}
else {
cout << "Invalid input." << endl;
return 0;
}
s->idle();
s->attack();
s->run();
s->dead();
return 1;
}
阅读全文