带武器的游戏角色
设计一个武器类,其数据成员至少要有武器名、威力,还可以加上你想描述武器的其他数据。想一想要对武器实施什么处理,设计其成员函数。
在上一次的游戏角色类Role基础上扩充,为每个角色创建一个武器,并在攻击(attack)行为发生时,武器在其中起作用。制定游戏规则,使之接近于真实的游戏场景,并利用成员函数实现游戏规则,最后在main函数中通过调用相应的成员函数,模拟游戏过程。
#include<iostream>
#include<string>
using namespace std;
class weapon
{
public:
weapon(string na,int po)
{
name=na;
power=po;
}
int getpower();
string getname();
private:
string name;
int power;
};
string weapon::getname()
{
return name;
}
int weapon::getpower()
{
return power;
}
class Role
{
public:
Role(string nam,int n,string we,int p);
~Role();
void show();
void attack(Role &other);
void eat(int n);
void beAttack(Role &other);
bool isAlive();
string getname();
private:
string name;
int blood;
weapon weapon;
bool life;
};
string Role::getname()
{
return name;
}
void Role::attack(Role &other)
{
if(isAlive())
{
cout<<name<<"使用"<<weapon.getname()<<"攻击"<<other.getname()<<',';
cout<<other.getname()<<"损失"<<weapon.getpower()<<"滴血,";
cout<<name<<"得到"<<weapon.getpower()<<"滴血"<<endl;
blood+=weapon.getpower();
other.blood-=weapon.getpower();
if(other.blood<=0)
life=false;
}
}
void Role::eat(int n)
{
if(isAlive())
cout<<name<<"吃了一个苹果,血量增加"<<n<<"点"<<endl;
blood+=n;
}
void Role::beAttack(Role &other)
{
if(isAlive())
{
cout<<other.getname()<<"使用"<<other.weapon.getname()<<"攻击"<<name<<',';
cout<<name<<"损失"<<other.weapon.getpower()<<"滴血,";
cout<<other.getname()<<"得到"<<other.weapon.getpower()<<"滴血"<<endl;
blood-=other.weapon.getpower();
other.blood+=weapon.getpower();
if(blood<=0)
life=false;
}
}
bool Role::isAlive()
{
return life;
}
Role::Role(string nam,int n,string we,int p):name(nam),blood(n),weapon(we,p)
{
// this->name=nam;
// this->blood=n;
// this->weapon.name=we;
// this->weapon.power=p;
if(blood>0)
life= true;
else
life= false;
}
Role::~Role()
{
if(blood<=0)
cout<<name<<"退出江湖"<<endl;
}
void Role::show()
{
if(blood>0)
cout<<name<<"还剩"<<blood<<"滴血"<<endl;
}
int main( )
{
int i=1;
cout<<"初始状态:"<<endl;
Role mary("Mary", 100,"灵兽刀",90);
Role jack("Jack", 100,"张扬剑",10);
mary.show();
jack.show();
cout<<"第一回合:"<<endl;
mary.attack(jack);
mary.beAttack(jack);
jack.attack(mary);
jack.beAttack(mary);
jack.eat(5);
mary.show();
jack.show();
cout<<"第二回合:"<<endl;
mary.attack(jack);
mary.beAttack(jack);
jack.attack(mary);
jack.beAttack(mary);
mary.show();
jack.show();
return 0;
}
感想:难!独立完成肯定是不可能的,还是做了参考,才完成。其中自己稍微做了修改,开始还出现错误:error LNK2011: 未链接预编译对象;映像可能不能运行;fatal error LNK1120: 1 个无法解析的外部命令;开始不明白错在哪儿,随后在构造函数中发现参数列表,我写了一个weapon we,weapon是类名,同样在Role类中做了一个私有成员变量,表示武器的名字。最后发现名字的命名类型是string,修改之后就好了。程序功能实现之后,想让程序更好看,就直接调用了私有成员变量,错误提示说不能访问,于是就专门设定了一个得到他们的公有的函数。现在知道了,访问私有成员要借助公有函数来实现,这个概念虽然在书本上看见过,但是还没有在实际操作中测试过(可能之前也出现过,只是印象不深刻)今天的编程时间有七个小时,一点一点,就算只接收到了一点点,收益还是不错的。(但是今天的对我来说的确有难度),情绪还是受到了点影响,还是要加油才行。