behavior_tree 0.1.6 → 0.1.10

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0a4f19e223d0e39d51558ee95ed5460a3f7d8926a04b11c2fe12a0ef0272d582
4
- data.tar.gz: 4f509e2ecf9b800040a149eed00c6673d49b2a74acf2eefa2d1046e28823aeb0
3
+ metadata.gz: da63d959db3394cf36424a76f36a06d4b30c3ccd97e2f8a0c2dbfabff0b55819
4
+ data.tar.gz: d433e361299388c9ad10c2c51f20a71a39dc66927939b748486633f3d3cad645
5
5
  SHA512:
6
- metadata.gz: 7f7ad33a93c569942a770f2bc938a1118c6a4e252af877356fbf732cb643ce593b6524ab4f612ecfd9ab673504d57bb354a162214a63ce710663ec424d48baff
7
- data.tar.gz: ffbc970ed1ebb83d6fd271eb7ebf3cb0aad2d219c7c941f4420d5b811220c0a16b34943bf961099a5a393987ab22b3a2a3a649065cac08dcaa06275108aa6cc7
6
+ metadata.gz: 4d7bc4c9956c6b9228bff0c87f843543ab933ad1e58a94f47f83421426eebd56cf91d6e15325eef15359716dce0ac56c6fff0aac0b5ba90b18a077d2a02a25f2
7
+ data.tar.gz: 53b998db96a7976336ecb1fc3e6e0315def2c97485aeedfb40fd3d03abc1ec654b781e32f7bc1df14a413f9a3ca8fceb83ec3241f46dd3b1db73d2ac0d1e8444
data/.rubocop.yml CHANGED
@@ -1,3 +1,4 @@
1
+ # require: rubocop-rspec
1
2
  AllCops:
2
3
  TargetRubyVersion: 2.6
3
4
  NewCops: enable
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- behavior_tree (0.1.6)
4
+ behavior_tree (0.1.10)
5
5
  colorize (~> 0.8.1)
6
6
 
7
7
  GEM
@@ -69,4 +69,4 @@ DEPENDENCIES
69
69
  simplecov
70
70
 
71
71
  BUNDLED WITH
72
- 2.1.2
72
+ 2.2.23
data/README.md CHANGED
@@ -1,50 +1,836 @@
1
- # Ruby Behavior Tree
1
+ # Behavior Tree
2
2
 
3
- ![](https://api.travis-ci.com/FeloVilches/Ruby-Behavior-Tree.svg?branch=main)
3
+ [![Travis CI](https://api.travis-ci.com/FeloVilches/Ruby-Behavior-Tree.svg?branch=main)](https://travis-ci.org/github/FeloVilches/Ruby-Behavior-Tree) [![Gem Version](https://badge.fury.io/rb/behavior_tree.svg)](https://rubygems.org/gems/behavior_tree)
4
4
 
5
- ============
5
+ A robust and customizable Ruby gem for creating Behavior Trees, used in games, AI, robotics, and more.
6
6
 
7
- (Copy from the auto-generated readme file. Some names changed, so some things are incorrect.)
7
+ <p align="center">
8
+ <img src="https://github.com/FeloVilches/ruby-behavior-tree/blob/main/assets/logo.png?raw=true" />
9
+ </p>
8
10
 
9
- WIP
11
+ ## Quick start
10
12
 
11
- ============
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'behavior_tree'
17
+ ```
18
+
19
+ And then execute:
12
20
 
13
- # Ruby::Behavior::Tree
21
+ $ bundle install
14
22
 
15
- Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/ruby/behavior/tree`. To experiment with that code, run `bin/console` for an interactive prompt.
23
+ Or install it yourself as:
16
24
 
17
- TODO: Delete this and the text above, and describe your gem
25
+ $ gem install behavior_tree
18
26
 
19
- ## Installation
27
+ ### Build your first tree
20
28
 
21
- Add this line to your application's Gemfile:
29
+ Require the gem if necessary:
22
30
 
23
31
  ```ruby
24
- gem 'ruby-behavior-tree'
32
+ require 'behavior_tree'
25
33
  ```
26
34
 
27
- And then execute:
35
+ Create a tree using the DSL:
28
36
 
29
- $ bundle install
37
+ ```ruby
38
+ my_tree = BehaviorTree::Builder.build do
39
+ sequence do
40
+ task {
41
+ puts "I'm a task!"
42
+ status.success!
43
+ }
44
+ condition ->(context) { context[:some_value] < 200 } do
45
+ task {
46
+ context[:some_value] += 1
47
+ status.success!
48
+ }
49
+ end
50
+ task { context[:some_value] > 100 ? status.failure! : status.success! }
51
+ end
52
+ end
30
53
 
31
- Or install it yourself as:
54
+ my_tree.print
55
+ # Output:
56
+ # ∅
57
+ # └─sequence success (0 ticks)
58
+ # ├─task success (0 ticks)
59
+ # ├─condition success (0 ticks)
60
+ # │ └─task success (0 ticks)
61
+ # └─task success (0 ticks)
62
+ ```
63
+
64
+ Later in the guide you'll learn how to add your own custom classes so they are available inside the DSL as well.
65
+
66
+ If the tree or part of it cannot be built using the DSL, you can build it using plain old Ruby objects like so:
67
+
68
+ ```ruby
69
+ # Initialize an empty sequence.
70
+ sequence = BehaviorTree::Sequence.new
71
+
72
+ # Creating some tasks. You can also create tasks by extending BehaviorTree::Task,
73
+ # keep reading to learn how.
74
+ task1 = BehaviorTree::Task.new {
75
+ puts 'Hello world'
76
+ status.success!
77
+ }
78
+
79
+ task2 = BehaviorTree::Task.new {
80
+ puts 'Another simple task'
81
+ status.success!
82
+ }
83
+
84
+ # Add as children.
85
+ sequence << task1
86
+ sequence << task2
87
+
88
+ # Finally build the tree.
89
+ another_tree = BehaviorTree::Tree.new sequence
90
+
91
+ another_tree.print
92
+ # Output:
93
+ # ∅
94
+ # └─sequence success (0 ticks)
95
+ # ├─task success (0 ticks)
96
+ # └─task success (0 ticks)
97
+ ```
98
+
99
+ You can join trees created with any of the above methods (DSL or plain old Ruby objects). Let's join both of the trees we just created:
100
+
101
+ ```ruby
102
+ sequence << my_tree
103
+
104
+ another_tree.print
105
+ # Output:
106
+ # ∅
107
+ # └─sequence success (0 ticks)
108
+ # ├─task success (0 ticks)
109
+ # ├─task success (0 ticks)
110
+ # └─sequence success (0 ticks)
111
+ # ├─task success (0 ticks)
112
+ # ├─condition success (0 ticks)
113
+ # │ └─task success (0 ticks)
114
+ # └─task success (0 ticks)
115
+ ```
116
+
117
+ Finally, let's tick the tree to put it into motion.
118
+
119
+ ```ruby
120
+ # We need to assign the initial context data first.
121
+ another_tree.context = { some_value: 5 }
122
+
123
+ 200.times { another_tree.tick! }
124
+
125
+ another_tree.print
126
+ # Output:
127
+ # ∅
128
+ # └─sequence failure (200 ticks)
129
+ # ├─task success (200 ticks)
130
+ # ├─task success (200 ticks)
131
+ # └─sequence success (200 ticks)
132
+ # ├─task success (200 ticks)
133
+ # ├─condition failure (200 ticks)
134
+ # │ └─task success (195 ticks)
135
+ # └─task success (195 ticks)
136
+ ```
137
+
138
+ ## Learn how to use
139
+
140
+ - [Quick start](#quick-start)
141
+ * [Build your first tree](#build-your-first-tree)
142
+ - [Learn how to use](#learn-how-to-use)
143
+ - [Basics](#basics)
144
+ * [Ticking the tree](#ticking-the-tree)
145
+ * [Node status](#node-status)
146
+ * [Storage](#storage)
147
+ + [Global context](#global-context)
148
+ + [Per-node storage](#per-node-storage)
149
+ * [Types of nodes](#types-of-nodes)
150
+ + [Task nodes](#task-nodes)
151
+ + [Control nodes](#control-nodes)
152
+ + [Decorators and condition nodes](#decorators-and-condition-nodes)
153
+ - [Create custom nodes](#create-custom-nodes)
154
+ * [Custom task](#custom-task)
155
+ * [Custom control node](#custom-control-node)
156
+ * [Custom decorator](#custom-decorator)
157
+ * [Custom condition](#custom-condition)
158
+ - [Node API](#node-api)
159
+ * [Status](#status)
160
+ * [tick!](#tick-)
161
+ * [halt!](#halt-)
162
+ * [Status related callbacks and hooks](#status-related-callbacks-and-hooks)
163
+ - [Add custom nodes to the DSL](#add-custom-nodes-to-the-dsl)
164
+ - [Troubleshoot and debug your trees](#troubleshoot-and-debug-your-trees)
165
+ * [Detecting cycles](#detecting-cycles)
166
+ * [Checking nodes are all unique objects](#checking-nodes-are-all-unique-objects)
167
+ * [Visualize a tree](#visualize-a-tree)
168
+ - [Miscellaneous](#miscellaneous)
169
+ * [Generate random trees](#generate-random-trees)
170
+ - [Contributing](#contributing)
171
+ - [License](#license)
172
+ - [Code of Conduct](#code-of-conduct)
32
173
 
33
- $ gem install ruby-behavior-tree
174
+ ## Basics
175
+
176
+ What is a behavior tree? According to the [Wikipedia](https://en.wikipedia.org/wiki/Behavior_tree_(artificial_intelligence,_robotics_and_control)):
177
+
178
+ > A behavior tree is a mathematical model of plan execution used in computer science, robotics, control systems and video games. They describe switchings between a finite set of tasks in a modular fashion. Their strength comes from their ability to create very complex tasks composed of simple tasks, without worrying how the simple tasks are implemented.
179
+
180
+ In simple words, it's a modular way to describe your program's control flow, in a very flexible and scalable way. It avoids the common pitfalls of usual control flow (i.e. `if-else`), such as spaghetti code, by structuring the logic as a tree, with branches (conditionals, sequence of tasks, etc) and leaf nodes (tasks to be executed).
181
+
182
+ ### Ticking the tree
183
+
184
+ ```ruby
185
+ my_tree.tick!
186
+
187
+ # Effects are propagated down the tree.
188
+ ```
189
+
190
+ ### Node status
191
+
192
+ Each node has a status, which can have three possible values:
193
+
194
+ 1. `success` which is usually returned by a task when it completes successfully, by conditional nodes when the condition they evaluate is true, or when nodes have never been set to run. Since this is the default status of all nodes, a node is in `success` status if it has never been ticked, or if it has been halted (using `halt!`).
195
+ 2. `running` which is returned by nodes that are currently executing.
196
+ 3. `failure` which is returned to signal that execution failed.
197
+
198
+ Each type of node has different logic for returning these three values.
199
+
200
+ ### Storage
201
+
202
+ #### Global context
203
+
204
+ Just like you would have access to local variables inside an `if-else` block, a behavior tree has a data structure called `context` which it can operate on. If this didn't exist, there would be no data to work with, and/or use to take decisions. In other implementations, it's called *blackboard*, a concept which refers to a global memory.
205
+
206
+ You can use any Ruby object as context, but the easiest way to get started is to pass a `Hash` object.
207
+
208
+ This example shows how to initialize a tree's context with an empty `Hash`, and when assigning it, the tree will propagate the object to all nodes of the tree.
209
+
210
+ ```ruby
211
+ my_tree.context = {}
212
+ ```
213
+
214
+ The method `context` is available on all nodes, which provides a reference to this object.
215
+
216
+ #### Per-node storage
217
+
218
+ Arbitrary data can also be stored on a per node basis.
219
+
220
+ ```ruby
221
+ node_instance[:arbitrary_variable] = :hello_world
222
+ ```
223
+
224
+ The preferred way to store node-scoped data is to use vanilla Ruby `@instance_variables`, but this is only possible if you are creating a custom class, and if the node manipulates its own data. Instead, a parent node may use this mechanism to manipulate its children data when necessary.
225
+
226
+ **Note:** `node_instance` is **not** a `Hash` object, but instead a Node object. This is a `[]` and `[]=` operator overload.
227
+
228
+ ### Types of nodes
229
+
230
+ #### Task nodes
231
+
232
+ A task node is the only type of leaf node, and it usually executes an arbitrary procedure.
233
+
234
+ Tasks would usually return `success` or `failure` when they complete, and return `running` if they haven't completed yet.
235
+
236
+ **Example #1: Custom task class**
237
+
238
+ ```ruby
239
+ class DecreaserTask < BehaviorTree::Task
240
+ def on_tick
241
+ context[:my_number] -= 1
242
+ status.success!
243
+ end
244
+ end
245
+ ```
246
+
247
+ Learn [how to register your custom nodes](#add-custom-nodes-to-the-dsl) so they become available in the DSL.
248
+
249
+ **Example #2: Insert inline logic in the DSL**
250
+
251
+ ```ruby
252
+ BehaviorTree::Builder.build do
253
+ task do
254
+ context[:my_number] -= 1
255
+ status.success!
256
+ end
257
+ end
258
+ ```
259
+
260
+ #### Control nodes
261
+
262
+ A control node decides the flow of the execution. In simpler words, it uses a certain logic to decide which branch to execute. This is where most of the similarities with a simple `if-else` come from.
263
+
264
+ A control node cannot be a leaf (i.e. it must have children).
265
+
266
+ There are two types of control nodes, and custom ones can be easily created ([see examples of custom control nodes](#custom-control-node)).
267
+
268
+ 1. **Sequence:**
269
+ a. Begins executing the first child node.
270
+ b. If the child returns `running`, the sequence also returns `running`.
271
+ c. If child returns `failure`, all children are halted, and the sequence returns `failure`.
272
+ d. If the child returns `success`, it continues with the next child node executing the same logic.
273
+ 2. **Selector:**
274
+ a. Begins executing the first child node.
275
+ b. If the child returns `running`, the sequence also returns `running`.
276
+ c. If child returns `success`, halt all children and return `success`.
277
+ d. If child returns `failure`, then continue with the next child.
278
+ e. If no node ever returned `success`, then return `failure`.
279
+
280
+ [Learn about "halting nodes" and what it means.](#halt-)
281
+
282
+ When a control node is ticked, by default it traverses children and ticks them using this logic:
283
+
284
+ 1. If at least one node is `running`, then begin from that one, in order.
285
+ 2. If no node is `running`, then traverse all nodes starting from the first one, in order.
286
+
287
+ **Example #1: Creating a sequence and a selector**
288
+
289
+ ```ruby
290
+ sequence = BehaviorTree::Sequence.new
291
+ selector = BehaviorTree::Selector.new
292
+
293
+ 3.times { sequence << BehaviorTree::Task.new }
294
+ 2.times { selector << BehaviorTree::Task.new }
295
+
296
+ # Make the selector a child of the sequence
297
+ sequence << selector
298
+
299
+ my_tree = BehaviorTree::Builder.build do
300
+ chain sequence
301
+ end
302
+
303
+ my_tree.print
304
+ # Output:
305
+ # ∅
306
+ # └─sequence success (0 ticks)
307
+ # ├─task success (0 ticks)
308
+ # ├─task success (0 ticks)
309
+ # ├─task success (0 ticks)
310
+ # └─selector success (0 ticks)
311
+ # ├─task success (0 ticks)
312
+ # └─task success (0 ticks)
313
+ ```
314
+
315
+ #### Decorators and condition nodes
316
+
317
+ A decorator can have only one child, and acts as a modifier for its child.
318
+
319
+ By default the decorator nodes present in this library are:
320
+
321
+ | Name | Class | DSL | Description |
322
+ | --- | --- | --- | --- |
323
+ | Condition | `BehaviorTree::Decorators::Condition` | `condition` or `cond` | Ticks its child only if the condition succeeds. If not, returns `failure` (and has no effect whatsoever on the child). If the condition succeeds, it ticks the child and returns its status. |
324
+ | Force Failure | `BehaviorTree::Decorators::ForceFailure` | `force_failure` | Ticks the child, and always returns `failure` regardless of what the child returned. |
325
+ | Force Success | `BehaviorTree::Decorators::ForceSuccess` | `force_success`| Ticks the child, and always returns `success` regardless of what the child returned. |
326
+ | Inverter | `BehaviorTree::Decorators::Inverter` | `inverter` or `inv` | Returns `running` if the child returns `running`, and returns the opposite (inverted status) when the child returns `failure` or `success`. |
327
+ | Repeater | `BehaviorTree::Decorators::Repeater` | `repeater` or `rep` | Ticks the child again N times while it's returning `success`. |
328
+ | Retry | `BehaviorTree::Decorators::Retry` | `re_try` | Ticks the child again N times while it's returning `failure`. |
329
+
330
+ **Example #1: Creating a tree with many decorators**
331
+
332
+ ```ruby
333
+ my_tree = BehaviorTree::Builder.build do
334
+ inv {
335
+ sel {
336
+ task -> { puts 'Task 1' }
337
+ force_failure { task -> { puts 'Task 2' } }
338
+ task -> { puts 'Task 3' }
339
+ }
340
+ }
341
+ task
342
+ end
343
+ ```
344
+
345
+ ## Create custom nodes
346
+
347
+ ### Custom task
348
+
349
+ There are two main ways to create tasks.
350
+
351
+ 1. By instantiating `BehaviorTree::TaskBase` (or its alias `BehaviorTree::Task`) and passing a lambda or block.
352
+ 2. By subclassing `BehaviorTree::TaskBase` and overriding the `on_tick` method with the desired procedure to execute.
353
+
354
+ Let's see examples of both.
355
+
356
+ **Example #1 Empty task (i.e. does nothing)**
357
+
358
+ ```ruby
359
+ task = BehaviorTree::TaskBase.new
360
+ ```
361
+
362
+ **Example #2 Task that returns status based on the context**
363
+
364
+ ```ruby
365
+ task = BehaviorTree::TaskBase.new do
366
+ if context[:a] > 1
367
+ status.success!
368
+ elsif context[:a] < -1
369
+ status.failure!
370
+ else
371
+ status.running!
372
+ end
373
+
374
+ context[:a] += 1
375
+ end
376
+
377
+ # Initialize context.
378
+ task.context = { a: -2 }
379
+
380
+ task.tick!; task.status #=> failure
381
+ task.tick!; task.status #=> running
382
+ task.tick!; task.status #=> running
383
+ task.tick!; task.status #=> running
384
+ task.tick!; task.status #=> success
385
+ task.tick!; task.status #=> success
386
+ ```
387
+
388
+ **Example #3: Same as #2, but using lambdas instead**
389
+
390
+ When using lambdas instead of normal `Proc` (or blocks), you must pass the `context` and `node` arguments if you want to access their data. Both parameters are optional.
391
+
392
+ ```ruby
393
+ task = BehaviorTree::TaskBase.new -> (context, node) {
394
+ if context[:a] > 1
395
+ # 'node' is the 'self' node (i.e. the task node).
396
+ node.status.success!
397
+ elsif context[:a] < -1
398
+ node.status.failure!
399
+ else
400
+ node.status.running!
401
+ end
402
+
403
+ context[:a] += 1
404
+ }
405
+ ```
406
+
407
+ **Example #4: Create a custom task class**
408
+
409
+ In this task not only we override the `on_tick` method, but also the constructor, and now this task needs a parameter to be instantiated.
410
+
411
+ ```ruby
412
+ class CustomTaskWithConstructorArgument < BehaviorTree::Task
413
+ def initialize(inc)
414
+ super()
415
+ @inc = inc
416
+ end
417
+
418
+ def on_tick
419
+ context[:a] += @inc
420
+ context[:a].even? ? status.success! : status.running!
421
+ end
422
+ end
423
+
424
+ task = CustomTaskWithConstructorArgument.new(3)
425
+
426
+ initial_context = { a: 3 }
427
+
428
+ task.context = initial_context
429
+
430
+ task.tick!
431
+
432
+ task.status.to_sym # => :success
433
+
434
+ initial_context # => {:a=>6}
435
+ ```
436
+
437
+ ### Custom control node
438
+
439
+ Control nodes use a concept called `traversal strategy`, which refers to the way the nodes are iterated.
440
+
441
+ The default strategy (named `prioritize_running`) is to:
442
+ 1. If there's at least one child running, then begin (or actually, resume) from there, and in order.
443
+ 2. If no child is running, then traverse all nodes starting from the first one, in order.
444
+
445
+ In order to change the strategy used by a class, you must execute (inside the class, not instance) the method `children_traversal_strategy`, and specify which strategy to use. The strategy is simply the name of a method that returns an `Enumerable` (an array, etc). This `Enumerable` must have the children to traverse.
446
+
447
+ Not executing `children_traversal_strategy` will make your class use the default strategy (i.e. `prioritize_running`).
448
+
449
+ **Example #1: Shuffle (random) traversal**
450
+
451
+ In this example, the `Shuffle` class changes only the traversal strategy, but doesn't change the way `Sequence` works. In other words, this is a sequence with random order.
452
+
453
+ ```ruby
454
+ class Shuffle < BehaviorTree::Sequence
455
+ children_traversal_strategy :shuffle
34
456
 
35
- ## Usage
457
+ private
36
458
 
37
- TODO: Write usage instructions here
459
+ # Memoize shuffled order. Keep the same order while the sequence is running.
460
+ def shuffle
461
+ @shuffled_order ||= @children.shuffle
462
+ running_idx = @shuffled_order.find_index { |node| node.status.running? }.to_i
38
463
 
39
- ## Development
464
+ @shuffled_order[running_idx..]
465
+ end
40
466
 
41
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
467
+ # Un-memoize the shuffled order so that it's
468
+ # shuffled again (everytime the status goes from not-running to running).
469
+ def on_started_running
470
+ @shuffled_order = nil
471
+ end
472
+ end
473
+ ```
474
+
475
+ **Example #2: Overriding the control flow logic**
476
+
477
+ The example above defines a new traversal strategy, but keeps the same logic as a vanilla `Sequence`. In the following example, we continue to use the strategy defined above, but create a different control flow logic.
478
+
479
+ Control nodes execute their control flow logic in the `on_tick` method, so this is the method that must be overriden.
480
+
481
+ ```ruby
482
+ # Return success if all either succeeded or failed. Otherwise return failure.
483
+ # (Similar to other control nodes, return running when a child is running.)
484
+ class AllOrNothing < ControlNodeBase
485
+ children_traversal_strategy :shuffle
486
+
487
+ def on_tick
488
+ success_count = 0
489
+ fail_count = 0
490
+
491
+ # This loop iterates children using the shuffle strategy, AND ticks each child.
492
+ tick_each_children do |child|
493
+ return status.running! if child.status.running?
494
+
495
+ # Regardless of whether the child succeeded or failed,
496
+ # continue with the next child. Just store whether it succeeded or not.
497
+ success_count += 1 if child.status.success?
498
+ fail_count += 1 if child.status.failure?
499
+
500
+ # Can be optimized to return failure as soon as it encounters at least one
501
+ # that failed and at least one that succeeded.
502
+ end
503
+
504
+ # Set self node and all children to success.
505
+ halt!
506
+
507
+ # Status is already success from the halt! above. Do nothing.
508
+ return if success_count == children.count || fail_count == children.count
509
+
510
+ # Else return fail. Results are not "all success" or "all failure".
511
+ status.failure!
512
+ end
513
+
514
+ # From here it's omitted. Copy code from example above.
515
+
516
+ def shuffle
517
+ # ...
518
+ end
519
+
520
+ def on_started_running
521
+ # ...
522
+ end
523
+ end
524
+ ```
525
+
526
+ Note that under the hood, `tick_each_children` uses the strategy defined (i.e. `shuffle` method), and traverses its children while also ticking them. You don't need to send `tick!` manually to the child. The code defined in `on_tick` is executed *right after* the child is ticked.
527
+
528
+ ### Custom decorator
529
+
530
+ **Note:** Condition nodes are also a type of decorator, but they are covered separately here: [Custom condition nodes](#custom-condition).
531
+
532
+ Here's an example of how to create a custom decorator. Simply inherit from `BehaviorTree::Decorators::DecoratorBase` and override any or both of these two methods, `decorate` and `status_map`.
533
+
534
+ ```ruby
535
+ class CustomDecorator < BehaviorTree::Decorators::DecoratorBase
536
+ protected
537
+
538
+ def decorate
539
+ # Additional logic to be executed when the node is ticked.
540
+ end
541
+
542
+ # This method must change the self node status in function
543
+ # of the child status. The default behavior is to copy its status.
544
+ # The status is mapped at the end of the tick lifecycle.
545
+ def status_map
546
+ self.status = child.status
547
+ end
548
+ end
549
+ ```
550
+
551
+ ### Custom condition
552
+
553
+ Creating a condition as a class. The `should_tick?` method must be overriden, and it must return a `boolean` value.
554
+
555
+ ```ruby
556
+ class CustomCondition < BehaviorTree::Decorators::Condition
557
+ def should_tick?
558
+ context[:a] > -1
559
+ end
560
+ end
561
+ ```
562
+
563
+ Or using inline logic in the DSL. When using the DSL, before starting the block (i.e. where the child is defined), you must pass a `lambda` which receives two parameters (both optional), `context` and `node` (the `self` of the condition node).
564
+
565
+ ```ruby
566
+ my_tree = BehaviorTree::Builder.build do
567
+ condition ->(context, node) { context[:a].positive? } do
568
+ task # The decorated task (condition node's child)
569
+ end
570
+ end
571
+
572
+ # Define tree's context data.
573
+ my_tree.context = { a: -1 }
574
+
575
+ # Tick the tree once.
576
+ my_tree.tick!
577
+
578
+ # Inspect the tree. Condition failed, and task node hasn't been touched.
579
+ my_tree.print
580
+ # Output:
581
+ # ∅
582
+ # └─condition failure (1 ticks)
583
+ # └─task success (0 ticks)
584
+ ```
585
+
586
+ **Note:** Other behavior tree implementations prefer the use of `sequence` control nodes, and placing conditional nodes as a leaves, but with the role of simply returning `failure` or `success`. Since sequences execute the next node only if the previous one succeeded, this also works as a conditional node. In this implementation, however, both patterns are available and you are free to choose which one to use.
587
+
588
+ ## Node API
589
+
590
+ ### Status
591
+
592
+ Every instance of node classes have a status object, where you can execute the following methods.
593
+
594
+ **Setters**
595
+
596
+ ```ruby
597
+ node.status.running!
598
+ node.status.success!
599
+ node.status.failure!
600
+
601
+ node.status = other_node.status # Copy status from other node
602
+ ```
603
+
604
+ **Querying status**
605
+
606
+ ```ruby
607
+ node.status.running? # => boolean
608
+ node.status.success? # => boolean
609
+ node.status.failure? # => boolean
610
+ ```
611
+
612
+ **Accessing previous status**
613
+
614
+ The previous status is also stored inside a node. It can be used in `on_status_change` to trigger a certain action in function of the current and previous state (See: [Status related callbacks and hooks](#status-related-callbacks-and-hooks)).
615
+
616
+ ```ruby
617
+ node.status.success!
618
+
619
+ node.status.running!
620
+
621
+ node.status.to_sym # => :running
622
+
623
+ node.prev_status.to_sym # => :success
624
+ ```
625
+
626
+ **Warning:** Don't modify the `prev_status` manually. It's updated automatically.
627
+
628
+ ### tick!
629
+
630
+ As you have seen in other examples, all nodes have a `tick!` method, which as the name says, ticks the node, and propagates it down to its children (if any).
631
+
632
+ The first thing it does is always setting the node to `running`. After this, what happens depends on the type of node. You can learn more about each node type and how to override their behavior in: [Create custom nodes](#create-custom-nodes).
633
+
634
+ ### halt!
635
+
636
+ This simply sets the node to `success`, and when a node has children, it executes `halt!` on all children as well, which propagates the `halt!` action down the tree.
637
+
638
+ This method is usually used when you want to reset the node and its children's status. In control nodes, since they follow the strategy of *"resume from the running nodes, if there is any"* is used by default, it's imperative to execute `halt!` once the sequence/selector has finished, so it can start again from the first node (unless you override this logic in a custom control node). Other than that, you may decide not to halt them if it's not necessary.
639
+
640
+ ### Status related callbacks and hooks
641
+
642
+ **on_status_change**
643
+
644
+ This method is executed everytime the node status changes. It's only triggered when there's a change (i.e. previous value and next value are different).
645
+
646
+ Therefore, the following code only triggers the callback once:
647
+
648
+ ```ruby
649
+ # Current status is success.
650
+ node.status.success? # => true
651
+
652
+ node.status.failure! # Triggers the callback.
653
+ node.status.failure! # Does not trigger.
654
+ node.status.failure!
655
+ ```
656
+
657
+ ```ruby
658
+ class RandomStatusTask < BehaviorTree::Task
659
+ def on_tick
660
+ puts 'Being ticked...'
661
+ possible_status = [:running, :success, :failure]
662
+ status.send("#{possible_status.sample}!")
663
+ end
664
+
665
+ def on_status_change
666
+ prev = prev_status
667
+ curr = status
668
+
669
+ puts "My status went from #{prev.to_sym} to #{curr.to_sym} (tick_count = #{tick_count})"
670
+ end
671
+ end
672
+
673
+ task = RandomStatusTask.new
674
+
675
+ 5.times { task.tick! }
676
+
677
+ # Output:
678
+ # My status went from success to running (tick_count = 1)
679
+ # Being ticked...
680
+ # My status went from running to failure (tick_count = 1)
681
+ # My status went from failure to running (tick_count = 2)
682
+ # Being ticked...
683
+ # My status went from running to failure (tick_count = 2)
684
+ # My status went from failure to running (tick_count = 3)
685
+ # Being ticked...
686
+ # My status went from running to success (tick_count = 3)
687
+ # My status went from success to running (tick_count = 4)
688
+ # Being ticked...
689
+ # My status went from running to success (tick_count = 4)
690
+ # My status went from success to running (tick_count = 5)
691
+ # Being ticked...
692
+ # My status went from running to failure (tick_count = 5)
693
+ ```
694
+
695
+ In the output of the example above, one thing to note is that the first line (change from `success` to `running`) happens because `tick!` **immediately and always** sets the node to `running`. This happens even before the task logic (`on_tick` method) has been executed.
696
+
697
+ The second line of the output is the `puts` of the actual task logic. The third line happens as a result of the task logic changing the status, therefore triggering a `on_status_change` call.
698
+
699
+ **on_started_running**
700
+
701
+ Similar to `on_status_change`, but only triggers when the node has been set to `running`.
702
+
703
+ **on_finished_running**
704
+
705
+ Similar to `on_status_change`, but only triggers when the node has been set to a status other than `running`.
706
+
707
+ ## Add custom nodes to the DSL
708
+
709
+ You can register new nodes to be used in the DSL, take for example the following code:
710
+
711
+ ```ruby
712
+ BehaviorTree::Builder.register(
713
+ :my_control_node,
714
+ 'CustomNodes::MyControlNode',
715
+ children: :multiple
716
+ )
717
+ ```
718
+
719
+ When using `BehaviorTree::Builder#register`, you must supply three arguments, the keyword to be used in the DSL, the class name, and an optional parameter indicating how many children your node must have.
720
+
721
+ The possible values for the `children:` argument are:
722
+
723
+ 1. `none` when your node is a leaf node (i.e. task). Default value if not specified.
724
+ 2. `multiple` when your node is a control node.
725
+ 3. `single` when your node is a decorator, conditional, etc.
726
+
727
+ Next, you can use the registered node in the DSL.
728
+
729
+ ```ruby
730
+ BehaviorTree::Builder.build do
731
+ my_control_node do
732
+ # The rest of the tree here.
733
+ end
734
+ end
735
+ ```
736
+
737
+ You can also define an alias for your node:
738
+
739
+ ```ruby
740
+ # First argument is original key (existing one).
741
+ # Second argument is the new alias.
742
+ BehaviorTree::Builder.register_alias(:my_control_node, :my_ctrl_node)
743
+ ```
744
+
745
+ This way, both `my_control_node` and `my_ctrl_node` can be used in the DSL.
746
+
747
+ ## Troubleshoot and debug your trees
748
+
749
+ Sometimes you may run into issues with your tree, and it's generally difficult to debug a recursive structure, but here are a few ways to make it a bit easier to debug and troubleshoot.
750
+
751
+ ### Detecting cycles
752
+
753
+ You can check if your tree has cycles by executing the following:
754
+
755
+ ```ruby
756
+ my_tree.cycle?
757
+ # => false
758
+ ```
759
+
760
+ ### Checking nodes are all unique objects
761
+
762
+ Sometimes you might accidentally chain the same node to a parent node. When this happens, the node will have multiple parents. Since this might be a desired situation in some cases, nodes are not cloned automatically by default.
763
+
764
+ You can check for repeated nodes using the following methods:
765
+
766
+ ```ruby
767
+ my_tree.uniq_nodes?
768
+ # => true
769
+ ```
770
+
771
+ Or obtain the actual repeated nodes:
772
+
773
+ ```ruby
774
+ my_tree.repeated_nodes
775
+ # => <Set: { ... repeated nodes ... }>
776
+ ```
777
+
778
+ **Note:** Object equality is tested using `Set#include?`.
779
+
780
+ ### Visualize a tree
781
+
782
+ Printing the tree is not only useful for verifying it has the desired structure, but also for detecting various issues.
783
+
784
+ ```ruby
785
+ 200.times { my_tree.tick! }
786
+
787
+ my_tree.print
788
+ ```
789
+
790
+ The above code generates the following output:
791
+
792
+ <p align="center">
793
+ <img src="https://github.com/FeloVilches/ruby-behavior-tree/blob/main/assets/printed_tree.jpg?raw=true" width="400"/>
794
+ </p>
795
+
796
+ In the example above, you can see that the bottom nodes haven't been ticked at all. Node starvation might occur for various reasons, such as having a `force_failure` node as one of the children of a `sequence` (the nodes after the `force_failure` would all be prevented from executing).
797
+
798
+ Printing can also be useful in detecting bugs in your custom nodes.
799
+
800
+ ## Miscellaneous
801
+
802
+ ### Generate random trees
803
+
804
+ Mostly created for debugging and testing various trees in development mode, you can generate random trees by executing the following code:
805
+
806
+ ```ruby
807
+ random_tree = BehaviorTree::Builder.build_random_tree
808
+
809
+ 100.times { random_tree.tick! }
810
+ random_tree.print
811
+ # Output:
812
+ # ∅
813
+ # └─selector running (100 ticks)
814
+ # ├─forcefailure failure (76 ticks)
815
+ # │ └─repeater success (76 ticks)
816
+ # │ └─retry success (95 ticks)
817
+ # │ └─task success (114 ticks)
818
+ # ├─inverter running (47 ticks)
819
+ #
820
+ # (the rest is omitted)
821
+ ```
822
+
823
+ Or make it smaller/larger by tweaking the optional argument `recursion_amount`:
824
+
825
+ ```ruby
826
+ random_tree = BehaviorTree::Builder.build_random_tree(recursion_amount: 9)
827
+ ```
42
828
 
43
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
829
+ Keep in mind this is only for development purposes, and the generated trees don't make sense at all. Also, only vanilla default nodes are used. Conditional nodes fail or succeed randomly, and task nodes generate random return values as well.
44
830
 
45
831
  ## Contributing
46
832
 
47
- Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/ruby-behavior-tree. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/ruby-behavior-tree/blob/master/CODE_OF_CONDUCT.md).
833
+ Bug reports and pull requests are welcome on GitHub at https://github.com/FeloVilches/ruby-behavior-tree. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/FeloVilches/ruby-behavior-tree/blob/main/CODE_OF_CONDUCT.md).
48
834
 
49
835
 
50
836
  ## License
@@ -53,4 +839,4 @@ The gem is available as open source under the terms of the [MIT License](https:/
53
839
 
54
840
  ## Code of Conduct
55
841
 
56
- Everyone interacting in the Ruby::Behavior::Tree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/ruby-behavior-tree/blob/master/CODE_OF_CONDUCT.md).
842
+ Everyone interacting in the Behavior Tree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/FeloVilches/ruby-behavior-tree/blob/main/CODE_OF_CONDUCT.md).