behaviortree
Version:
A JavaScript implementation of Behavior Trees. They are useful for implementing AIs. For Browsers and NodeJS.
55 lines (54 loc) • 1.72 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registryLookUp = exports.getRegistry = void 0;
const helper_1 = require("./helper");
const Task_1 = __importDefault(require("./Task"));
let registry = {};
function getRegistry() {
return registry;
}
exports.getRegistry = getRegistry;
function registryLookUp(node) {
if (typeof node === 'string') {
const lookedUpNode = registry[node];
if (!lookedUpNode) {
throw new Error(`No node with name ${node} registered.`);
}
return lookedUpNode;
}
return node;
}
exports.registryLookUp = registryLookUp;
class BehaviorTree {
constructor({ tree, blackboard }) {
this.tree = tree;
this.blackboard = blackboard;
this.lastResult = undefined;
}
step({ introspector } = {}) {
const lastRun = this.lastResult && typeof this.lastResult === 'object' ? this.lastResult : undefined;
const rerun = (0, helper_1.isRunning)(this.lastResult);
if (introspector) {
introspector.start(this);
}
this.lastResult = registryLookUp(this.tree).run(this.blackboard, {
lastRun,
introspector,
rerun,
registryLookUp
});
if (introspector) {
introspector.end();
}
}
static register(name, node) {
registry[name] = typeof node === 'function' ? new Task_1.default({ name, run: node }) : node;
}
static cleanRegistry() {
registry = {};
}
}
exports.default = BehaviorTree;