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:
This file contains 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
makeDecision() { | |
if (iq > 80) { | |
negotiation(); | |
if(comunication > 80){ | |
win(); | |
}else{ | |
loss(); | |
} | |
}else{ | |
attack(); | |
if(strength > 80){ | |
win(); | |
}else{ | |
loss(); | |
} | |
} | |
} |
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.
This file contains 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
/** | |
* 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); | |
}; |
Finally, you need to create the tree and let it make the decision:
This file contains 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
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 ); |
Reference:
No comments:
Post a Comment