UNPKG

behaviortree

Version:

A JavaScript implementation of Behavior Trees. They are useful for implementing AIs. For Browsers and NodeJS.

61 lines (60 loc) 2.62 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const constants_1 = require("./constants"); const helper_1 = require("./helper"); const Node_1 = __importDefault(require("./Node")); class BranchNode extends Node_1.default { constructor(blueprint) { super(blueprint); // Override this in subclasses this.OPT_OUT_CASE = constants_1.SUCCESS; this.START_CASE = constants_1.SUCCESS; this.nodeType = 'BranchNode'; this.nodes = blueprint.nodes || []; this.numNodes = this.nodes.length; } run(blackboard = {}, { lastRun, introspector, rerun, registryLookUp = (x) => x } = {}) { if (!rerun) this.blueprint.start(blackboard); // eslint-disable-next-line @typescript-eslint/no-explicit-any let overallResult = this.START_CASE; const results = []; const lastRunStates = (typeof lastRun === 'object' && lastRun.state) || []; const startingIndex = Math.max(lastRunStates.findIndex((x) => (0, helper_1.isRunning)(x)), 0); let currentIndex = 0; for (; currentIndex < this.numNodes; ++currentIndex) { if (currentIndex < startingIndex) { // Keep last result results[currentIndex] = lastRunStates[currentIndex]; continue; } const node = registryLookUp(this.nodes[currentIndex]); const result = node.run(blackboard, { lastRun: lastRunStates[currentIndex], introspector, rerun, registryLookUp }); results[currentIndex] = result; if (result === constants_1.RUNNING || typeof result === 'object') { overallResult = constants_1.RUNNING; break; } else if (result === this.OPT_OUT_CASE) { overallResult = result; break; } else { rerun = false; } } const running = (0, helper_1.isRunning)(overallResult); if (!running) { this.blueprint.end(blackboard); } if (introspector) { const debugResult = running ? constants_1.RUNNING : overallResult; introspector.wrapLast(Math.min(currentIndex + 1, this.numNodes), this, debugResult, blackboard); } return overallResult === constants_1.RUNNING ? { total: overallResult, state: results } : overallResult; } } exports.default = BranchNode;