Created
May 14, 2022 19:01
-
-
Save nommiin/1633414132b4e93a684874aa08671360 to your computer and use it in GitHub Desktop.
A simple FSM class
This file contains hidden or 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
| function StateManager( start ) constructor { | |
| States = {}; | |
| Current = start; | |
| CurrentRef = undefined; | |
| BaseRef = undefined; | |
| InstanceRef = other; | |
| static Register = function( name, evt ) { | |
| if (!variable_struct_exists(States, name)) { | |
| var names = variable_struct_get_names(evt), events = {}; | |
| for(var i = 0; i < array_length(names); i++) { | |
| events[$ names[i]] = method(InstanceRef, method_get_index(evt[$ names[i]])); | |
| } | |
| States[$ name] = { | |
| Name: name, | |
| Events: events | |
| }; | |
| return self; | |
| } | |
| show_error("Could not create state \"" + string(name) + "\", state already exists", true); | |
| } | |
| static Initialize = function() { | |
| if (States.Base != undefined) BaseRef = States.Base; | |
| if (Current != undefined) { | |
| Change(Current); | |
| } | |
| return self; | |
| } | |
| static Change = function( name ) { | |
| var state = States[$ name]; | |
| if (state != undefined) { | |
| if (CurrentRef != undefined) { | |
| Invoke("Exit"); | |
| } | |
| Current = name; | |
| CurrentRef = state; | |
| Invoke("Enter"); | |
| return; | |
| } | |
| show_error("Could not change to non-existent state \"" + string(name) + "\"", true) | |
| } | |
| static Invoke = function( evt, ref=undefined ) { | |
| var state = (ref != undefined ? ref : CurrentRef); | |
| if (state != undefined) { | |
| if (BaseRef != undefined) { | |
| var base = BaseRef.Events[$ evt]; | |
| if (base != undefined) base(); | |
| } | |
| var event = state.Events[$ evt]; | |
| if (event != undefined) { | |
| return event(); | |
| } | |
| return undefined; | |
| } | |
| show_error("Could not invoke event \"" + string(evt) + "\", current state is not defined", true); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment