Simple Behaviour Trees

by Pietro Polsinelli

HTML

<script src="https://dl.dropboxusercontent.com/u/4422922/simpleBehaviourTreeModel.js"></script>

<h1>Simple Behaviour Trees in Javascript</h1>

      <h3>Open console to see also API feedback.</h3>

      <button onclick="example()">launch example</button>

      <hr>
<div id="console"></div>
      <hr>

JavaScript

/**
 * Created by Pietro Polsinelli && Matteo Bicocchi on 15/05/2015.
 *
 * Fisrt inspired by the simplicity of
 * http://stackoverflow.com/questions/4241824/creating-an-ai-behavior-tree-in-c-sharp-how
 *
 * ! SEE FULL SOURCES IN BOTH JAVASCRIPT AND C# on GitHub https://github.com/ppolsinelli/SimpleBehaviourTrees
 *
 * Follow us on Twitter @ppolsinelli @pupunzi where we post about game design, game development, Unity3d 2D, HTML5, CSS3, jquery, applied games.
 *
 */


/**
 * Utility functions
 */

function writeOnConsole(text) {
	var node = document.createElement("LI");                 // Create a <li> node
	var textnode = document.createTextNode(text);         // Create a text node
	node.appendChild(textnode);                              // Append the text to <li>
	document.getElementById("console").appendChild(node);     // Append <li> to <ul> with id="myList"
//	console.debug(text)
}

var totalKidsWondering = 20;

function example() {
	/**
	 *  PolicemanManager is like a static instance that processes actions on a given actor
	 *  through a behaviour tree instance.
	 */
	var PolicemanManager = {};

	PolicemanManager.ifKidInSight = function (behaviourTreeInstanceState) {

		behaviourTreeInstanceState.setState(BehaviourTreeInstance.STATE_COMPLETED);

		if (totalKidsWondering > 0) {
			writeOnConsole("total kids wandering: " + totalKidsWondering);
			var b = Math.random() > 0;
			writeOnConsole(behaviourTreeInstanceState.actor.name + ": " + "see kid? " + (b ? "yes" : "no"));
			return  b;
		} else {
			writeOnConsole(behaviourTreeInstanceState.actor.name + ": " + "No more kids");
			return false;
		}
	};

	PolicemanManager.ifChaseGotKid = function (behaviourTreeInstanceState) {

		writeOnConsole("ifChaseGotKid 1 ->" + new Date());

		writeOnConsole("ifChaseGotKid state: "+behaviourTreeInstanceState.findStateForNode(behaviourTreeInstanceState.currentNode));

		if (behaviourTreeInstanceState.hasToStart()) {

			writeOnConsole("ifChaseGotKid 2 ->" + new...