Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
Merge branch 'experiments/fsm'
- Loading branch information
Showing
5 changed files
with
365 additions
and
258 deletions.
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| function FSM(initial) { | ||
| const NOSTATE = 'none'; | ||
| let currentState = NOSTATE; | ||
| const states = {}; | ||
| const transitions = []; | ||
|
|
||
| this.addState = function(name, enterFunc, updateFunc, exitFunc) { | ||
| states[name] = { | ||
| enter: enterFunc, | ||
| update: updateFunc, | ||
| exit: exitFunc, | ||
| }; | ||
| }; | ||
|
|
||
| this.addTransition = function(statesFrom, stateTo, conditionFunc) { | ||
| transitions.push({ | ||
| from: statesFrom, | ||
| to: stateTo, | ||
| cond: conditionFunc, | ||
| }); | ||
| }; | ||
|
|
||
| this.update = function(deltaTime) { | ||
| if (currentState == NOSTATE) { | ||
| currentState = initial; | ||
| states[currentState].enter(deltaTime); | ||
| } | ||
| states[currentState].update(deltaTime); | ||
| for (let transition of transitions) { | ||
| for (let fromState of transition.from) { | ||
| if (fromState == currentState && transition.cond()) { | ||
| if (DEBUG) { | ||
| console.log('FSM: switch from', fromState, 'to', transition.to); | ||
| } | ||
| states[currentState].exit(deltaTime); | ||
| currentState = transition.to; | ||
| states[currentState].enter(deltaTime); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } |
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
Oops, something went wrong.