// 行为树(Behavior Tree)
// 每个节点执行后返回 成功/失败
// 行为树由4种节点构成:
// (1)Composite Node
// <1>Selector Node
// <2>Sequence Node
// <3>Parallel Node
// (2)Decorator Node
// (3)Condition Node
// (4)Action Node
// 由于行为树的结构和XML文件很类似,因此用XML来动态配置行为树是一个不错的方法.
// VC2008
#include "stdafx.h"
#include <list>
// 节点基类
template<typename EventT>
class BehaviorTreeNode
{
public:
BehaviorTreeNode(){};
virtual ~BehaviorTreeNode(){};
public:
virtual bool Behavior(const EventT& e) { return true; };
};
// 策略接口
class BehaviorTreeBranchStrategy
{
public:
BehaviorTreeBranchStrategy(){};
virtual ~BehaviorTreeBranchStrategy(){};
virtual void BehaviorBegin() {};
virtual void BehaviorEnd() {};
virtual bool IsContinue() { return true; };
virtual bool GetResult() { return true; };
};
// 非叶子节点
template<typename EventT>
class BranchNode : public BehaviorTreeNode<EventT>
{
public:
BranchNode() : m_pStrategy(0) { };
virtual ~BranchNode() {};
public:
virtual void AddNode(BehaviorTreeNode<EventT>* pAddNode)
{
if(pAddNode != 0)
{
m_listChildNode.push_back(pAddNode);
}
}
virtual void RemoveNode(BehaviorTreeNode<EventT>* pRemoveNode)
{
if(pRemoveNode != 0)
{
m_listChildNode.remove(pRemoveNode);
}
}
virtual BehaviorTreeBranchStrategy* GetStrategy() const
{
return m_pStrategy;
}
virtual void SetStrategy(BehaviorTreeBranchStrategy* pStrategy)
{
m_pStrategy = pStrategy;
}
virtual bool Behavior(const EventT& e)
{
if(m_pStrategy == 0)
{
return false;
}
m_pStrategy->BehaviorBegin();
for(std::list<BehaviorTreeNode<EventT> >::iterator it = m_listChildNode.begin();
it != m_listChildNode.end(); ++it)
{
if( !m_pStrategy->IsContinue() )
{
break;
}
m_pStrategy->Behavior( it->Behavior(e) );
}
m_pStrategy->BehaviorEnd();
return m_pStrategy->GetResult();
}
protected:
// 子节点
std::list<BehaviorTreeNode<EventT> > m_listChildNode;
// 策略
BehaviorTreeBranchStrategy* m_pStrategy;
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}