Files
kunpocc-behaviortree/src/behaviortree/BehaviorTree.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-09-03 10:54:07 +08:00
import { Blackboard, IBlackboard } from "./Blackboard";
import { IBTNode } from "./BTNode/BTNode";
import { Status } from "./header";
2025-06-04 23:10:59 +08:00
/**
*
*
*/
2025-09-02 17:05:46 +08:00
export class BehaviorTree<T> {
/**
* @internal
*/
2025-09-03 10:54:07 +08:00
private _root: IBTNode;
2025-09-02 17:05:46 +08:00
/**
* @internal
*/
2025-09-03 10:54:07 +08:00
private _blackboard: IBlackboard;
2025-09-02 17:05:46 +08:00
2025-09-03 10:54:07 +08:00
get root(): IBTNode { return this._root; }
get blackboard(): IBlackboard { return this._blackboard }
2025-09-02 17:05:46 +08:00
2025-06-04 23:10:59 +08:00
/**
* constructor
2025-09-03 10:54:07 +08:00
* @param entity
2025-06-04 23:10:59 +08:00
* @param root
*/
2025-09-03 10:54:07 +08:00
constructor(entity: T, root: IBTNode) {
2025-06-04 23:10:59 +08:00
this._root = root;
2025-09-03 10:54:07 +08:00
this._blackboard = new Blackboard(undefined, entity);
2025-09-02 17:05:46 +08:00
// 构造时就初始化所有节点ID避免运行时检查
this._initializeAllNodeIds(this._root);
2025-06-04 23:10:59 +08:00
}
/**
2025-09-02 17:05:46 +08:00
*
*/
2025-09-03 10:54:07 +08:00
public tick(): Status {
return this._root._execute();
2025-09-02 17:05:46 +08:00
}
/**
* ID
*
* @param node
* @internal
*/
2025-09-03 10:54:07 +08:00
private _initializeAllNodeIds(node: IBTNode, parent?: IBTNode): void {
2025-09-02 17:05:46 +08:00
// 设置当前节点ID
2025-09-04 14:08:19 +08:00
node._initialize(this._blackboard, parent ? parent.local : this._blackboard);
2025-09-02 17:05:46 +08:00
// 递归设置所有子节点ID
for (const child of node.children) {
2025-09-03 10:54:07 +08:00
this._initializeAllNodeIds(child, node);
2025-06-04 23:10:59 +08:00
}
}
2025-09-02 17:05:46 +08:00
/**
*
*
*/
public reset(): void {
this._blackboard.clean();
2025-06-04 23:10:59 +08:00
}
}