Monday, July 1, 2013

HTML5 game - decision tree

Most game entity, that you create for your HTML5 games needs our own intelligence. It has to decide what to do next. For example: walks, attacks, speaks, … In this post I show you how to make decision with decision tree.


Consider the following scenario:


makeDecision() {
if (iq > 80) {
negotiation();
if(comunication > 80){
win();
}else{
loss();
}
}else{
attack();
if(strength > 80){
win();
}else{
loss();
}
}
}
view raw gistfile1.js hosted with ❤ by GitHub



This type of the presentation is easy to represent in the form of a tree:


It is better to convert each condition on a separate object. Then you can check the condition and return either a decision or another decision object.


/**
* Make a decision
* @param {string} name
* @param {number} threshold
* @param {Object} leNode - less then threshold Node
* @param {Object} gNode - qrow then threshold Node
function Decision(name, threshold, leNode, gNode) {
this._name = name;
this._threshold = threshold;
this._leNode = leNode;
this._gNode = gNode;
}
Decision.prototype.execute = function(agent) {
var node = agent[this._name] > this._threshold ? this._gNode : this._leNode;
node.execute(agent);
};
view raw gistfile1.txt hosted with ❤ by GitHub


Finally, you need to create the tree and let it make the decision:


function Hero(){
this.inteligence = 100;
this.communication = 120;
this.strength = 50;
}
function WinAction(){}
WinAction.prototype.execute = function( hero ){
console.log("Won");
}
function LossAction(){}
LossAction.prototype.execute = function( hero ){
console.log("Loss");
}
function decisionTree() {
var winAction = WinAction();
var lossAction = LossAction();
return new Decision("inteligence", 80,
new Decision("strength", 50, lossAction, winAction),
new Decision("communication", 50, lossAction, winAction));
}
var hero = new Hero();
var tree = decisionTree();
tree.execute( hero );
view raw gistfile1.js hosted with ❤ by GitHub



Reference:








No comments:

Post a Comment