Skip to content

Instantly share code, notes, and snippets.

@troufster
Created January 11, 2011 11:16
Show Gist options
  • Save troufster/774308 to your computer and use it in GitHub Desktop.
Save troufster/774308 to your computer and use it in GitHub Desktop.
fsm.js
/**
* Hairy Balls FSM
*
*/
var FSM = function(s, is) {
this.states = s;
this.iState = is;
this.curState = is;
}
FSM.prototype.update = function(agent) {
//Evaluate current state transition triggers
var trans = this.states[this.curState]['Trans'];
var newState = null;
var actions = []; //Actions to perform
for (var t in trans) {
if(trans[t].func(agent)) {
newState = trans[t].transTo;
actions.push(this.states[this.curState].exit);
actions.push(this.states[newState].entry);
break;
}
}
if(newState) {
this.curState = newState;
//Trigger entry/exit actions
for (var f in actions) {
actions[f](agent);
}
return;
}
//No transitions triggered, run current state func
this.states[this.curState].func(agent);
}
var block = {
'Chillaxing' : {
func: function(agent) {
console.log('Just chillaxing');
},
entry: function(agent) {
console.log('Going to bed');
},
exit : function(agent) {
console.log('Getting out of bed');
},
'Trans' : {
'Rested -> Work' : {
func : function(agent) {
return agent.sleep > 5;
},
transTo : 'Working'
}
}
},
'Working' : {
func : function(agent) {
console.log("At work!");
},
entry : function(agent) {
console.log("Going to work");
},
exit : function(agent){
console.log("Leaving work");
},
'Trans' : {
'Tired -> Chillaxing' : {
func : function(agent) {
return agent.sleep < 5;
},
transTo : 'Chillaxing'
}
}
}
}
var fsm = new FSM(block,'Chillaxing');
fsm.update({sleep:3});
fsm.update({sleep:10});
fsm.update({sleep:10});
fsm.update({sleep:3});
fsm.update({sleep:3});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment