Skip to content

Instantly share code, notes, and snippets.

@maryrosecook
Created May 25, 2011 16:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maryrosecook/991347 to your computer and use it in GitHub Desktop.
Save maryrosecook/991347 to your computer and use it in GitHub Desktop.
Examples for Machine.js
var landscape = new Landscape(); // one actor
// make instance of Machine and get the root nodes for each actor
var machine = new Machine();
landscape.state = machine.generateTree(landscapeJson, landscape);
// every second, something happens in the ecosystem
setTimeout("step()", 1000);
var step = function() {
// trigger the next state transition
landscape.state = landscape.state.tick();
}
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="machine.js"></script>
// the landscape object - rains or is sunny
function Landscape() {
this.groundwater = 0;
this.oxygen = 0;
}
Landscape.prototype = {
hasWater: function() { return this.groundwater > 0; },
giveWater: function() {
this.groundwater -= 1;
return 1;
},
oxygenate: function() { this.oxygen += 1; },
};
var landscapeBehaviourJson = {
identifier: "idle", strategy: "sequential",
children: [
{ identifier: "shine" },
{ identifier: "rain" },
]
};
Landscape.states = {
idle: function() { },
rain: function() { this.groundwater += 1; },
canRain: function() { return Math.random() > 0.5; },
shine: function() { }, // nothing to do - just a state
canShine: function() { return Math.random() > 0.1; },
isShining: function() { return this.state.identifier == "shine"; },
};
var soldierBehaviourJson = {
identifier: "idle", strategy: "sequential",
children: [
{
identifier: "fight", strategy: "prioritised",
children: [
{ identifier: "shoot" }
]
},
{
identifier: "returnToBase", strategy: "prioritised",
children: [
{ identifier: "plotCourseToBase" },
{ identifier: "followCourseToBase" }
]
}
]
};
var returnToBase = function() {
this.state = this.state.warp("returnToBase");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment