C++遊戲系列2:角色裝備武器
阿新 • • 發佈:2019-02-20
知識點:類的組合,A類的資料成員,是B類的物件,或B類的物件,做A類的資料成員
【專案-帶武器的遊戲角色】
設計一個武器類,其資料成員至少要有武器名、威力,還可以加上你想描述武器的其他資料。想一想要對武器實施什麼處理,設計其成員函式。
在上週的遊戲角色類Role基礎上擴充,為每個角色建立一個武器,並在攻擊(attack)行為發生時,武器在其中起作用。制定遊戲規則,使之接近於真實的遊戲場景,並利用成員函式實現遊戲規則,最後在main函式中通過呼叫相應的成員函式,模擬遊戲過程。
參考解答:
/*
僅設計了一個非常簡單的使用武器的規則
當攻擊對方時,自己漲血數等於自己武器的威力,同時對方失去等量血
對方失血變為0或負後,死去
歡迎遊戲者,按你的想像擴充
*/
#include <iostream>
using namespace std;
class Weapon
{
public:
Weapon(string wnam, int f);
int getForce();
private:
string wname; //名稱
int force; //威力
};
Weapon::Weapon(string wnam, int f):wname(wnam),force(f) {}
int Weapon::getForce()
{
return force;
}
class Role
{
public :
Role(string nam, int b, string wnam, int f); //建構函式
~Role(); //解構函式
void eat(int d); //吃東西,漲d血
void attack(Role &r); //攻擊別人,自己漲血,同時失血
bool isAlived(); //是否活著
void show(); //顯示
private:
string name;
int blood;
Weapon weapon;
bool life;
};
Role::Role(string nam, int b, string wnam, int f):name(nam),blood(b),weapon(wnam,f)
{
if(blood>0)
life=true;
else
life=false;
}
Role::~Role()
{
cout<<name<<"退出江湖..."<<endl;
}
void Role::eat(int d) //吃東西,漲d血
{
if(isAlived())
blood+=d;
}
void Role::attack(Role &r) //攻擊別人,漲1血
{
if(isAlived())
{
blood+=weapon.getForce();
r.blood-=weapon.getForce();
if(r.blood<=0)
r.life=false;
}
}
bool Role::isAlived() //是否活著
{
return life;
}
void Role::show() //顯示
{
cout<<name<<" has "<<blood<<" blood, it is ";
if(isAlived())
cout<<"alived.";
else
cout<<"dead.";
cout<<endl;
}
int main( )
{
Role mary("Mary", 500, "TuLong",200);
Role jack("Jack", 10, "YiTian", 180);
cout<<"---begin---"<<endl;
mary.show();
jack.show();
cout<<"---1st round---"<<endl;
jack.attack(mary);
mary.show();
jack.show();
cout<<"---2nd round---"<<endl;
mary.attack(jack);
mary.show();
jack.show();
cout<<"---end---"<<endl;
return 0;
}