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

97 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-06-04 23:10:59 +08:00
import { Blackboard } from "./Blackboard";
import { BaseNode } from "./BTNode/BaseNode";
/**
*
*
*/
2025-09-02 17:05:46 +08:00
export class BehaviorTree<T> {
/**
* @internal
*/
2025-06-04 23:10:59 +08:00
private _root: BaseNode;
2025-09-02 17:05:46 +08:00
/**
* @internal
*/
private _blackboard: Blackboard;
/**
* @internal
*/
private _subject: T;
/**
* ID计数器
* @internal
*/
private _nodeIdCounter: number = 0;
get root(): BaseNode { return this._root; }
get blackboard() { return this._blackboard }
get subject(): T { return this._subject; }
2025-06-04 23:10:59 +08:00
/**
* constructor
2025-09-02 17:05:46 +08:00
* @param subject
2025-06-04 23:10:59 +08:00
* @param root
*/
2025-09-02 17:05:46 +08:00
constructor(subject: T, root: BaseNode) {
2025-06-04 23:10:59 +08:00
this._root = root;
2025-09-02 17:05:46 +08:00
this._blackboard = new Blackboard();
this._subject = subject;
// 构造时就初始化所有节点ID避免运行时检查
this._initializeAllNodeIds(this._root);
2025-06-04 23:10:59 +08:00
}
/**
2025-09-02 17:05:46 +08:00
*
*/
public tick(): void {
this._root._execute(this);
}
/**
* ID
* ID
* @internal
*/
private _generateNodeId(): string {
return `${++this._nodeIdCounter}`;
}
/**
* ID
*
* @param node
* @internal
*/
private _initializeAllNodeIds(node: BaseNode): void {
// 设置当前节点ID
node.id = this._generateNodeId();
// 递归设置所有子节点ID
for (const child of node.children) {
this._initializeAllNodeIds(child);
2025-06-04 23:10:59 +08:00
}
}
2025-09-02 17:05:46 +08:00
/**
*
*
*/
public reset(): void {
this._blackboard.clear();
// 重置所有节点的状态
this._root.cleanupAll();
2025-06-04 23:10:59 +08:00
}
2025-09-02 17:05:46 +08:00
/**
*
*
* @param node
*/
public resetMemoryNode(node: BaseNode): void {
// 通过黑板标记该节点需要重置记忆
this._blackboard.set(`reset_memory`, true, node);
2025-06-04 23:10:59 +08:00
}
}