Skip to content

Instantly share code, notes, and snippets.

@oleganza
Created March 11, 2009 10:03
Show Gist options
  • Save oleganza/77396 to your computer and use it in GitHub Desktop.
Save oleganza/77396 to your computer and use it in GitHub Desktop.
/*
The simplest possible state machine implementation in AS3.
Author: Oleg Andreev <oleganza@gmail.com>
Date: March 11, 2009
Example:
// If you single hit spacebar, you just trigger play/pause state.
// But if you hold the button for a little while, the state
// will be restored when you release the key.
var spaceBarSM = new StateMachine(
"play",
{
play: { down: "prepause" },
prepause: {up: "pause", down: "holdpause" },
holdpause: {up: "play" },
pause: { down: "preplay" },
preplay: {up: "play", down: "holdplay" },
holdplay: {up: "pause" }
}
)
spaceBarSM.addEventListener("play:down", streamPause)
spaceBarSM.addEventListener("holdplay:up", streamPause)
spaceBarSM.addEventListener("pause:down", streamPlay)
spaceBarSM.addEventListener("holdpause:up", streamPlay)
// do this in onKeyUp event listener:
spaceBarSM.fire("up")
*/
package pierlis.framework
{
import flash.events.*
import pierlis.framework.*
public class StateMachine extends EventDispatcher
{
public var state:String
public var transitions:Object
public function StateMachine(initialState:String, _transitions:Object)
{
state = initialState
transitions = _transitions
}
public function fire(event:String)
{
var state1 = state
var state2 = transitions[state1][event]
if (state2)
{
state = state2
dispatchEvent(new Event(state1 + ":" + event)) // "play:down"
dispatchEvent(new Event("exit " + state1)) // "exit play"
dispatchEvent(new Event("enter " + state2)) // "enter prepause"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment