C++ 多态的游戏例程
作者:网络转载 发布时间:[ 2015/6/26 14:27:58 ] 推荐标签:软件开发
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;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11