Jump to content
Frequently Asked Questions
  • Are you not able to open the client? Try following our getting started guide
  • Still not working? Try downloading and running JarFix
  • Help! My bot doesn't do anything! Enable fresh start in client settings and restart the client
  • How to purchase with PayPal/OSRS/Crypto gold? You can purchase vouchers from other users
  • Try asking for help in the chatbox
  • Behavior Trees For Dummies - Basic Woodcutting Script


    Recommended Posts

    Behavior Trees For Dummies

    I'm not a pro at anything and take everything I say with a grain of salt. I have no idea what i'm doing and my opinions here are mostly preference. Make your own decisions, disagree with me, tell me why, and lets make better bots. Also, can't take credit for the idea of behavior trees in bots. I read @jgs95's post about them a week ago.

    Introduction

    The most popular type of scripts I have found during my time scripting is the `Node` based system. Node based systems split up their code into sections called Nodes (duh). Each Node is comprised of a condition that checks whether or not the node should run, and a action to perform if the condition passes. If you don't yet know about Node based systems I highly suggest checking out This post. You should know about other methodologies of bot scripting so you can weigh the pros and cons of both for yourself.

    Code That A Computer Can Read Is Useless.

    At a very high level Behavior Trees are used to handle triggering actions based on conditions. Sound a lot like the Node system mentioned earlier? Both methodologies are just ways to handle triggering actions based on conditions. That's what most if not all bots do. So why choose Behavior Trees? There are two things that need to be able to understand your code. The computer, and humans (yourself included). Writing code that the computer understands is easy. Take a look at the following JavaScript code.

    var _0x49e6=['1JEFwRC','5222dXsJWJ','92FVLqzU','1365284gtsOMo','1614886gtbOhP','3648908RUJhLp','Hello\x20World!','74944THxNfO','412769AyhqCE','log','1402906gnphcE'];(function(_0xf7574b,_0x59a0fa){var _0x3a1092=_0x3bf3;while(!![]){try{var _0x2ce5f6=parseInt(_0x3a1092(0x182))+parseInt(_0x3a1092(0x185))*parseInt(_0x3a1092(0x184))+parseInt(_0x3a1092(0x17f))+parseInt(_0x3a1092(0x186))+-parseInt(_0x3a1092(0x183))*parseInt(_0x3a1092(0x180))+parseInt(_0x3a1092(0x187))+-parseInt(_0x3a1092(0x17d));if(_0x2ce5f6===_0x59a0fa)break;else _0xf7574b['push'](_0xf7574b['shift']());}catch(_0x46c630){_0xf7574b['push'](_0xf7574b['shift']());}}}(_0x49e6,0xd60df));function hi(){var _0x221f00=_0x3bf3;console[_0x221f00(0x181)](_0x221f00(0x17e));}function _0x3bf3(_0x3c1132,_0x58570b){_0x3c1132=_0x3c1132-0x17d;var _0x49e678=_0x49e6[_0x3c1132];return _0x49e678;}hi();

    This runs. The computer is absolutely fine with this. But what about the poor sap that has to maintain this code? Or what if you need to go back and change something. I guarantee if you even step away to shit after writing this you will comeback and have no fucking idea what this does and probably blame someone else for writing it insisting they are an idiot and should be killed immediately (personal experience). This is why coding for humans is more important that coding for the computers. Take a look at the following code that does the exact same thing as the above example.

    function helloWorld() {
    	console.log("Hello World!");
    }

    Tell me that doesn't make one thousand times more sense than the other example. Clean, readable code is the backbone of a good program. How fast, or efficient it is should be the second thing you think about. You can always go back and optimize. It's much harder to go back and make it understandable. If the topic of clean code has given you a boner/wet vagina I highly suggest reading Clean Code by Robert C. Martin. Now that we understand that we should prioritize writing code that humans can understand we can start looking at why we should choose Behavior Trees over everything else.

    Why Choose Behavior Trees Over Everything Else?

    Lets take a look at a node based wood chopper main script class. This is based off of This really great tutorial on the Node system by @GoldenGates. Great read, go read it if you aren't that solid with the node system yet.

    public class WoodChopper extends AbstractScript {
       private final Node[] array = new Node[] {
          	new WalkToTrees(this),
            new ChopWood(this),
            new WalkToBank(this),
          	new OpenBank(this),
          	new DepositLogs(this)
        };
    
    	@Override
    	public int onLoop() {
    		for (final Node node : array)
    			if (node.activate()) {
              		node.execute();
            	}
    		return Calculations.random(250, 500);
    	}
    }

    The main con I have for the Node based system is how it reads, reuse, and how you handle more complex conditions. Correctly naming your Node instances is a great start. but we are left wondering what conditions do these nodes run on. If we wanted to get a bit more flexible we could abstract out our conditions and actions using two new classes. a `Action` class and a `Condition` class. Then our main script class would look like this.

    public class WoodChopper extends AbstractScript {
        private final Node[] array = new Node[] {
          	new Node(new ShouldMoveToTrees(), new WalkToTrees()),
            new Node(new ShouldChopWood(), new ChopWood()),
            new Node(new ShouldWalkToBank(), new WalkToBank()),
            new Node(new ShouldOpenBank(), new OpenBank()),
          	new Node(new ShouldDepositLogs(), new DepositLogs())
        };
    
    	@Override
    	public int onLoop() {
    		for (final Node node : array)
    			if (node.activate()) {
              		node.execute();
            	}
    		return Calculations.random(250, 500);
    	}
    }

    This is pretty good. The logic flow is pretty obvious and its clear what conditions trigger what actions, in what order. For a basic script id be happy with this assuming your conditions and actions names aren't complete trash. Lets pretend that we want to chop trees behind Lumbridge castle and there is that obnoxious asshole mugger back there that attacks us all the time. We need to add some combat nodes to our Node array. Lets take a look at what that might look like now.

    public class WoodChopper extends AbstractScript {
        private final Node[] array = new Node[] {
            new Node(new IsUnderAttackWithEnoughHealth(), new FightBack()),
            new Node(new IsUnderAttackWithoutEnoughHealthAndHasFood(), new Eat()),
          	new Node(new IsUnderAttackWithoutEnoughHealthAndDoesNotHaveFood(), new RunAway()),
          	new Node(new ShouldMoveToTrees(), new WalkToTrees()),
            new Node(new ShouldChopWood(), new ChopWood()),
            new Node(new ShouldWalkToBank(), new WalkToBank()),
            new Node(new ShouldOpenBank(), new OpenBank()),
          	new Node(new ShouldDepositLogs(), new DepositLogs())
        };
    
    	@Override
    	public int onLoop() {
    		for (final Node node : array)
    			if (node.activate()) {
              		node.execute();
            	}
    		return Calculations.random(250, 500);
    	}
    }

    We can see now that our conditions start to contain a lot of the same wording and logic. All of our combat nodes check to see if the player is under attack. Then we make a decision about the current health of our player. Then we make a decision on if we have food or not. It's as if each of these decisions are sub decisions. Sounds a whole lot like a tree to me. Now you could only have a `IsUnderAttack` condition and then have your other conditions inside the `FightBack` action but then we are hiding logic that someone might miss while also making it harder to dynamically add more behaviors, and also adding conditions to an action which goes against the name of "action". Actions should only be exactly what they are, actions. So what are we going to do about this? JESUS CHRIST GET TO BEHAVIOR TREES ALREADY YOU FUCK. Fine here we go.

    First off, Watch the following Videos if you have never heard of behavior trees or have no idea how they work.

    Data structures: Introduction to Trees - mycodeschool

    Introduction To Behavior Trees - Holistic3d

    What is a Behavior Tree and How do they work? (BT intro part 1) - Peter Ogren

    How to create Behavior Trees using Backward Chaining (BT intro part 2) - Peter Ogren

    Here is how we would create the same script with a behavior tree. After looking at this i'll go over why I think it is more readable/cleaner/flexible. 

    public class WoodChopper extends AbstractScript {
       Node bankTree = new TreeBuilder()
       .sequence()
          .oncePerSequenceCompletion()
             .condition(new PlayerShouldBank())
             .finish()
          .oncePerSequenceCompletion()
             .action(new MoveToBank())
             .finish()
          .action(new DepositLogs())
          .finish()
       .buildTree();
    
       Node chopTree = new TreeBuilder()
       .sequence()
          .oncePerSequenceCompletion()
             .action(new MoveToTrees())
             .finish()
          .action(new ChopTree())
          .condition(new PlayerShouldBank())
          .finish()
       .buildTree();
    
       Node tree = new TreeBuilder()
       .selector()
          .appendTree(bankTree)
          .appendTree(chopTree)
       .buildTree();
    
    	@Override
    	public int onLoop() {
    		tree.tick();
    		return Calculations.random(250, 500);
    	}
    }

    Separation of Concerns

    Behavior trees let us split up our logic into small, clean, chunks of code that only have to do with what they are doing. We have a tree dedicated to handling banking, a tree dedicated to handling chopping wood, and a tree dedicated to putting other trees together.

    Readability

    The biggest advantage I think behavior trees have over the node system is that the code reads basically in plain English. If we look at the "chopTree" above and read line by line we fully understand what it is doing without having to go anywhere, look into any of the classes etc. To really drive my point home on this ill show you some pseudocode for the "chopTree" and you can compare it to the actual code above.

    To chop a tree we must do the following
    	in sequence
        	if we have not already moved to the tree location
            	move to the location of the trees
            chop down a tree
            if we have more inventory room repeat this sequence

    Adaptability

    Finally, our ability to add to our bots behavior is incredibly easy. Lets add our combat behavior to our behavior tree like we did to the node based system. We just create our combat tree, and add it to our root tree. We don't care about anything else in the code base. Since we want to prioritize combat we make sure to put this tree earlier in our root sequence.

    Node combatTree = new TreeBuilder()
      .selector()
      	.sequence()
      		.condition(new HasMoreThanHalfHealth())
      		.action(new Retaliate())
      	.selector()
      		.sequence()
      			.condition(new HasFood())
      			.action(new EatFood())
      		.action(new RunAway())
      .buildTree()
      
    Node root = new TreeBuilder()
      .selector()
        .appendTree(combatTree)
    	.appendTree(bankTree)
    	.appendTree(chopTree)
      .buildTree();

    Small Conditions and Actions 

    Another lovely side effect of using a behavior tree over a node system is our conditions will only be checking a maximum of one thing. Remember earlier when we had the god awful "IsUnderAttackWithoutEnoughHealthAndDoesNotHaveFood" condition? Lots of code duplication, and not very reusable as it has been so tightly written to go along with the certain action it was originally meant to. Now look at our new conditions. "HasMoreThanHalfHealth", "HasFood", these conditions could be reused in other places, and also are way less prone to bugs as they are simpler.

    Code Sharing

    Another pro of re-usability/adaptability is how easy it makes it to share between multiple projects. Lets say you write an incredible combat tree that handles eating, switching styles, praying, running away, etc. All you gotta do is pull that hoe into your new bot and append it to your root tree. (you can do this with nodes too just want to plant brain seeds).

    Conclusion

    Library/Framework

    If any of these reasons for using behavior trees made sense to you and you agree with them you might be asking if there is a pre-made framework for behavior trees you can use, and there is, I wrote one. But your not getting it. Implementing it yourself will really drive home all the ideas and pitfalls of this structure. The videos I posted above should be a good enough starting point for figuring out how to write your own implementation. Try to resist just googling for implementations because they are out there. It will make you a better developer if you pain through this and just do it. You'll learn a lot.

    When to still use Node Systems

    Like I said earlier I think there is no perfect tool for every job. You just need to know the tools at your disposal and implement what you think is most appropriate. If your bot just walks from Lumbridge to Edgeville don't implement a whole ass behavior tree. The overhead would just be ridiculous. If your building a PVP bot that also banks, switches PVP load outs etc, a behavior tree is probably a better fit. Basically, behavior trees are great for handling bots that handle a lot of behaviors. If your bot doesn't meet this criteria it's probably fine just remember my rant about readable, clean code.

    Alright,
    Bye


     

    Link to post
    Share on other sites

    Excellent post! I'm glad that behaviour trees are beginning to receive some appreciation. I've still not decided which structure I'm most comfortable with, I'm stuck between binary trees versus a fully blown behaviour tree. But I guess a binary tree is just a subset of a behaviour tree. Perhaps the benefit of understanding behaviour trees is you can pick and choose the elements that suit your project. You might not always need selectors, inverters, succeeders, in every project, but they give you a good toolkit to work with, as opposed to a simple validate/execute node.

    Link to post
    Share on other sites
    14 hours ago, jgs95 said:

    Excellent post! I'm glad that behaviour trees are beginning to receive some appreciation. I've still not decided which structure I'm most comfortable with, I'm stuck between binary trees versus a fully blown behaviour tree. But I guess a binary tree is just a subset of a behaviour tree. Perhaps the benefit of understanding behaviour trees is you can pick and choose the elements that suit your project. You might not always need selectors, inverters, succeeders, in every project, but they give you a good toolkit to work with, as opposed to a simple validate/execute node.

    Thanks! and thanks again for giving me the idea for this post! hmm, I'd have to look at how you implemented a binary tree for handling botting. I'd assume you implemented some sort of selector logic to your nodes which at that point you just kind of have a behavior tree that you have limited yourself to two nodes and less flexibility haha. I'd be interested to take a look at an example of how you setup your binary trees to work!

    14 hours ago, flipjazz said:

    Nice write-up.

    What's your view on how to adapt behavior trees for quests, which usually involve a long sequence of linear and dependent steps?

    Thanks!
    So I started implementing Chefs Assistant last night to play around with using behavior trees for quest bots. Here is a diagram of what my behavior tree looks like.image.thumb.png.4b2b580151034b1efba277b38fcb89aa.png
    (Could break up some of these actions into more sequences like "walk to bucket", then "get bucket" but lucid chart wants me to buy premium for unlimited shapes which is a joke).

    Things to remember when reading this diagram

    Sequences read left to right and if a node fails we restart

    Selectors read left to right and if a node responds with a success we consider that good enough and move on.

    Conditions return success or failure

    Actions return success (lets pretend they never fail for sake of simplicity lol. But in the real world you would probably have some extra stuff for handling that.)

    So Looking at the chart above it makes the most sense to me to use one base "sequence" since like you said quests "usually involve a long sequence of linear and dependent steps".
    You can see that we start to have a pattern arise as well with each of our steps. We generally have a "selector" which checks if the step is complete (the left child node of each step "selector" for instance "Has Bucket of Milk" which will return successful if the player has a bucket of milk"). And if it is not we move into a sub sequence for that step. All you need to remember for reading these trees is that for the most part they read left to right and once you get to a "leaf" (a node with no children) you move back to the very top.

    Another point that this diagram drives home from the original post is that behavior trees read exactly like English. This tree reads exactly like what the steps to complete the quest are. If you are new to tree traversal or behavior tree traversal i could try and animate what going through one of the steps branches would look like (or just watch the videos in the original post and that should help, then come back to this.)

    Link to post
    Share on other sites

    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now
    ×
    ×
    • Create New...

    Important Information

    We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.