Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 151 lines (120 sloc) 5.858 kB
844542b @stephenb adding array support in the event's "from" value and passing
authored
1 Description:
2 ------------
3
4 A simple state machine written in CoffeeScript.
5
6 Sample Usage:
7 ------
8
9 A "StateMachine" class is provided that can be used as the basis of your state machine implementation.
10 The object passed in to the constructor has an expected format that will define the state machine.
11 The sample stuff below will use a chess game as a basic example.
12
13 Step one will always be to require the state machine:
14
15 {StateMachine} = require 'state_machine'
16
17 The StateMachine class' constructor takes in an object that defines the entire state machine.
18 Here's what it looks like:
19
20 states:
21 stateName:
22 active: true/false (optional, the 1st state defaults to true)
23 onEnter: enterMethod (called when successfully entering the state)
24 onExit: exitMethod (called when successfully exiting the state)
25 guard: guardMethod (stops the change to this state if returns false)
26 stateName2: etc...
27 events:
28 eventName:
29 from: fromState (should be a defined state, or "any")
30 to: toState (should be a defined state)
31 eventName2: etc...
32 onStateChange: changeMethod (called on any state change)
33
34 If you don't need anything fancy on the states, then you can use a basic Array setup:
35
36 game = new StateMachine states: ['whiteToMove', 'blackToMove']
37
38 game.availableStates()
39 # outputs: [ 'whiteToMove', 'blackToMove' ]
40 game.currentState()
41 # outputs: 'whiteToMove'
42
43 But, you should really define some *events* that will trigger state changes. Each
44 defined event gives you a method you can call to trigger the state change.
45
46 class ChessGame extends StateMachine
47 switchSides: ->
48 # ...
49 console.log "switchSides called."
50
51 game = new ChessGame
52 states:
53 whiteToMove:
54 onEnter: -> this.switchSides()
55 blackToMove:
56 onEnter: -> this.switchSides()
57 events:
58 whiteMoved: {from:'whiteToMove', to:'blackToMove'}
59 blackMoved: {from:'blackToMove', to:'whiteToMove'}
60
61 game.whiteMoved()
62 # outputs: switchSides called.
63
64 You can also pass the states definition to the defineStateMachine method. So, a more custom
65 and comprehensive implementation may look like:
66
67 class ChessGame extends StateMachine
68 constructor: (@board, @pieces) ->
69 @defineStateMachine
70 states:
71 whiteToMove:
72 # If black was in check, sides can't switch unless they're now not in check
73 guard: (args) -> not (args.from is 'blackInCheck' and this.blackKingInCheck())
74 onEnter: -> this.deliverMessage('white', 'Your move.')
75 blackToMove:
76 guard: (args) -> not (args.from is 'whiteInCheck' and this.whiteKingInCheck())
77 onEnter: -> this.deliverMessage('black', 'Your move.')
78 whiteInCheck:
79 onEnter: -> this.deliverMessage('white', 'Check!')
80 onExit: -> this.deliverMessage('white', 'Check escaped.')
81 blackInCheck:
82 onEnter: -> this.deliverMessage('black', 'Check!')
83 onExit: -> this.deliverMessage('black', 'Check escaped.')
84 whiteCheckmated:
85 onEnter: ->
86 this.deliverMessage('white', 'Checkmate, you lose :-(')
87 this.deliverMessage('black', 'Checkmate, you win!')
88 blackCheckmated:
89 onEnter: ->
90 this.deliverMessage('black', 'Checkmate, you lose :-(')
91 this.deliverMessage('white', 'Checkmate, you win!')
92 events:
93 whiteMoved: { from: 'whiteToMove', to: 'blackToMove' }
94 whiteChecked: { from: ['blackToMove', 'blackInCheck'], to: 'whiteInCheck' }
95 whiteCheckMated: { from: ['blackToMove', 'blackInCheck'], to: 'whiteCheckmated' }
96 blackMoved: { from: 'blackToMove', to: 'whiteToMove' }
97 blackChecked: { from: ['whiteToMove', 'whiteInCheck'], to: 'blackInCheck' }
98 blackCheckMated: { from: ['whitetoMove', 'whiteInCheck'], to: 'blackCheckmated' }
99 onStateChange: (args) -> this.logActivity(args.from, args.to, args.event)
100
101 blackKingInCheck: ->
102 # ...
103
104 whiteKingInCheck: ->
105 # ...
106
107 deliverMessage: (playerColor, message) ->
108 console.log "[Message to #{playerColor}] #{message}"
109
110 logActivity: (from, to, event) ->
111 console.log "Activity: from => #{from}, to => #{to}, event => #{event}"
112
113 ##################################
114
115 game = new ChessGame
116
117 game.whiteMoved()
118 # outputs:
119 # [Message to black] Your move.
120 # Activity: from => whiteToMove, to => blackToMove, event => whiteMoved
121
122 game.blackMoved()
123 # outputs:
124 # [Message to white] Your move.
125 # Activity: from => blackToMove, to => whiteToMove, event => blackMoved
126
127 game.blackChecked()
128 # outputs:
129 # [Message to black] Check!
130 # Activity: from => whiteToMove, to => blackInCheck, event => blackChecked
131
132 game.whiteCheckMated()
133 # outputs:
134 # [Message to black] Check escaped.
135 # [Message to white] Checkmate, you lose :-(
136 # [Message to black] Checkmate, you win!
137 # Activity: from => blackInCheck, to => whiteCheckmated, event => whiteCheckMated
138
139 try
140 game.blackMoved()
141 catch error
142 console.log error
143 # outputs:
144 # Cannot change from state 'blackToMove'; it is not the active state!
145
146
147 Note that each callback method (onEnter, onExit, guard, and onStateChange) gets passed an args object that
148 has a "from", "to", and "event" key, providing the previous state, new state, and the
149 event that triggered the state change.
150
Something went wrong with that request. Please try again.