您的位置:首页 > 其它

第七周项目3 角色类组合多文件

2016-04-13 19:22 169 查看
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"></span><pre name="code" class="cpp">/*
*Copyright(c) 2016,烟台大学计算机学院
*All rights reserved.
*作    者:刘金石
*完成日期:2016年4月10日
*版本  号:v1.0
*问题描述:设计游戏中的角色类,并把武器作为一个单独的类,使用多文件处理
*输入描述:角色。
*输出描述:输出模拟战斗过程。
*/



<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">game.h     //头文件</span>


#ifndef GAMESS_H_INCLUDED
#define GAMESS_H_INCLUDED
using namespace std;
class Weapon
{
string name;//武器名字
int force;//武器威力
public:
Weapon(string mname,int mforce):name(mname),force(mforce){}//构造函数
int getcomForce();//获取普通攻击数值
int getbigForce();//获取大招攻击数值
};
class Role
{
public:
Role(string jsname,int xblood,string wqname,int wqf);//角色类的构造函数
~Role();//析构函数
void show();
bool isAlived();
void comattack(Role &r);//普通攻击
void finalhit(Role &r);//大招攻击
void eat(int bloo);//吃东西,获取血量
private:
string name;//角色名字
int blood;
bool life;//角色状态
Weapon weapon;
};

#endif // GAMESS_H_INCLUDED
role.cpp:定义角色类的成员函数

#include<iostream>
#include"gamess.h"
using namespace std;
bool Role::isAlived() //是否活着
{
return life;
}
Role::Role(string jsname,int xblood,string wqname,int wqf):name(jsname),blood(xblood),weapon(wqname,wqf)
{
if(blood>0)
life=true;
else
life=false;
}
Role::~Role()
{
cout<<name<<"退出江湖..."<<endl;
}
void Role::comattack(Role &r)
{
cout<<r.name<<" "<<"was"<<" "<<"be"<<" "<<"attack"<<endl;
if(isAlived())
{
//blood+=weapon.getcomForce();
r.blood-=weapon.getcomForce();
if(r.blood<=0)
r.life=false;
}
}
void Role::finalhit(Role &r)
{
cout<<r.name<<" "<<"was"<<" "<<"be"<<" "<<"attack"<<endl;
if(isAlived())
{
//blood+=weapon.getbigForce();
r.blood-=weapon.getbigForce();
if(r.blood<=0)
r.life=false;
}
}
void Role::show() //显示
{
cout<<name<<" has "<<blood<<" blood, it is ";
if(isAlived())
cout<<"alived.";
else
cout<<"dead.";
cout<<endl;
}
void Role::eat(int blo)
{
blood=blood+blo;
cout<<name<<" "<<"eat"<<" "<<"something,"<<"blood"<<" "<<"is"<<" "<<blood<<endl;
}


weapon.cpp:武器类的成员函数的实现

#include<iostream>
#include"gamess.h"
using namespace std;
int  Weapon::getcomForce()
{
return force;
}
int  Weapon::getbigForce()
{
return (force*2);
}


main.cpp//测试文件

#include<iostream>
#include"gamess.h"
using namespace std;
int main()
{
cout<<"---begin---"<<endl;
Role mary("Mary",4,"yitian",2);
Role jack("Jack",6,"tulong",3);
mary.show();
jack.show();
cout<<"---1st round---"<<endl;
mary.comattack(jack);
mary.eat(2);
mary.show();
jack.show();
cout<<"---2nd round---"<<endl;
jack.finalhit(mary);
mary.show();
jack.show();
cout<<"---end---"<<endl;
return 0;
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: