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.clear();
|
|
|
|
|
|
// 重置所有节点的状态
|
|
|
|
|
|
this._root.cleanupAll();
|
2025-06-04 23:10:59 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|