C++ 多态的游戏例程

发表于:2015-6-26 11:52

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:阿青1987    来源:51Testing软件测试网采编

  1)头文件 game.h
#ifndef GAME_H
#define GAME_H
// base class
class CCreature {
protected:
int m_nLifePower, m_nPower;
public:
virtual void Attack(CCreature *pCreature){}
virtual void Hurted(int nPower){}
virtual void FightBack(CCreature *pCreature){}
virtual int IsDead(){}
};
class CDragon: public CCreature {
public:
CDragon();
virtual void Attack(CCreature *pCreature);
virtual void Hurted(int nPower);
virtual void FightBack(CCreature *pCreature);
virtual int IsDead();
};
class CWolf: public CCreature {
public:
CWolf();
virtual void Attack(CCreature *pCreature);
virtual void Hurted(int nPower);
virtual void FightBack(CCreature *pCreature);
virtual int IsDead();
};
#endif // GAME_H
  2)成员函数实现文件game.cpp
#include <iostream>
#include "game.h"
using namespace std;
// === Dragon
CDragon::CDragon()
{
this->m_nLifePower = 100; // life value
this->m_nPower = 50; // attack ability
}
void CDragon::Attack(CCreature *p)
{
// attack code place here
cout << "Dragon fire" << endl;
p->Hurted(m_nPower);
if (!p->IsDead())
p->FightBack(this);
}
void CDragon::Hurted(int nPower)
{
// hurt action place here
cout << "Dragon hurt " << nPower << endl;
m_nLifePower -= nPower;
if (m_nLifePower <= 0)
cout << "Dragon was killed" << endl;
}
void CDragon::FightBack(CCreature *p)
{
// fight back action place here.
cout << "Dragon fire back! " << endl;
p->Hurted(m_nPower/2);
}
int CDragon::IsDead()
{
if (m_nLifePower <= 0)
return 1;
return 0;
}
// === Wolf
CWolf::CWolf()
{
this->m_nLifePower = 80; // life value
this->m_nPower = 30; // attack ability
}
void CWolf::Attack(CCreature *p)
{
// attack code place here
cout << "CWolf palm" << endl;
p->Hurted(m_nPower);
if (!p->IsDead())
p->FightBack(this);
}
void CWolf::Hurted(int nPower)
{
// hurt action place here
cout << "CWolf hurt " << nPower << endl;
m_nLifePower -= nPower;
if (m_nLifePower <= 0)
cout << "CWolf was killed" << endl;
}
void CWolf::FightBack(CCreature *p)
{
// fight back action place here.
cout << "CWolf palm back! " << endl;
p->Hurted(m_nPower/2);
}
int CWolf::IsDead()
{
if (m_nLifePower <= 0)
return 1;
return 0;
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号