Created
January 29, 2019 16:31
-
-
Save ItsMeThom-zz/624c695944c5519d703922646bf93e81 to your computer and use it in GitHub Desktop.
Simple Behaviour Tree experiments python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Tree: | |
| def __init__(self, root): | |
| self.root_node = root | |
| self.next_node = self.root_node | |
| def tick(self): | |
| print("next node is: {}".format(self.next_node)) | |
| if self.next_node is False: | |
| #TODO: Replace with enum: | |
| # Continue, Success, Failure | |
| # TODO: Replace this with a stack so we can Pop() | |
| # and get back to the parent node easily. | |
| # tree failed, return to root. | |
| print("Failure, go back to root") | |
| self.next_node = self.root_node | |
| if not callable(self.next_node): | |
| raise RuntimeError("Node was not callable {}".format(self.next_node)) | |
| # call current and it evaulates and returns a Node() or result. | |
| print("Get next node") | |
| self.next_node = self.next_node() | |
| class Node: | |
| children = [] | |
| def __init__(self, *children): | |
| self.children = (c for c in children) | |
| def __call__(self, *args, **kwargs): | |
| # override in children to add node() functionality | |
| pass | |
| class Sequence(Node): | |
| children = [] | |
| def __init__(self, *children): | |
| print("Setting sequence children to {}".format(children)) | |
| super().__init__(*children) | |
| def __call__(self, *args): | |
| next_node = next(self.children, False) | |
| print("Sequence next is: {}".format(next_node)) | |
| return next_node | |
| class If(Node): | |
| def __init__(self, test, return_node): | |
| self.test_function = test | |
| self.return_node = return_node | |
| super().__init__() | |
| def __call__(self): | |
| if not callable(self.test_function): | |
| raise Exception("Cant test not callable object") | |
| print("Calling IF test function") | |
| if self.test_function(): | |
| print("IF tested TRUE") | |
| return self.return_node | |
| class Printer(Node): | |
| def __call__(self, *args, **kwargs): | |
| print("I was called {}".format(self)) | |
| def testo(): | |
| return True | |
| ai = Tree(root=If(testo, Sequence( | |
| Printer(), | |
| Printer(), | |
| Printer() | |
| ))) | |
| ai.tick() | |
| ai.tick() | |
| ai.tick() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment