Open main menu

CDOT Wiki β

Changes

State

1,911 bytes added, 09:21, 23 March 2007
Code Samples
[http://matrix.senecac.on.ca/~rmwang/btppresentation/statesample.html Click here to see the UML diagram for this example]
<pre>
class IState;
class cDarkElf : public cUnit {
IState* _pState;
void ChangeState(IState*);
public:
cDarkElf();
~cDarkElf();
void Attack(cUnit* Target);
void Move(int x, int y);
void Stop();
void HoldPosition();
void Slaughter(cUnit* Target);
void Update();
};
</pre>
<pre>
class IState {
const ID_STATE _ID;
public:
enum ID_STATE {STATE_ATTACK, STATE_MOVE, STATE_STOP,
STATE_HOLDPOSITION, STATE_SLAUGHTER };
IState(ID_STATE state) : _ID(state) {}
ID_STATE GetID() {return _ID;}
virtual void Operate() = 0;
};
 
class cState_Attack : public IState {
cUnit* _pTarget;
cUnit* _pUnit;
public:
cState_Attack(cUnit* target, cUnit* pUnit) : IState(STATE_ATTACK), _pTarget(target), _pUnit(pUnit) {}
void Operate();
};
 
class cState_Move : public IState {
int _x, _y;
cUnit* _pUnit;
public:
cState_Move(int x, int y, cUnit* pUnit);
void Operate();
};
 
class cState_Stop : public IState {
public:
void Operate();
};
 
class cState_HoldPosition : public IState {
public:
void Operate();
};
 
class cState_SLAUGHTER : public IState {
cUnit* _pTarget;
cUnit* _pUnit;
public:
cState_Slaughter(cUnit* target, cUnit* pUnit) : IState(STATE_SLAUGHTER), _pTarget(target), _pUnit(pUnit) {}
void Operate();
};
cDarkElf::cDarkElf() {_pState = new cState_Stop;}
cDarkElf::~cDarkElf() {delete _pState;}
void cDarkElf::ChangeState(IState* pState) {
delete _pState;
_pState = pState;
}
void cDarkElf::Attack(cUnit* Target) {ChangeState(new cState_Attack(Target, this));}
void cDarkElf::Move(int x, int y) {ChangeState(new cState_Move(x, y, this));}
void cDarkElf::Stop() {ChangeState(new cState_Stop);}
void cDarkElf::HoldPosition() {ChangeState(new cState_HoldPosition);}
void cDarkElf::Patrol(int x1, int y1, int x2, int y2) {ChangeState(new cState_Patrol(x1, y1, x2, y2));}
void cDarkElf::Update() {_pState->Operate();}
</pre>
1
edit