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简单支付验证)钱包接入比特币网络,通 ...
随机推荐
- MapleSim助力长臂挖掘机建模问题解决
1.问题描述 一家机械零部件设计公司需要一个挖掘机模型,验证他们的零部件是否匹配完整的挖掘机系统.由于他们是一个零部件供应商,公司没有足够的资源和研发人员使用传统的工具创建一个完整系统的详细模型.然而 ...
- for循环后面跟分号 - for (i = 0; i <= 3; i++);这不是错误语句
#include<iostream> int main() { using namespace std; ; ; i <= ; i++); t = t + i; cout <& ...
- ABP理论学习之NHibernate集成
返回总目录 本篇目录 Nuget包 配置 实体映射 仓储 仓储基类 实现仓储 自定义仓储方法 阅读其他 ABP可以使用任何ORM框架工作,并且已经内置了NHibernate集成.这篇文章会解释如何在A ...
- Servlet程序中玩验证码
验证码思想:所谓验证码就是产生若干随机数,存放到session中,然后在servlet中获取session中的该值与页面输入值相比较,进而判断正误. 产生验证码的方法: 随机数放在图片中,封装为一 ...
- Andrew Ng机器学习公开课笔记 -- 学习理论
网易公开课,第9,10课 notes,http://cs229.stanford.edu/notes/cs229-notes4.pdf 这章要讨论的问题是,如何去评价和选择学习算法 Bias/va ...
- CocoaPods pod 安装、更新慢解决方法
使用CocoaPods来添加第三方类库,无论是执行pod install还是pod update都卡在了Analyzing dependencies不动了,令人甚是DT. 每一次都忘记现在自己记录一下 ...
- java,H5微信蓝牙设备开发教程申请设备和添加设备(2)
转载地址 http://www.vxzsk.com/76.html 申请设备功能 a. 登录公众平台,点击左边功能栏的"添加功能插件",选择"设备功能". b ...
- Leetcode-83 Remove Duplicates from Sorted List
#83. Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that ...
- 谈谈php里的IOC控制反转,DI依赖注入
理论 发现问题 在深入细节之前,需要确保我们理解"IOC控制反转"和"DI依赖注入"是什么,能够解决什么问题,这些在维基百科中有非常清晰的说明. 控制反转(In ...
- .NET平台开源项目速览(3)小巧轻量级NoSQL文件数据库LiteDB
今天给大家介绍一个不错的小巧轻量级的NoSQL文件数据库LiteDB.本博客在2013年也介绍过2款.NET平台的开源数据库: 1.[原创]开源.NET下的XML数据库介绍及入门 2.[原创]C#开源 ...