| Total Complexity | 5 |
| Total Lines | 49 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | """Tutorial 2 - how to use decisions""" |
||
| 2 | import curio |
||
| 3 | import async_btree as bt |
||
| 4 | import contextvars |
||
| 5 | |||
| 6 | |||
| 7 | async def some_action(): |
||
| 8 | print("continue here...") |
||
| 9 | |||
| 10 | |||
| 11 | async def say_hello(): |
||
| 12 | print(f"Hello {name.get()}") |
||
| 13 | |||
| 14 | async def is_name_set(): |
||
| 15 | return name.get() != "" |
||
| 16 | |||
| 17 | async def ask_for_name(): |
||
| 18 | new_name = input("Hello, whats your name? \n") |
||
| 19 | if new_name != "": |
||
| 20 | name.set(new_name) |
||
| 21 | return bt.definition.SUCCESS |
||
| 22 | else: |
||
| 23 | return bt.definition.FAILURE |
||
| 24 | |||
| 25 | |||
| 26 | name = contextvars.ContextVar('name',default="") |
||
| 27 | |||
| 28 | greet_with_name = bt.decision(condition=is_name_set, |
||
| 29 | success_tree=bt.always_success(say_hello), |
||
| 30 | failure_tree=bt.sequence([ask_for_name,bt.always_success(say_hello)]) |
||
| 31 | ) |
||
| 32 | |||
| 33 | b_tree = bt.sequence( |
||
| 34 | children=[ |
||
| 35 | greet_with_name, |
||
| 36 | bt.always_success(child=bt.action(target=some_action)), |
||
| 37 | ] |
||
| 38 | ) |
||
| 39 | |||
| 40 | if __name__ == '__main__': |
||
| 41 | |||
| 42 | name = contextvars.ContextVar('name',default="") |
||
| 43 | |||
| 44 | curio.run(b_tree) |
||
| 45 | |||
| 46 | # You can take a look at the final behavior tree |
||
| 47 | abstract_tree_tree_1 = bt.analyze(b_tree) |
||
| 48 | print(bt.stringify_analyze(abstract_tree_tree_1)) |
||
| 49 | |||
| 50 |