├── .editorconfig ├── .gitignore ├── .npmignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code-of-conduct.md ├── package.json ├── rollup.config.ts ├── src ├── behaviorTreeBuilder.ts ├── behaviorTreeStatus.ts ├── errors.ts ├── iBehaviorTreeNode.ts ├── iParentBehaviorTreeNode.ts ├── index.ts ├── nodes │ ├── actionNode.ts │ ├── inverterNode.ts │ ├── parallelNode.ts │ ├── selectorNode.ts │ └── sequenceNode.ts └── timeData.ts ├── test ├── behaviorTreeBuilder.test.ts └── nodes │ ├── inverterNode.test.ts │ ├── parallelNode.test.ts │ ├── selectorNode.test.ts │ └── sequanceNode.test.ts ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache 12 | docs 13 | tsconfig.json 14 | src 15 | tools -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | yarn: true 4 | directories: 5 | - ~/.npm 6 | notifications: 7 | email: false 8 | node_js: 9 | - '10' 10 | - '11' 11 | - '8' 12 | 13 | script: yarn run test:prod && yarn run report-coverage 14 | 15 | jobs: 16 | include: 17 | - stage: deploy 18 | if: branch = master 19 | script: 20 | - yarn build 21 | - yarn semantic-release 22 | - yarn deploy-docs 23 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/robinxb/behaviortree.js 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a Pull Request with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). 18 | Make sure all of your commits are atomic (one feature per commit). 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 robinxb 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ts-behavior-tree 2 | 3 | A javascript/typescript behaviour tree library implementation of [Fluent-Behaviour-Tree](https://github.com/codecapers/Fluent-Behaviour-Tree) 4 | 5 | [View Documented](https://robinxb.github.io/ts-behavior-tree) 6 | 7 | [![Travis](https://img.shields.io/travis/robinxb/ts-behavior-tree.svg)](https://travis-ci.org/robinxb/ts-behavior-tree) 8 | [![Coveralls](https://img.shields.io/coveralls/robinxb/ts-behavior-tree.svg)](https://coveralls.io/github/robinxb/ts-behavior-tree) 9 | [![npm version](https://badge.fury.io/js/ts-behavior-tree.svg)](https://badge.fury.io/js/ts-behavior-tree) 10 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 11 | 12 | Table of Contents 13 | - [ts-behavior-tree](#ts-behavior-tree) 14 | - [Motivation](#motivation) 15 | - [Feature](#feature) 16 | - [Installation](#installation) 17 | - [npm](#npm) 18 | - [yarn](#yarn) 19 | - [Scripts](#scripts) 20 | - [Usage](#usage) 21 | - [Development](#development) 22 | - [Clone the repository](#clone-the-repository) 23 | - [Use npm/yarn commands](#use-npmyarn-commands) 24 | 25 | ## Motivation 26 | 27 | Although there is another js/ts library for fluent-behaviour-tree, but it uses `async/promise` to accomplish. 28 | 29 | So I rewrite based on the origin C# implement. 🎉 30 | 31 | ## Feature 32 | 33 | * Pure ES5 34 | * Tiny (~5KB Minified) 35 | * Full [Documented](https://robinxb.github.io/ts-behavior-tree) 36 | * Zero dependency 37 | 38 | ## Installation 39 | 40 | ### npm 41 | 42 | ```bash 43 | npm install ts-behavior-tree 44 | ``` 45 | 46 | ### yarn 47 | 48 | ```bash 49 | yarn add ts-behavior-tree 50 | ``` 51 | 52 | ### Scripts 53 | 54 | This library is supported with multiple formats (UMD, ES5) 55 | 56 | You can get release versions of these from [releases page](https://github.com/robinxb/ts-behavior-tree/releases). 57 | 58 | ## Usage 59 | 60 | You can find examples from [test/BehaviorTreeBuilder.test.ts](https://github.com/robinxb/ts-behavior-tree/blob/master/test/behaviorTreeBuilder.test.ts). 61 | 62 | Here is a simple usage 63 | 64 | ```javascript 65 | import { BehaviorTreeBuilder, BehaviorTreeStatus, TimeData } from 'ts-behavior-tree' 66 | const node = new BehaviorTreeBuilder() 67 | .Sequence('aa') 68 | .Do('aa', () => BehaviorTreeStatus.Failure) 69 | .End() 70 | .Build() 71 | console.log(node.Tick(new TimeData()) === BehaviorTreeStatus.Failure) 72 | ``` 73 | 74 | 75 | ## Development 76 | 77 | ### Clone the repository 78 | 79 | ```bash 80 | git clone git@github.com:robinxb/ts-behavior-tree.git 81 | ``` 82 | 83 | ### Use npm/yarn commands 84 | 85 | * `npm t`: Run test suite 86 | * `npm start`: Runs `npm run build` in watch mode 87 | * `npm run test:watch`: Run test suite in [interactive watch mode](http://facebook.github.io/jest/docs/cli.html#watch) 88 | * `npm run test:prod`: Run linting and generate coverage 89 | * `npm run build`: Generate bundles and typings, create docs 90 | * `npm run lint`: Lints code 91 | * `npm run commit`: Commit using conventional commit style \([husky](https://github.com/typicode/husky) will tell you to use it if you haven't :wink:\) 92 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-behavior-tree", 3 | "version": "0.0.0-development", 4 | "description": "A javascript/typescript behaviour tree library", 5 | "keywords": [ 6 | "typescript", 7 | "javescript", 8 | "behaviour", 9 | "behavior", 10 | "tree" 11 | ], 12 | "main": "dist/ts-behavior-tree.umd.js", 13 | "module": "dist/ts-behavior-tree.es5.js", 14 | "typings": "dist/types/index.d.ts", 15 | "files": [ 16 | "dist" 17 | ], 18 | "author": "robinxb ", 19 | "repository": { 20 | "type": "git", 21 | "url": "https://github.com/robinxb/ts-behavior-tree.git" 22 | }, 23 | "license": "MIT", 24 | "engines": { 25 | "node": ">=8.0.0" 26 | }, 27 | "scripts": { 28 | "lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 29 | "prebuild": "rimraf dist", 30 | "build": "tsc --module commonjs && rollup -c rollup.config.ts && typedoc --out docs --target es6 --theme minimal --mode file src", 31 | "start": "rollup -c rollup.config.ts -w", 32 | "test": "jest --coverage", 33 | "test:watch": "jest --coverage --watch", 34 | "test:prod": "npm run lint && npm run test -- --no-cache", 35 | "deploy-docs": "ts-node tools/gh-pages-publish", 36 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 37 | "commit": "git-cz", 38 | "semantic-release": "semantic-release", 39 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 40 | "travis-deploy-once": "travis-deploy-once", 41 | "prepush": "npm run test:prod && npm run build", 42 | "commitmsg": "commitlint -E HUSKY_GIT_PARAMS" 43 | }, 44 | "lint-staged": { 45 | "{src,test}/**/*.ts": [ 46 | "prettier --write", 47 | "git add" 48 | ] 49 | }, 50 | "config": { 51 | "commitizen": { 52 | "path": "node_modules/cz-conventional-changelog" 53 | } 54 | }, 55 | "jest": { 56 | "transform": { 57 | ".(ts|tsx)": "ts-jest" 58 | }, 59 | "testEnvironment": "node", 60 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 61 | "moduleFileExtensions": [ 62 | "ts", 63 | "tsx", 64 | "js" 65 | ], 66 | "coveragePathIgnorePatterns": [ 67 | "/node_modules/", 68 | "/test/" 69 | ], 70 | "coverageThreshold": { 71 | "global": { 72 | "branches": 90, 73 | "functions": 95, 74 | "lines": 95, 75 | "statements": 95 76 | } 77 | }, 78 | "collectCoverageFrom": [ 79 | "src/**/*.{js,ts}" 80 | ] 81 | }, 82 | "prettier": { 83 | "semi": false, 84 | "singleQuote": true 85 | }, 86 | "commitlint": { 87 | "extends": [ 88 | "@commitlint/config-conventional" 89 | ] 90 | }, 91 | "devDependencies": { 92 | "@commitlint/cli": "^7.1.2", 93 | "@commitlint/config-conventional": "^7.1.2", 94 | "@types/jest": "^23.3.2", 95 | "@types/lodash.isundefined": "^3.0.6", 96 | "@types/node": "^10.11.0", 97 | "colors": "^1.3.2", 98 | "commitizen": "^3.0.0", 99 | "coveralls": "^3.0.2", 100 | "cross-env": "^5.2.0", 101 | "cz-conventional-changelog": "^2.1.0", 102 | "husky": "^1.0.1", 103 | "jest": "^23.6.0", 104 | "jest-config": "^23.6.0", 105 | "lint-staged": "^8.0.0", 106 | "lodash.camelcase": "^4.3.0", 107 | "lodash.isundefined": "^3.0.1", 108 | "prettier": "^1.14.3", 109 | "prompt": "^1.0.0", 110 | "replace-in-file": "^3.4.2", 111 | "rimraf": "^2.6.2", 112 | "rollup": "^0.67.0", 113 | "rollup-plugin-commonjs": "^9.1.8", 114 | "rollup-plugin-json": "^3.1.0", 115 | "rollup-plugin-node-resolve": "^3.4.0", 116 | "rollup-plugin-sourcemaps": "^0.4.2", 117 | "rollup-plugin-typescript2": "^0.18.0", 118 | "semantic-release": "^15.13.12", 119 | "shelljs": "^0.8.3", 120 | "travis-deploy-once": "^5.0.9", 121 | "ts-jest": "^23.10.2", 122 | "ts-node": "^7.0.1", 123 | "tslint": "^5.11.0", 124 | "tslint-config-prettier": "^1.15.0", 125 | "tslint-config-standard": "^8.0.1", 126 | "typedoc": "^0.12.0", 127 | "typescript": "^3.0.3", 128 | "typescript-collections": "^1.3.2" 129 | }, 130 | "husky": { 131 | "hooks": { 132 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", 133 | "pre-commit": "lint-staged", 134 | "pre-push": "npm run test:prod && npm run build" 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import resolve from 'rollup-plugin-node-resolve' 2 | import commonjs from 'rollup-plugin-commonjs' 3 | import sourceMaps from 'rollup-plugin-sourcemaps' 4 | import camelCase from 'lodash.camelcase' 5 | import typescript from 'rollup-plugin-typescript2' 6 | import json from 'rollup-plugin-json' 7 | 8 | const pkg = require('./package.json') 9 | 10 | const libraryName = 'ts-behavior-tree' 11 | 12 | export default { 13 | input: `src/index.ts`, 14 | output: [ 15 | { file: pkg.main, name: camelCase(libraryName), format: 'umd', sourcemap: true }, 16 | { file: pkg.module, format: 'es', sourcemap: true }, 17 | ], 18 | // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') 19 | watch: { 20 | include: 'src/**', 21 | }, 22 | plugins: [ 23 | // Allow json resolution 24 | json(), 25 | // Compile TypeScript files 26 | typescript({ useTsconfigDeclarationDir: true }), 27 | // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) 28 | commonjs({ 29 | include: /node_modules/, 30 | namedExports: { 31 | 'lodash': ['isNull', 'isUndefined'], 32 | } 33 | }), 34 | // Allow node_modules resolution, so you can use 'external' to control 35 | // which external modules to include in the bundle 36 | // https://github.com/rollup/rollup-plugin-node-resolve#usage 37 | resolve(), 38 | 39 | // Resolve source maps to the original source 40 | sourceMaps(), 41 | ], 42 | } 43 | -------------------------------------------------------------------------------- /src/behaviorTreeBuilder.ts: -------------------------------------------------------------------------------- 1 | import Stack from 'typescript-collections/dist/lib/Stack' 2 | import { TimeData } from './timeData' 3 | import { BehaviorTreeStatus } from './behaviorTreeStatus' 4 | import { IBehaviorTreeNode } from './iBehaviorTreeNode' 5 | import { ActionNode } from './nodes/actionNode' 6 | import { IParentBehaviorTreeNode } from './iParentBehaviorTreeNode' 7 | import { ParallelNode } from './nodes/parallelNode' 8 | import { InverterNode } from './nodes/inverterNode' 9 | import { SelectorNode } from './nodes/selectorNode' 10 | import isUndefined from 'lodash.isundefined' 11 | import { SequenceNode } from './nodes/sequenceNode' 12 | import { ErrUnnestedTree, ErrZeroNodes, ErrorSpliceUnnested } from './errors' 13 | 14 | /** 15 | * The builder of behavior tree 16 | * 17 | * Use [[End]] to complete build. 18 | * 19 | * Use [[Build]] to get an instance of root node. 20 | * 21 | * Basic usage example: 22 | * 23 | * ```ts 24 | * import {behaviorTreeBuilder} from 'ts-behavior-tree'; 25 | * let root = new behaviorTreeBuilder() 26 | * .Do('something', t => { 27 | * console.log(`Time updated: ${t}`); 28 | * } 29 | * ).end().build(); 30 | * ``` 31 | */ 32 | export class BehaviorTreeBuilder { 33 | curNode: IBehaviorTreeNode | undefined = undefined 34 | parentNodeStack: Stack = new Stack() 35 | 36 | /** 37 | * Create an action node. 38 | * @param name name of action node. 39 | * @param fn Things need to be executed. 40 | * @returns Builder itself. 41 | */ 42 | Do(name: string, fn: (timeData: TimeData) => BehaviorTreeStatus): BehaviorTreeBuilder { 43 | if (this.parentNodeStack.isEmpty()) { 44 | throw ErrUnnestedTree 45 | } 46 | let actionNode = new ActionNode(name, fn) 47 | this.parentNodeStack.peek()!.AddChild(actionNode) 48 | return this 49 | } 50 | 51 | /** 52 | * Like an action node, but the function can return true/false and is mapped to success/failure. 53 | * @param name name of this node. 54 | * @param fn Things need to be executed. 55 | * @returns Builder itself. 56 | */ 57 | Condition(name: string, fn: (timeData: TimeData) => boolean): BehaviorTreeBuilder { 58 | return this.Do(name, t => (fn(t) ? BehaviorTreeStatus.Success : BehaviorTreeStatus.Failure)) 59 | } 60 | 61 | /** 62 | * Create an inverter node that inverts the success/failure of its children. 63 | * @param name name of this node. 64 | * @returns Builder itself. 65 | */ 66 | Inverter(name: string): BehaviorTreeBuilder { 67 | let inverterNode = new InverterNode(name) 68 | if (!this.parentNodeStack.isEmpty()) { 69 | this.parentNodeStack.peek()!.AddChild(inverterNode) 70 | } 71 | this.parentNodeStack.push(inverterNode) 72 | return this 73 | } 74 | 75 | /** 76 | * Create a sequence node. 77 | * @param name 78 | * @returns Builder itself. 79 | */ 80 | Sequence(name: string): BehaviorTreeBuilder { 81 | let sequenceNode = new SequenceNode(name) 82 | if (!this.parentNodeStack.isEmpty()) { 83 | this.parentNodeStack.peek()!.AddChild(sequenceNode) 84 | } 85 | this.parentNodeStack.push(sequenceNode) 86 | return this 87 | } 88 | 89 | /** 90 | * Create a parallel node. 91 | * @param name name of this node. 92 | * @param numRequiredToFail If number of failures reaches this, then this node will return [[behaviorTreeStatus.Failure]] 93 | * @param numRequiredToSucceed If number of success reaches this, then this node will return [[behaviorTreeStatus.Success]] 94 | * @returns Builder itself. 95 | */ 96 | Parallel( 97 | name: string, 98 | numRequiredToFail: number, 99 | numRequiredToSucceed: number 100 | ): BehaviorTreeBuilder { 101 | let parallelNode = new ParallelNode(name, numRequiredToFail, numRequiredToSucceed) 102 | if (!this.parentNodeStack.isEmpty()) { 103 | this.parentNodeStack.peek()!.AddChild(parallelNode) 104 | } 105 | this.parentNodeStack.push(parallelNode) 106 | return this 107 | } 108 | 109 | /** 110 | * Create a selector node. 111 | * @param name name of this node. 112 | * @returns Builder itself. 113 | */ 114 | Selector(name: string): BehaviorTreeBuilder { 115 | let selectorNode = new SelectorNode(name) 116 | if (!this.parentNodeStack.isEmpty()) { 117 | this.parentNodeStack.peek()!.AddChild(selectorNode) 118 | } 119 | this.parentNodeStack.push(selectorNode) 120 | return this 121 | } 122 | 123 | /** 124 | * Splice a sub tree into the parent tree. 125 | * @param subTree sub tree that need to be added. 126 | * @returns Builder itself. 127 | */ 128 | Splice(subTree: IBehaviorTreeNode): BehaviorTreeBuilder { 129 | if (this.parentNodeStack.isEmpty()) { 130 | throw ErrorSpliceUnnested 131 | } 132 | 133 | this.parentNodeStack.peek()!.AddChild(subTree) 134 | return this 135 | } 136 | 137 | /** 138 | * Build the actual tree. 139 | * @returns Root node of this tree. 140 | */ 141 | Build(): IBehaviorTreeNode { 142 | if (isUndefined(this.curNode)) { 143 | throw ErrZeroNodes 144 | } 145 | return this.curNode 146 | } 147 | 148 | /** 149 | * Ends a sequence of children. 150 | * @returns Builder itself. 151 | */ 152 | End(): BehaviorTreeBuilder { 153 | this.curNode = this.parentNodeStack.pop() 154 | return this 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/behaviorTreeStatus.ts: -------------------------------------------------------------------------------- 1 | export enum BehaviorTreeStatus { 2 | Success, 3 | Failure, 4 | Running 5 | } 6 | -------------------------------------------------------------------------------- /src/errors.ts: -------------------------------------------------------------------------------- 1 | export const ErrUnnestedTree = new Error( 2 | "Can't create an unnested ActionNode, it must be a leaf node." 3 | ) 4 | export const ErrZeroNodes = new Error("Can't create a behavior tree with zero nodes") 5 | export const ErrInvNodeMustHaveChild = new Error(`InverterNode must have a child node!`) 6 | export const ErrInvNodeMoreThanOneChild = new Error( 7 | "Can't add more than a single child to InverterNode!" 8 | ) 9 | export const ErrorSpliceUnnested = new Error( 10 | 'Cannot splice an unnested sub-tree, there must be a parent-tree.' 11 | ) 12 | -------------------------------------------------------------------------------- /src/iBehaviorTreeNode.ts: -------------------------------------------------------------------------------- 1 | import { TimeData } from './timeData' 2 | import { BehaviorTreeStatus } from './behaviorTreeStatus' 3 | 4 | export interface IBehaviorTreeNode { 5 | Tick(timeData: TimeData): BehaviorTreeStatus 6 | } 7 | -------------------------------------------------------------------------------- /src/iParentBehaviorTreeNode.ts: -------------------------------------------------------------------------------- 1 | import { IBehaviorTreeNode } from './iBehaviorTreeNode' 2 | 3 | export interface IParentBehaviorTreeNode extends IBehaviorTreeNode { 4 | AddChild(child: IBehaviorTreeNode): void 5 | } 6 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './behaviorTreeBuilder' 2 | export * from './errors' 3 | export * from './behaviorTreeStatus' 4 | export * from './iBehaviorTreeNode' 5 | export * from './iParentBehaviorTreeNode' 6 | export * from './timeData' 7 | export * from './nodes/actionNode' 8 | export * from './nodes/inverterNode' 9 | export * from './nodes/parallelNode' 10 | export * from './nodes/selectorNode' 11 | export * from './nodes/sequenceNode' 12 | -------------------------------------------------------------------------------- /src/nodes/actionNode.ts: -------------------------------------------------------------------------------- 1 | import { TimeData } from '../timeData' 2 | import { BehaviorTreeStatus } from '../behaviorTreeStatus' 3 | import { IBehaviorTreeNode } from '../iBehaviorTreeNode' 4 | 5 | export class ActionNode implements IBehaviorTreeNode { 6 | private name: string 7 | private fn: (timeData: TimeData) => BehaviorTreeStatus 8 | 9 | constructor(name: string, fn: (timeData: TimeData) => BehaviorTreeStatus) { 10 | this.name = name 11 | this.fn = fn 12 | } 13 | 14 | Tick(time: TimeData) { 15 | return this.fn(time) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/nodes/inverterNode.ts: -------------------------------------------------------------------------------- 1 | import { TimeData } from '../timeData' 2 | import { BehaviorTreeStatus } from '../behaviorTreeStatus' 3 | import { IBehaviorTreeNode } from '../iBehaviorTreeNode' 4 | import { IParentBehaviorTreeNode } from '../iParentBehaviorTreeNode' 5 | import isUndefined from 'lodash.isundefined' 6 | import { ErrInvNodeMustHaveChild, ErrInvNodeMoreThanOneChild } from '../errors' 7 | 8 | export class InverterNode implements IParentBehaviorTreeNode { 9 | private name: string 10 | private childNode: IBehaviorTreeNode | undefined 11 | 12 | constructor(name: string) { 13 | this.name = name 14 | } 15 | 16 | Tick(time: TimeData) { 17 | if (isUndefined(this.childNode)) { 18 | throw ErrInvNodeMustHaveChild 19 | } 20 | 21 | let result = this.childNode.Tick(time) 22 | if (result === BehaviorTreeStatus.Failure) { 23 | return BehaviorTreeStatus.Success 24 | } else if (result === BehaviorTreeStatus.Success) { 25 | return BehaviorTreeStatus.Failure 26 | } else { 27 | return BehaviorTreeStatus.Running 28 | } 29 | } 30 | 31 | /** 32 | * Add a child to the parent node. 33 | * @param child Child needs to be added. 34 | */ 35 | AddChild(child: IBehaviorTreeNode) { 36 | if (!isUndefined(this.childNode)) { 37 | throw ErrInvNodeMoreThanOneChild 38 | } 39 | 40 | this.childNode = child 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/nodes/parallelNode.ts: -------------------------------------------------------------------------------- 1 | import { IParentBehaviorTreeNode } from '../iParentBehaviorTreeNode' 2 | import LinkedList from 'typescript-collections/dist/lib/LinkedList' 3 | import { IBehaviorTreeNode } from '../iBehaviorTreeNode' 4 | import { TimeData } from '../timeData' 5 | import { BehaviorTreeStatus } from '../behaviorTreeStatus' 6 | 7 | /** 8 | * Sequence node 9 | * 10 | * Runs child nodes in sequence, until one fails. 11 | */ 12 | export class ParallelNode implements IParentBehaviorTreeNode { 13 | private name: string 14 | private children: LinkedList = new LinkedList() 15 | private numRequiredToFail: number 16 | private numRequiredToSucceed: number 17 | 18 | constructor(name: string, numRequiredToFail: number, numRequiredToSucceed: number) { 19 | this.name = name 20 | this.numRequiredToFail = numRequiredToFail 21 | this.numRequiredToSucceed = numRequiredToSucceed 22 | } 23 | 24 | Tick(time: TimeData) { 25 | let numChildrenSuceeded = 0 26 | let numChildrenFailed = 0 27 | 28 | this.children.forEach(child => { 29 | let childStatus = child.Tick(time) 30 | switch (childStatus) { 31 | case BehaviorTreeStatus.Success: 32 | ++numChildrenSuceeded 33 | break 34 | case BehaviorTreeStatus.Failure: 35 | ++numChildrenFailed 36 | break 37 | } 38 | }) 39 | 40 | if (numChildrenSuceeded > 0 && numChildrenSuceeded >= this.numRequiredToSucceed) { 41 | return BehaviorTreeStatus.Success 42 | } 43 | 44 | if (numChildrenFailed > 0 && numChildrenFailed >= this.numRequiredToFail) { 45 | return BehaviorTreeStatus.Failure 46 | } 47 | return BehaviorTreeStatus.Running 48 | } 49 | 50 | AddChild(child: IBehaviorTreeNode) { 51 | this.children.add(child) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/nodes/selectorNode.ts: -------------------------------------------------------------------------------- 1 | import { TimeData } from '../timeData' 2 | import { BehaviorTreeStatus } from '../behaviorTreeStatus' 3 | import { IBehaviorTreeNode } from '../iBehaviorTreeNode' 4 | import { IParentBehaviorTreeNode } from '../iParentBehaviorTreeNode' 5 | import * as _ from 'lodash' 6 | import LinkedList from 'typescript-collections/dist/lib/LinkedList' 7 | 8 | export class SelectorNode implements IParentBehaviorTreeNode { 9 | /** 10 | * List of child nodes. 11 | */ 12 | private children: LinkedList = new LinkedList() 13 | 14 | constructor(private name: string) {} 15 | 16 | Tick(time: TimeData) { 17 | let childStatus = BehaviorTreeStatus.Failure 18 | this.children.forEach(child => { 19 | childStatus = child.Tick(time) 20 | if (childStatus !== BehaviorTreeStatus.Failure) { 21 | return false 22 | } 23 | }) 24 | return childStatus 25 | } 26 | 27 | /** 28 | * Add a child to the parent node. 29 | * @param child Child needs to be added. 30 | */ 31 | AddChild(child: IBehaviorTreeNode) { 32 | this.children.add(child) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/nodes/sequenceNode.ts: -------------------------------------------------------------------------------- 1 | import { TimeData } from '../timeData' 2 | import { BehaviorTreeStatus } from '../behaviorTreeStatus' 3 | import { IBehaviorTreeNode } from '../iBehaviorTreeNode' 4 | import LinkedList from 'typescript-collections/dist/lib/LinkedList' 5 | import { IParentBehaviorTreeNode } from '../iParentBehaviorTreeNode' 6 | 7 | /** 8 | * Sequence node 9 | * 10 | * Runs child nodes in sequence, until one fails. 11 | */ 12 | export class SequenceNode implements IParentBehaviorTreeNode { 13 | /** 14 | * Name of the node. 15 | */ 16 | private name: string 17 | 18 | /** 19 | * List of child nodes. 20 | */ 21 | private children: LinkedList = new LinkedList() 22 | 23 | constructor(name: string) { 24 | this.name = name 25 | } 26 | 27 | /** 28 | * Add a child to the sequence. 29 | * 30 | * @param child Child added to sequence. 31 | */ 32 | AddChild(child: IBehaviorTreeNode) { 33 | this.children.add(child) 34 | } 35 | 36 | /** 37 | * Tick update 38 | * @param time Delta time since last tick 39 | * @returns 40 | */ 41 | Tick(time: TimeData) { 42 | let childStatus = BehaviorTreeStatus.Success 43 | this.children.forEach(child => { 44 | childStatus = child.Tick(time) 45 | if (childStatus !== BehaviorTreeStatus.Success) { 46 | return false 47 | } 48 | }) 49 | return childStatus 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/timeData.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Delta time used by all nodes 3 | */ 4 | export class TimeData { 5 | deltaTime: number 6 | /** 7 | * Creates an instance of time data. 8 | * @param deltaTime Delta time 9 | */ 10 | constructor(deltaTime: number = 1) { 11 | this.deltaTime = deltaTime 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/behaviorTreeBuilder.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BehaviorTreeBuilder, 3 | BehaviorTreeStatus, 4 | InverterNode, 5 | TimeData, 6 | SequenceNode, 7 | ParallelNode, 8 | SelectorNode 9 | } from '../src/index' 10 | import { 11 | ErrZeroNodes, 12 | ErrUnnestedTree, 13 | ErrInvNodeMoreThanOneChild, 14 | ErrorSpliceUnnested 15 | } from '../src/errors' 16 | 17 | let testObject: BehaviorTreeBuilder 18 | 19 | beforeEach(() => { 20 | testObject = new BehaviorTreeBuilder() 21 | }) 22 | 23 | test('cant create a behavior tree with zero nodes', () => { 24 | expect(() => testObject.Build()).toThrow(ErrZeroNodes) 25 | }) 26 | 27 | test('cant create an unested action node', () => { 28 | expect(() => testObject.Do('some-node-1', t => BehaviorTreeStatus.Running).Build()).toThrow( 29 | ErrUnnestedTree 30 | ) 31 | }) 32 | 33 | test('can create inverter node', () => { 34 | let node = testObject 35 | .Inverter('inv') 36 | .Do('some-node', t => BehaviorTreeStatus.Success) 37 | .End() 38 | .Build() 39 | expect(node).toBeInstanceOf(InverterNode) 40 | expect(node.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Failure) 41 | }) 42 | 43 | test('cant create an unbalanced behavior tree', () => { 44 | expect(() => 45 | testObject 46 | .Inverter('inv') 47 | .Do('some-node', t => BehaviorTreeStatus.Success) 48 | .Build() 49 | ).toThrowError(ErrZeroNodes) 50 | }) 51 | 52 | test('condition is syntactic sugar for do', () => { 53 | let returnFn = jest 54 | .fn() 55 | .mockReturnValueOnce(true) 56 | .mockReturnValue(false) 57 | let node = testObject 58 | .Inverter('inv') 59 | .Condition('some-node', t => returnFn()) 60 | .End() 61 | .Build() 62 | expect(node).toBeInstanceOf(InverterNode) 63 | expect(node.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Failure) 64 | expect(node.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Success) 65 | }) 66 | 67 | test('can invert an inverter', () => { 68 | let node = testObject 69 | .Inverter('inv') 70 | .Inverter('some-inverter') 71 | .Inverter('some-other-inverter') 72 | .Do('some-node', t => BehaviorTreeStatus.Success) 73 | .End() 74 | .End() 75 | .Build() 76 | expect(node).toBeInstanceOf(InverterNode) 77 | expect(node.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Success) 78 | }) 79 | 80 | test('adding more than a single child to inverter throws exception', () => { 81 | expect(() => 82 | testObject 83 | .Inverter('inv') 84 | .Do('some-node', t => BehaviorTreeStatus.Success) 85 | .Do('some-node', t => BehaviorTreeStatus.Success) 86 | .End() 87 | .Build() 88 | ).toThrowError(ErrInvNodeMoreThanOneChild) 89 | }) 90 | 91 | test('can create a sequance', () => { 92 | let invokeCount = 0 93 | let sequance = testObject 94 | .Sequence('some-sequance') 95 | .Do('some-action-1', t => { 96 | ++invokeCount 97 | return BehaviorTreeStatus.Success 98 | }) 99 | .Do('some-action-2', t => { 100 | ++invokeCount 101 | return BehaviorTreeStatus.Success 102 | }) 103 | .End() 104 | .Build() 105 | 106 | expect(sequance).toBeInstanceOf(SequenceNode) 107 | expect(sequance.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Success) 108 | expect(invokeCount).toEqual(2) 109 | }) 110 | 111 | test('can create parallel', () => { 112 | let invokeCount = 0 113 | let parallel = testObject 114 | .Parallel('some-parallel', 2, 2) 115 | .Do('some-action-1', t => { 116 | ++invokeCount 117 | return BehaviorTreeStatus.Success 118 | }) 119 | .Do('some-action-2', t => { 120 | ++invokeCount 121 | return BehaviorTreeStatus.Success 122 | }) 123 | .End() 124 | .Build() 125 | 126 | expect(parallel).toBeInstanceOf(ParallelNode) 127 | expect(parallel.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Success) 128 | expect(invokeCount).toEqual(2) 129 | }) 130 | 131 | test('can create selector', () => { 132 | let invokeCount = 0 133 | let selector = testObject 134 | .Selector('some-selector') 135 | .Do('some-action-1', t => { 136 | ++invokeCount 137 | return BehaviorTreeStatus.Failure 138 | }) 139 | .Do('some-action-2', t => { 140 | ++invokeCount 141 | return BehaviorTreeStatus.Success 142 | }) 143 | .End() 144 | .Build() 145 | 146 | expect(selector).toBeInstanceOf(SelectorNode) 147 | expect(selector.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Success) 148 | expect(invokeCount).toEqual(2) 149 | }) 150 | 151 | test('can splice sub tree', () => { 152 | let invokeCount = 0 153 | let spliced = testObject 154 | .Sequence('spliced') 155 | .Do('test', t => { 156 | ++invokeCount 157 | return BehaviorTreeStatus.Success 158 | }) 159 | .End() 160 | .Build() 161 | 162 | let tree = testObject 163 | .Sequence('parent-tree') 164 | .Splice(spliced) 165 | .End() 166 | .Build() 167 | 168 | expect(() => tree.Tick(new TimeData())).not.toThrow() 169 | expect(invokeCount).toEqual(1) 170 | }) 171 | 172 | test('parent node stack test', () => { 173 | const testfn = jest.fn() 174 | let node = testObject 175 | .Sequence('some-seq') 176 | .Do('test1', t => BehaviorTreeStatus.Success) 177 | .Sequence('some-seq-2') 178 | .Do('test2', t => BehaviorTreeStatus.Success) 179 | .Selector('sel') 180 | .Parallel('some-parral', 2, 2) 181 | .Do('pa-sub-1', t => BehaviorTreeStatus.Failure) 182 | .Do('pa-sub-2', t => BehaviorTreeStatus.Failure) 183 | .End() 184 | .Do('sel-sub-1', t => { 185 | testfn() 186 | return BehaviorTreeStatus.Failure 187 | }) 188 | .Do('sel-sub-2', t => BehaviorTreeStatus.Running) 189 | .End() 190 | .End() 191 | .End() 192 | .Build() 193 | 194 | expect(node.Tick(new TimeData())).toEqual(BehaviorTreeStatus.Running) 195 | expect(testfn).toBeCalledTimes(1) 196 | }) 197 | 198 | test('splice an unnested sub tree throws exception', () => { 199 | let spliced = testObject 200 | .Sequence('spliced') 201 | .Do('test', t => { 202 | return BehaviorTreeStatus.Success 203 | }) 204 | .End() 205 | .Build() 206 | 207 | expect(() => testObject.Splice(spliced)).toThrow(ErrorSpliceUnnested) 208 | }) 209 | -------------------------------------------------------------------------------- /test/nodes/inverterNode.test.ts: -------------------------------------------------------------------------------- 1 | import { BehaviorTreeStatus, TimeData, InverterNode, IBehaviorTreeNode } from '../../src/index' 2 | 3 | import { ErrInvNodeMustHaveChild, ErrInvNodeMoreThanOneChild } from '../../src/errors' 4 | 5 | let testObject: InverterNode 6 | 7 | beforeEach(() => { 8 | testObject = new InverterNode('inv') 9 | }) 10 | 11 | test('ticking with no child node throws exception', () => { 12 | expect(() => testObject.Tick(new TimeData())).toThrowError(ErrInvNodeMustHaveChild) 13 | }) 14 | 15 | test('inverts success of child node', () => { 16 | const time = new TimeData(1) 17 | 18 | const mockChild = jest.fn(() => ({ 19 | Tick: jest.fn(() => { 20 | return BehaviorTreeStatus.Success 21 | }) 22 | }))() 23 | testObject.AddChild(mockChild) 24 | 25 | expect(BehaviorTreeStatus.Failure).toEqual(testObject.Tick(time)) 26 | expect(mockChild.Tick).toBeCalledTimes(1) 27 | }) 28 | 29 | test('inverts failure of child node', () => { 30 | const time = new TimeData() 31 | 32 | const mockChild = jest.fn(() => ({ 33 | Tick: jest.fn(() => { 34 | return BehaviorTreeStatus.Failure 35 | }) 36 | }))() 37 | testObject.AddChild(mockChild) 38 | 39 | expect(BehaviorTreeStatus.Success).toEqual(testObject.Tick(time)) 40 | expect(mockChild.Tick).toBeCalledTimes(1) 41 | }) 42 | 43 | test('pass through running of child node', () => { 44 | const time = new TimeData() 45 | 46 | const mockChild = jest.fn(() => ({ 47 | Tick: jest.fn(() => { 48 | return BehaviorTreeStatus.Running 49 | }) 50 | }))() 51 | testObject.AddChild(mockChild) 52 | 53 | expect(BehaviorTreeStatus.Running).toEqual(testObject.Tick(time)) 54 | expect(mockChild.Tick).toBeCalledTimes(1) 55 | }) 56 | 57 | test('adding more than a single child throws exception', () => { 58 | const time = new TimeData() 59 | 60 | const mockChild1 = jest.fn(() => ({ 61 | Tick: jest.fn(() => { 62 | return BehaviorTreeStatus.Running 63 | }) 64 | }))() 65 | const mockChild2 = jest.fn(() => ({ 66 | Tick: jest.fn(() => { 67 | return BehaviorTreeStatus.Running 68 | }) 69 | }))() 70 | testObject.AddChild(mockChild1) 71 | expect(() => testObject.AddChild(mockChild2)).toThrowError(ErrInvNodeMoreThanOneChild) 72 | }) 73 | -------------------------------------------------------------------------------- /test/nodes/parallelNode.test.ts: -------------------------------------------------------------------------------- 1 | import { BehaviorTreeStatus, TimeData, ParallelNode, IBehaviorTreeNode } from '../../src/index' 2 | 3 | let testObject: ParallelNode 4 | 5 | beforeEach(() => { 6 | testObject = new ParallelNode('p', 2, 2) 7 | }) 8 | 9 | test('runs all nodes in order', () => { 10 | const time = new TimeData() 11 | let callOrder = 0 12 | const mockChild1 = jest.fn(() => ({ 13 | Tick: jest.fn(() => { 14 | expect(1).toEqual(++callOrder) 15 | return BehaviorTreeStatus.Running 16 | }) 17 | }))() 18 | const mockChild2 = jest.fn(() => ({ 19 | Tick: jest.fn(() => { 20 | expect(2).toEqual(++callOrder) 21 | return BehaviorTreeStatus.Running 22 | }) 23 | }))() 24 | testObject.AddChild(mockChild1) 25 | testObject.AddChild(mockChild2) 26 | expect(BehaviorTreeStatus.Running).toEqual(testObject.Tick(time)) 27 | expect(2).toEqual(callOrder) 28 | expect(mockChild1.Tick).toBeCalledTimes(1) 29 | expect(mockChild2.Tick).toBeCalledTimes(1) 30 | }) 31 | 32 | test('fails when required number of children fail', () => { 33 | const time = new TimeData() 34 | 35 | const mockChild1 = jest.fn(() => ({ 36 | Tick: jest.fn(() => { 37 | return BehaviorTreeStatus.Failure 38 | }) 39 | }))() 40 | const mockChild2 = jest.fn(() => ({ 41 | Tick: jest.fn(() => { 42 | return BehaviorTreeStatus.Failure 43 | }) 44 | }))() 45 | const mockChild3 = jest.fn(() => ({ 46 | Tick: jest.fn(() => { 47 | return BehaviorTreeStatus.Running 48 | }) 49 | }))() 50 | testObject.AddChild(mockChild1) 51 | testObject.AddChild(mockChild2) 52 | testObject.AddChild(mockChild3) 53 | 54 | expect(BehaviorTreeStatus.Failure).toEqual(testObject.Tick(time)) 55 | 56 | expect(mockChild1.Tick).toBeCalledTimes(1) 57 | expect(mockChild2.Tick).toBeCalledTimes(1) 58 | expect(mockChild3.Tick).toBeCalledTimes(1) 59 | }) 60 | 61 | test('succeeds when required number of children succeed', () => { 62 | const time = new TimeData() 63 | 64 | const mockChild1 = jest.fn(() => ({ 65 | Tick: jest.fn(() => { 66 | return BehaviorTreeStatus.Success 67 | }) 68 | }))() 69 | const mockChild2 = jest.fn(() => ({ 70 | Tick: jest.fn(() => { 71 | return BehaviorTreeStatus.Success 72 | }) 73 | }))() 74 | const mockChild3 = jest.fn(() => ({ 75 | Tick: jest.fn(() => { 76 | return BehaviorTreeStatus.Success 77 | }) 78 | }))() 79 | testObject.AddChild(mockChild1) 80 | testObject.AddChild(mockChild2) 81 | testObject.AddChild(mockChild3) 82 | 83 | expect(BehaviorTreeStatus.Success).toEqual(testObject.Tick(time)) 84 | 85 | expect(mockChild1.Tick).toBeCalledTimes(1) 86 | expect(mockChild2.Tick).toBeCalledTimes(1) 87 | expect(mockChild3.Tick).toBeCalledTimes(1) 88 | }) 89 | 90 | test('continues to run if the required number of children neither succeed or fail', () => { 91 | const time = new TimeData() 92 | 93 | const mockChild1 = jest.fn(() => ({ 94 | Tick: jest.fn(() => { 95 | return BehaviorTreeStatus.Success 96 | }) 97 | }))() 98 | const mockChild2 = jest.fn(() => ({ 99 | Tick: jest.fn(() => { 100 | return BehaviorTreeStatus.Failure 101 | }) 102 | }))() 103 | 104 | testObject.AddChild(mockChild1) 105 | testObject.AddChild(mockChild2) 106 | 107 | expect(BehaviorTreeStatus.Running).toEqual(testObject.Tick(time)) 108 | 109 | expect(mockChild1.Tick).toBeCalledTimes(1) 110 | expect(mockChild2.Tick).toBeCalledTimes(1) 111 | }) 112 | -------------------------------------------------------------------------------- /test/nodes/selectorNode.test.ts: -------------------------------------------------------------------------------- 1 | import { BehaviorTreeStatus, TimeData, SelectorNode, IBehaviorTreeNode } from '../../src/index' 2 | 3 | let testObject: SelectorNode 4 | beforeEach(() => { 5 | testObject = new SelectorNode('selector') 6 | }) 7 | 8 | test('runs the first node if it succeeds', () => { 9 | const time = new TimeData() 10 | const mockChild1 = jest.fn(() => ({ 11 | Tick: jest.fn(() => { 12 | return BehaviorTreeStatus.Success 13 | }) 14 | }))() 15 | const mockChild2 = jest.fn(() => ({ 16 | Tick: jest.fn(() => { 17 | return BehaviorTreeStatus.Running 18 | }) 19 | }))() 20 | testObject.AddChild(mockChild1) 21 | testObject.AddChild(mockChild2) 22 | expect(BehaviorTreeStatus.Success).toEqual(testObject.Tick(time)) 23 | expect(mockChild1.Tick).toBeCalledTimes(1) 24 | expect(mockChild2.Tick).not.toBeCalled() 25 | }) 26 | 27 | test('stops on the first node when it is running', () => { 28 | const time = new TimeData() 29 | const mockChild1 = jest.fn(() => ({ 30 | Tick: jest.fn(() => { 31 | return BehaviorTreeStatus.Running 32 | }) 33 | }))() 34 | const mockChild2 = jest.fn(() => ({ 35 | Tick: jest.fn(() => { 36 | return BehaviorTreeStatus.Failure 37 | }) 38 | }))() 39 | testObject.AddChild(mockChild1) 40 | testObject.AddChild(mockChild2) 41 | expect(BehaviorTreeStatus.Running).toEqual(testObject.Tick(time)) 42 | expect(mockChild1.Tick).toBeCalledTimes(1) 43 | expect(mockChild2.Tick).not.toBeCalled() 44 | }) 45 | 46 | test('runs the second node if the first fails', () => { 47 | const time = new TimeData() 48 | const mockChild1 = jest.fn(() => ({ 49 | Tick: jest.fn(() => { 50 | return BehaviorTreeStatus.Failure 51 | }) 52 | }))() 53 | const mockChild2 = jest.fn(() => ({ 54 | Tick: jest.fn(() => { 55 | return BehaviorTreeStatus.Success 56 | }) 57 | }))() 58 | testObject.AddChild(mockChild1) 59 | testObject.AddChild(mockChild2) 60 | expect(BehaviorTreeStatus.Success).toEqual(testObject.Tick(time)) 61 | expect(mockChild1.Tick).toBeCalledTimes(1) 62 | expect(mockChild2.Tick).toBeCalledTimes(1) 63 | }) 64 | 65 | test('fails when all children fail', () => { 66 | const time = new TimeData() 67 | const mockChild1 = jest.fn(() => ({ 68 | Tick: jest.fn(() => { 69 | return BehaviorTreeStatus.Failure 70 | }) 71 | }))() 72 | const mockChild2 = jest.fn(() => ({ 73 | Tick: jest.fn(() => { 74 | return BehaviorTreeStatus.Failure 75 | }) 76 | }))() 77 | testObject.AddChild(mockChild1) 78 | testObject.AddChild(mockChild2) 79 | expect(BehaviorTreeStatus.Failure).toEqual(testObject.Tick(time)) 80 | expect(mockChild1.Tick).toBeCalledTimes(1) 81 | expect(mockChild2.Tick).toBeCalledTimes(1) 82 | }) 83 | -------------------------------------------------------------------------------- /test/nodes/sequanceNode.test.ts: -------------------------------------------------------------------------------- 1 | import { BehaviorTreeStatus, TimeData, IBehaviorTreeNode, SequenceNode } from '../../src/index' 2 | 3 | let testObject: SequenceNode 4 | beforeEach(() => { 5 | testObject = new SequenceNode('selector') 6 | }) 7 | 8 | test('can_run_all_children_in_order', () => { 9 | const time = new TimeData() 10 | let callOrder = 0 11 | const mockChild1 = jest.fn(() => ({ 12 | Tick: jest.fn(() => { 13 | expect(++callOrder).toEqual(1) 14 | return BehaviorTreeStatus.Success 15 | }) 16 | }))() 17 | const mockChild2 = jest.fn(() => ({ 18 | Tick: jest.fn(() => { 19 | expect(++callOrder).toEqual(2) 20 | return BehaviorTreeStatus.Success 21 | }) 22 | }))() 23 | testObject.AddChild(mockChild1) 24 | testObject.AddChild(mockChild2) 25 | expect(BehaviorTreeStatus.Success).toEqual(testObject.Tick(time)) 26 | 27 | expect(2).toEqual(callOrder) 28 | expect(mockChild1.Tick).toBeCalledTimes(1) 29 | expect(mockChild2.Tick).toBeCalledTimes(1) 30 | }) 31 | 32 | test('when first child is running second child is supressed', () => { 33 | const time = new TimeData() 34 | const mockChild1 = jest.fn(() => ({ 35 | Tick: jest.fn(() => { 36 | return BehaviorTreeStatus.Running 37 | }) 38 | }))() 39 | const mockChild2 = jest.fn(() => ({ 40 | Tick: jest.fn(() => { 41 | return BehaviorTreeStatus.Success 42 | }) 43 | }))() 44 | testObject.AddChild(mockChild1) 45 | testObject.AddChild(mockChild2) 46 | 47 | expect(BehaviorTreeStatus.Running).toEqual(testObject.Tick(time)) 48 | 49 | expect(mockChild1.Tick).toBeCalledTimes(1) 50 | expect(mockChild2.Tick).not.toBeCalled() 51 | }) 52 | 53 | test('when first child fails then entire sequence fails', () => { 54 | const time = new TimeData() 55 | const mockChild1 = jest.fn(() => ({ 56 | Tick: jest.fn(() => { 57 | return BehaviorTreeStatus.Failure 58 | }) 59 | }))() 60 | const mockChild2 = jest.fn(() => ({ 61 | Tick: jest.fn(() => { 62 | return BehaviorTreeStatus.Success 63 | }) 64 | }))() 65 | testObject.AddChild(mockChild1) 66 | testObject.AddChild(mockChild2) 67 | 68 | expect(BehaviorTreeStatus.Failure).toEqual(testObject.Tick(time)) 69 | 70 | expect(mockChild1.Tick).toBeCalledTimes(1) 71 | expect(mockChild2.Tick).not.toBeCalled() 72 | }) 73 | 74 | test('when second child fails then entire sequence fails', () => { 75 | const time = new TimeData() 76 | const mockChild1 = jest.fn(() => ({ 77 | Tick: jest.fn(() => { 78 | return BehaviorTreeStatus.Success 79 | }) 80 | }))() 81 | const mockChild2 = jest.fn(() => ({ 82 | Tick: jest.fn(() => { 83 | return BehaviorTreeStatus.Failure 84 | }) 85 | }))() 86 | testObject.AddChild(mockChild1) 87 | testObject.AddChild(mockChild2) 88 | 89 | expect(BehaviorTreeStatus.Failure).toEqual(testObject.Tick(time)) 90 | 91 | expect(mockChild1.Tick).toBeCalledTimes(1) 92 | expect(mockChild2.Tick).toBeCalledTimes(1) 93 | }) 94 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name "robinxb"') 26 | exec('git config user.email "84084888@qq.com"') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install']) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module":"es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "declarationDir": "dist/types", 14 | "esModuleInterop": true, 15 | "outDir": "dist/lib", 16 | "typeRoots": [ 17 | "node_modules/@types" 18 | ] 19 | }, 20 | "include": [ 21 | "src" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ] 6 | } --------------------------------------------------------------------------------