C++ 版本的 行为树的简单实现

//回到主人身边
class AINodeGotoOwnerSide : public AINodeBase
{
private:
static AINodeRegister<AINodeGotoOwnerSide> reg; public:
virtual bool invoke(int level = , bool isLog = false);
};
AINodeRegister<AINodeGotoOwnerSide> AINodeGotoOwnerSide::reg(ANT_GOTO_OWNER_SIDE, "AINodeGotoOwnerSide");
bool AINodeGotoOwnerSide::invoke(int level, bool isLog)
{
return rand() % > ;
}
AINodeDescribe des[] = {
AINodeDescribe(, , ANBT_SELECT, "根节点"),
AINodeDescribe(, , ANBT_SEQUENCE, "是否拾取金币的判定节点"),
AINodeDescribe(, , ANT_RELEASE_SKILL, "附近是否存在金币"),
AINodeDescribe(, , ANT_PICKING_UP_COINS, "捡取金币节点"),
AINodeDescribe(, , ANBT_SEQUENCE, "是否回到主人身边的判定节点"),
AINodeDescribe(, , ANT_RELEASE_SKILL, "是不是很长时间没有见到金币了"),
AINodeDescribe(, , ANT_PICKING_UP_COINS, "是不是很长时间没有回到主人身边了"),
AINodeDescribe(, , ANT_PICKING_UP_COINS, "回到主人身边的执行节点"),
AINodeDescribe(, , ANT_PICKING_UP_COINS, "没事随便逛逛吧"),
};
int desCount = sizeof(des) / sizeof(AINodeDescribe);
vector<AINodeDescribe> des_vtr;
for (int i = ; i < desCount; ++i)
{
des_vtr.push_back(des[i]);
}
AINodeBase * rootNode = AINodeHelper::sharedHelper()->CreateNodeTree(des_vtr);
cout << "\n状态结构组织图 \n" << endl;
AINodeHelper::sharedHelper()->printAITree(rootNode); cout << "\n状态结构组织图 \n" << endl;
for (int i = ; i < ; ++i)
{
cout << "调用树开始" << endl; rootNode->invoke(, true); cout << "调用树结束" << endl;
}
AITree.h
//
// AITree.h
// KPGranny2
//
// Created by bianchx on 15/9/15.
//
// #ifndef __KPGranny2__AITree__
#define __KPGranny2__AITree__ #include <stdio.h>
#include <vector>
#include <map>
#include <string> #include "AITreeNodeType.h" #pragma mark =============== public Helper Action ================== class AINodeBase; typedef AINodeBase * (* BaseNodeCreate)(); struct AINodeDescribe
{
AINodeDescribe()
{
memset(this, 0, sizeof(AINodeDescribe));
} AINodeDescribe(int id, int pId, int typeId, char * describe = NULL)
:Id(id)
,ParentId(pId)
,AINodeTypeId(typeId)
{
memset(Describe, 0, sizeof(Describe)); if(describe != NULL && strlen(describe) < sizeof(Describe) / sizeof(char))
{
strcpy(Describe, describe);
}
} int Id; //当期节点Id
int ParentId; //父节点Id
int AINodeTypeId; //智能节点类型Id
char Describe[256]; //节点名称
}; class AINodeHelper
{
private:
static AINodeHelper * m_nodeHlper; std::map<int, BaseNodeCreate> m_type2Create;
std::map<int, std::string> m_type2Name; public:
static AINodeHelper * sharedHelper(); void registerNodeCreate(int type, BaseNodeCreate create);
void registerNodeName(int type, std::string name); AINodeBase * CreateNode(int type); //创建节点 AINodeBase * CreateNodeTree(std::vector<AINodeDescribe> des, void * host = NULL); void printAITree(AINodeBase * node, int level = 0);
}; template <class T>
class AINodeRegister
{
public:
static AINodeBase * CreateT()
{
return new T();
} AINodeRegister(int type, std::string name = "")
{
AINodeHelper * helper = AINodeHelper::sharedHelper(); helper->registerNodeCreate(type, &AINodeRegister::CreateT); if(name != "")
helper->registerNodeName(type, name);
}
}; #pragma mark ================== 具体的内容 ================= enum AINodeBaseType
{
ANBT_SELECT, //选择节点
ANBT_SEQUENCE, //顺序节点
ANBT_NOT, //取反节点
}; class MemoryManagementObject
{
private:
int m_mmo_referenceCount; public:
MemoryManagementObject()
:m_mmo_referenceCount(1)
{
} virtual ~MemoryManagementObject()
{ } int getReferenceCount();
void retain();
void release();
}; class AINodeBase : public MemoryManagementObject
{
protected:
std::string m_nodeName;
std::string m_nodeDescribe; public:
AINodeBase()
:m_host(NULL)
,m_nodeName("AINodeBase")
,m_nodeDescribe("")
{
} virtual ~AINodeBase() { } void * m_host; //AI的宿主 virtual bool invoke(int level = 0, bool isLog = false) { return false; } virtual void destroy(); virtual void setDescribe(std::string describe);
virtual std::string getDescribe(); virtual void setName(std::string name);
virtual std::string getName();
}; //列表节点
class AIListNode : public AINodeBase
{
protected:
std::vector<AINodeBase *> m_childNodes; public:
virtual void addChildNode(AINodeBase * node);
virtual std::vector<AINodeBase *> & getChildNodes();
virtual void destroy();
}; //单条节点
class AISingleNode : public AINodeBase
{
protected:
AINodeBase * m_childNode; public:
AISingleNode()
:m_childNode(NULL)
{ } virtual void setChildNode(AINodeBase * node);
virtual AINodeBase * getChildNode();
virtual void destroy();
}; //选择节点
class AISelectNode : public AIListNode
{
private:
static AINodeRegister<AISelectNode> reg; public:
virtual bool invoke(int level = 0, bool isLog = false);
}; //顺序节点
class AISequenceNode : public AIListNode
{
private:
static AINodeRegister<AISequenceNode> reg; public:
virtual bool invoke(int level = 0, bool isLog = false);
}; //取反节点
class AINotNode : public AISingleNode
{
private:
static AINodeRegister<AINotNode> reg; public:
virtual bool invoke(int level = 0, bool isLog = false);
}; #endif /* defined(__KPGranny2__AITree__) */
AITree.cpp
//
// AITree.cpp
// KPGranny2
//
// Created by bianchx on 15/9/15.
//
// #include "AITree.h" #include <iostream>
#include <sstream> #define COMMAND_LINE 0
#define COCOS2D 1
#define AI_DEBUG 1 #if COCOS2D
#include "cocos2d.h"
#endif using namespace std; AINodeHelper * AINodeHelper::m_nodeHlper(NULL); AINodeHelper * AINodeHelper::sharedHelper()
{
if(m_nodeHlper == NULL)
m_nodeHlper = new AINodeHelper(); return m_nodeHlper;
} void AINodeHelper::registerNodeCreate(int type, BaseNodeCreate create)
{
m_type2Create[type] = create;
} void AINodeHelper::registerNodeName(int type, std::string name)
{
m_type2Name[type] = name;
} AINodeBase * AINodeHelper::CreateNode(int type)
{
AINodeBase * nodeBase = NULL; do
{
map<int, BaseNodeCreate>::iterator iter = m_type2Create.find(type); if(iter == m_type2Create.end())
break; nodeBase = (*iter).second(); if(nodeBase == NULL)
break; map<int, string>::iterator iter_name = m_type2Name.find(type);
if(iter_name != m_type2Name.end())
{
string & name = (*iter_name).second;
nodeBase->setName(name);
}
}while(0); return nodeBase;
} AINodeBase * AINodeHelper::CreateNodeTree(vector<AINodeDescribe> des, void * host)
{
if(des.size() == 0)
return NULL; #if COMMAND_LINE && AI_DEBUG
cout << "CreateNodeTree all count = " << des.size() << endl;
#endif #if COCOS2D && AI_DEBUG
CCLOG("CreateNodeTree all count = %d", (int)des.size());
#endif map<int, AINodeBase *> m_type2Create; AINodeBase * rootNode = NULL; for(vector<AINodeDescribe>::iterator iter = des.begin(); iter != des.end(); ++iter)
{
AINodeDescribe &item = (*iter);
AINodeBase * node = CreateNode(item.AINodeTypeId); #if COMMAND_LINE && AI_DEBUG
cout << "CreateNodeTree " << item.AINodeTypeId << endl;
#endif #if COCOS2D && AI_DEBUG
CCLOG("CreateNodeTree %d", item.AINodeTypeId);
#endif if(node == NULL)
continue; node->m_host = host; //注入宿主 if(strlen(item.Describe) != 0)
{
node->setDescribe(item.Describe);
} m_type2Create[item.Id] = node; if(item.ParentId == 0)
{
rootNode = node;
}
else
{
do
{
AINodeBase * parentNode = m_type2Create[item.ParentId];
if(parentNode == NULL)
break; AIListNode * listParentNode = dynamic_cast<AIListNode *>(parentNode);
if(listParentNode != NULL)
{
listParentNode->addChildNode(node);
break;
} AISingleNode * singleNode = dynamic_cast<AISingleNode *>(parentNode);
if(singleNode != NULL)
{
singleNode->setChildNode(node);
break;
} } while (0);
}
} return rootNode;
} void AINodeHelper::printAITree(AINodeBase * node, int level)
{
ostringstream oss; for (int i = 0; i < level; ++i)
{
oss << "\t";
} oss << node->getName() << " " << node->getDescribe() << " " << node; #if COMMAND_LINE
cout << oss.str().c_str() << endl;;
#endif #if COCOS2D
CCLOG(oss.str().c_str());
#endif do
{
AIListNode * listNode = dynamic_cast<AIListNode *>(node);
if(listNode != NULL)
{
vector<AINodeBase *> & childs = listNode->getChildNodes();
if(childs.size() > 0)
{
for (std::vector<AINodeBase *>::iterator i = childs.begin(); i != childs.end(); ++i)
{
printAITree(*i, level + 1);
}
} break;
} AISingleNode * singleNode = dynamic_cast<AISingleNode *>(node);
if(singleNode != NULL)
{
AINodeBase * child = singleNode->getChildNode();
if(child != NULL)
{
printAITree(child, level + 1);
}
}
} while (0); } int MemoryManagementObject::getReferenceCount()
{
return m_mmo_referenceCount;
} void MemoryManagementObject::retain()
{
++m_mmo_referenceCount;
} void MemoryManagementObject::release()
{
--m_mmo_referenceCount; if(m_mmo_referenceCount <= 0)
{
delete this;
}
} //最根层节点
void AINodeBase::destroy()
{
#if COMMAND_LINE && AI_DEBUG
cout << "destroy " << getName() << " " << this << endl;
#endif #if COCOS2D && AI_DEBUG
CCLOG("destroy %s %p", getName().c_str(), this);
#endif release();
} void AINodeBase::setDescribe(std::string describe)
{
m_nodeDescribe = describe;
} string AINodeBase::getDescribe()
{
return m_nodeDescribe;
} void AINodeBase::setName(string name)
{
m_nodeName = name;
} string AINodeBase::getName()
{
return m_nodeName;
} //列表节点
void AIListNode::addChildNode(AINodeBase * node)
{
m_childNodes.push_back(node);
} std::vector<AINodeBase *> & AIListNode::getChildNodes()
{
return m_childNodes;
} void AIListNode::destroy()
{
if(m_childNodes.size() > 0)
{
for(vector<AINodeBase *>::iterator iter = m_childNodes.begin(); iter != m_childNodes.end(); ++iter)
{
(*iter)->destroy();
}
} AINodeBase::destroy();
} //单条节点
void AISingleNode::setChildNode(AINodeBase * node)
{
if(m_childNode != node)
{
if(m_childNode != NULL)
m_childNode->destroy(); m_childNode = node;
}
} AINodeBase * AISingleNode::getChildNode()
{
return m_childNode;
} void AISingleNode::destroy()
{
if(m_childNode != NULL)
{
m_childNode->destroy();
} AINodeBase::destroy();
} //选择节点
AINodeRegister<AISelectNode> AISelectNode::reg(ANBT_SELECT, "AISelectNode"); bool AISelectNode::invoke(int level, bool isLog)
{
bool success = false; do
{
if(m_childNodes.size() == 0)
break; for(vector<AINodeBase *>::iterator iter = m_childNodes.begin(); iter != m_childNodes.end(); ++iter)
{
AINodeBase * node = (*iter);
bool inv = node->invoke(level + 1, isLog); #if (COMMAND_LINE || COCOS2D) && AI_DEBUG
ostringstream oss; for (int i = 0; i < level; ++i) {
oss << " ";
} oss << node->getName() << " invoke " << inv;
#endif #if COMMAND_LINE && AI_DEBUG
if(isLog)
{
cout << oss.str().c_str() << endl;
}
#endif #if COCOS2D && AI_DEBUG
if(isLog)
{
CCLOG("%s", oss.str().c_str());
}
#endif if(inv)
{
success = true;
break;
}
}
} while (false); return success;
} //顺序节点
AINodeRegister<AISequenceNode> AISequenceNode::reg(ANBT_SEQUENCE, "AISequenceNode"); bool AISequenceNode::invoke(int level, bool isLog)
{
bool success = true; do
{
for(vector<AINodeBase *>::iterator iter = m_childNodes.begin(); iter != m_childNodes.end(); ++iter)
{
AINodeBase * node = (*iter);
bool inv = node->invoke(level + 1, isLog); #if (COMMAND_LINE || COCOS2D) && AI_DEBUG
ostringstream oss; for (int i = 0; i < level; ++i) {
oss << " ";
} oss << node->getName() << " invoke " << inv;
#endif #if COMMAND_LINE && AI_DEBUG
if(isLog)
{
cout << oss.str() << endl;
}
#endif #if COCOS2D && AI_DEBUG
if(isLog)
{
CCLOG("%s", oss.str().c_str());
}
#endif if(inv == false)
{
success = false;
break;
}
}
} while (false); return success;
} //取反节点
AINodeRegister<AINotNode> AINotNode::reg(ANBT_NOT, "AINotNode"); bool AINotNode::invoke(int level, bool isLog)
{
bool success = false; do
{
if(m_childNode == NULL)
break; success = !(m_childNode->invoke(level + 1, isLog));
} while (false); #if (COMMAND_LINE || COCOS2D) && AI_DEBUG
ostringstream oss; for (int i = 0; i < level; ++i) {
oss << " ";
} if(m_childNode != NULL)
{
oss << m_childNode->getName() << " invoke " << !success;
}
else
{
oss << "no child";
}
#endif #if COMMAND_LINE && AI_DEBUG
if(isLog)
{
cout << oss.str() << endl;
}
#endif #if COCOS2D && AI_DEBUG
if(isLog)
{
CCLOG("no child");
}
#endif return success;
}
C++ 版本的 行为树的简单实现的更多相关文章
- 『zkw线段树及其简单运用』
阅读本文前,请确保已经阅读并理解了如下两篇文章: 『线段树 Segment Tree』 『线段树简单运用』 引入 这是一种由\(THU-zkw\)大佬发明的数据结构,本质上是经典的线段树区间划分思想, ...
- 【ARM-Linux开发】内核3.x版本之后设备树机制
内核3.x版本之后设备树机制 Based on Linux 3.10.24 source code 参考/documentation/devicetree/Booting-without- ...
- 《机器学习Python实现_10_10_集成学习_xgboost_原理介绍及回归树的简单实现》
一.简介 xgboost在集成学习中占有重要的一席之位,通常在各大竞赛中作为杀器使用,同时它在工业落地上也很方便,目前针对大数据领域也有各种分布式实现版本,比如xgboost4j-spark,xgbo ...
- RDIFramework.NET V2.7 Web版本升手风琴+树型目录(2级+)方法
RDIFramework.NET V2.7 Web版本升手风琴+树型目录(2级+)方法 手风琴风格在Web应用非常的普遍,越来越多的Web应用都是采用这种方式来体现各个功能模块,传统的手风琴风格只支持 ...
- LA、Remember the Word (字典树, 简单dp)
传送门 题意: 给你一个初始串 S,strlen(s) <= 3e5 然后给你 n 个单词. n <= 4000, 每个单词的长度不超过 100 : 问你这个初始串,分割成若干个单词的 ...
- 动态树(Link-Cut-Tree)简单总结(指针版本)
Link-Cut-Tree(动态树 LCT) 1.定义 1. 偏爱子节点: 一颗子树内最后访问的点若在该子树根节点 X 的某个儿子节点 P 的子树中,则称 P 为 X 的偏爱子节点. 偏爱边:连向偏爱 ...
- C#.NET 大型通用信息化系统集成快速开发平台 4.0 版本 - 用户权限树的实现 -- 权限递归树
业务系统里经常会需要计算类似的树形权限树的业务需求 1:往往会有一些需求,a 对 b 有权限, b对c 有权限, 等等. 2:还需要很直观的看到,整个权限的树形关系,一目了然的那种. 3:程序调用简单 ...
- POJ 3630 Phone List(trie树的简单应用)
题目链接:http://poj.org/problem?id=3630 题意:给你多个字符串,如果其中任意两个字符串满足一个是另一个的前缀,那么输出NO,否则输出YES 思路:简单的trie树应用,插 ...
- 比特币区块结构Merkle树及简单支付验证分析
在比特币网络中,不是每个节点都有能力储存完整的区块链数据,受限于存储空间的的限制,很多节点是以SPV(Simplified Payment Verification简单支付验证)钱包接入比特币网络,通 ...
随机推荐
- MongoDB 聚合管道(Aggregation Pipeline)
管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...
- Reactive Extensions介绍
Reactive Extensions(Rx)是对LINQ的一种扩展,他的目标是对异步的集合进行操作,也就是说,集合中的元素是异步填充的,比如说从Web或者云端获取数据然后对集合进行填充.Rx起源于M ...
- 标准数据源访问库 - JayData
JayData 是一个标准的.跨平台的库和方法,用于访问和操作各种不同的数据源,最适合用于 JavaScript 和 HTML5 应用. 官方网站:http://jaydata.org/ ASP.N ...
- MySQL 权限
create user创建用户 CREATE USER li@localhost IDENTIFIED BY 'li'; 授予用户li数据库person的所有权限,并允许用户li将数据库person的 ...
- Win7&Ubuntu12.04 双系统引导问题
周末的时候手贱,重装系统,导致原来的ubuntu12.04和win7双系统的引导不见了,所以在此进行一下说明,如何修复. 1. win7和ubuntu12.04双系统引导修复 问题描述: 在重装 ...
- Android 解决方法数 65536 (65k) 限制
可能出现的错误信息: Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: ...
- Atitit webservice的发现机制 discover机制
Atitit webservice的发现机制 discover机制 1.1. Ws disconvert 的组播地址和端口就是37021 1.2. Ws disconvert的发现机制建立在udp组播 ...
- PHP从PHP5.0到PHP7.1的性能全评测
本文是最初是来自国外的这篇:PHP Performance Evolution 2016, 感谢高可用架构公众号翻译成了中文版, 此处是转载的高可用架构翻译后的文章从PHP 5到PHP 7性能全评测( ...
- OpenCASCADE DataExchange DWG
OpenCASCADE DataExchange DWG eryar@163.com Abstract. DWG is a file format created in the 70’s for th ...
- c++与java中子类中调用父类成员的方法
java中: import java.util.Scanner; public class ClassTest{ public static void main(String args[]){ chi ...