行为树节点接口
enum STATUS
{
STATUS_SLEEP,
STATUS_RUNNING,
STATUS_SUCCESS,
STATUS_FAILURE,
};
enum TYPE
{
TYPE_LEAF,
TYPE_BRANCH,
};
class Node {
public:
std::string _name; // 节点的名字
int _Index[12]; // 节点的序号,从根节点到当前节点的序号数组
int _level; // 节点的层级,也是序号数组的大小
STATUS _status; // 当前状态
TYPE _type; // 节点的类型
protected:
// 构造函数
Node(TYPE type):_status(STATUS_SLEEP), _type(type), _level(0) {}
public:
TYPE getNodeType() { return _type; }
STATUS getNodeStatus() { return _status; }
// 检查节点的有效性,添加节点时会检察有效性
virtual bool isValid() = 0;
//virtual void setToCurRunning(Node *root) = 0; // 设为当前运行
// 运行节点
virtual STATUS run() = 0;
virtual ~Node(){}
};
叶节点实现
typedef STATUS (*Action)();
typedef bool (*Condition)();
class Leaf : public Node {
private:
Condition _condition; // 叶节点的跳转条件,满足条件,也许应该在行为树里面,待定
Action _action; // 叶节点的行为
public:
Leaf():Node(TYPE_LEAF), _condition(NULL), _action(NULL){}
// 设置跳转条件
void setCondition(Condition condition)
{
_condition = condition;
}
// 设置行为动作
void setAction(Action action)
{
_action = action;
}
// 检查有效性
bool isValid()
{
return _action != NULL;
}
/*void setToCurRunning(Node *root)
{
Branch *branch =
}*/
// 运行动作,记录返回状态
STATUS run()
{
_status = _action();
return _status;
}
~Leaf(){}
};
分支节点实现
class Branch : public Node {
protected:
Node* _subNode[12]; // 子节点组
int _subNodeCnt = 0; // 子节点的数量
int _runNodeIdx = 0; // 当前运行的子节点索引
Branch() : Node(TYPE_BRANCH) {}
public:
Node *addNode(Node *node)
{
// 检查添加节点的有效性
if (!node->isValid())
return NULL;
// 将添加的节点添加到子节点中
_subNode[_subNodeCnt] = node;
// 添加的子节点在添加之前为根节点
node->_Index[0] = _subNodeCnt;
// 子节点的层级等于父节点的层级+1
node->_level += _level + 1;
// 将子节点的索引向后移,空出父节点的索引数
for (int i = 11 - _level; i >= 0; i--) {
node->_Index[i + _level] = node->_Index[i];
}
// 将父节点的索引添加给子节点
for (int i = 0; i <= _level; i++) {
node->_Index[i] = _Index[i];
}
// 如果子节点为branch,刷新branch下面的子节点的索引
if (node->getNodeType == TYPE_BRANCH) {
Branch *branch = (Branch*)node;
branch->freshSubNodeIndex();
}
_subNodeCnt++; // 子节点的数目+1
return node;
}
bool isValid() { return true; }
STATUS run() { return STATUS_SUCCESS; }
virtual ~Branch(){}
private:
void freshSubNodeIndex()
{
for (int i = 0; i < _subNodeCnt; i++) {
Node *node = _subNode[i];
node->_level = _level + 1;
for (int i = 11 - _level; i < 0; i++) {
node->_Index[i + _level] = node->_Index[i];
}
for (int i = 0; i <= _level; i++) {
node->_Index[i] = _Index[i];
}
if (node->getNodeType == TYPE_BRANCH) {
Branch *branch = (Branch*)node;
branch->freshSubNodeIndex();
}
}
}
};
sequence的branch实现
class Sequence : public Branch {
public:
Sequence():Branch(){}
bool isValid() {
return true;
}
STATUS run() {
int index = _runNodeIdx;
STATUS subStatus = _subNode[index]->run();
if (index + 1 < _subNodeCnt) {
if (subStatus == STATUS_FAILURE) {
_status = STATUS_FAILURE;
}
else {
_status = STATUS_RUNNING;
if(subStatus == STATUS_SUCCESS)
index++;
}
}
else {
_status = subStatus;
if (subStatus == STATUS_SUCCESS) {
index++;
}
}
_runNodeIdx = index;
return _status;
}
~Sequence(){}
};