UNPKG

behaviortree

Version:

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

42 lines (41 loc) 1.65 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 BranchNode_1 = __importDefault(require("./BranchNode")); const helper_1 = require("./helper"); class Random extends BranchNode_1.default { constructor() { super(...arguments); this.nodeType = 'Random'; } run(blackboard = {}, { lastRun, introspector, rerun, registryLookUp = (x) => x } = {}) { let currentIndex = 0; if (rerun) { currentIndex = lastRun.state.findIndex((x) => (0, helper_1.isRunning)(x)); } else { this.blueprint.start(blackboard); currentIndex = Math.floor(Math.random() * this.numNodes); } const node = registryLookUp(this.nodes[currentIndex]); const result = node.run(blackboard, { lastRun, introspector, rerun, registryLookUp }); const running = (0, helper_1.isRunning)(result); if (!running) { this.blueprint.end(blackboard); } if (introspector) { const debugResult = running ? constants_1.RUNNING : result; introspector.wrapLast(1, this, debugResult, blackboard); } if (running) { const returningResult = { total: constants_1.RUNNING, state: new Array(this.numNodes).fill(undefined) }; returningResult.state[currentIndex] = result; return returningResult; } return result; } } exports.default = Random;