行爲樹節點接口
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(){}
};