Created
August 27, 2024 21:18
-
-
Save firebelley/96f2f82e3feaa2756fe647d8b9843174 to your computer and use it in GitHub Desktop.
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
| class_name CallableStateMachine | |
| var state_dictionary = {} | |
| var current_state: String | |
| func add_states( | |
| normal_state_callable: Callable, | |
| enter_state_callable: Callable, | |
| leave_state_callable: Callable | |
| ): | |
| state_dictionary[normal_state_callable.get_method()] = { | |
| "normal": normal_state_callable, | |
| "enter": enter_state_callable, | |
| "leave": leave_state_callable | |
| } | |
| func set_initial_state(state_callable: Callable): | |
| var state_name = state_callable.get_method() | |
| if state_dictionary.has(state_name): | |
| _set_state(state_name) | |
| else: | |
| push_warning("No state with name " + state_name) | |
| func update(): | |
| if current_state != null: | |
| (state_dictionary[current_state].normal as Callable).call() | |
| func change_state(state_callable: Callable): | |
| var state_name = state_callable.get_method() | |
| if state_dictionary.has(state_name): | |
| _set_state.call_deferred(state_name) | |
| else: | |
| push_warning("No state with name " + state_name) | |
| func _set_state(state_name: String): | |
| if current_state: | |
| var leave_callable = state_dictionary[current_state].leave as Callable | |
| if !leave_callable.is_null(): | |
| leave_callable.call() | |
| current_state = state_name | |
| var enter_callable = state_dictionary[current_state].enter as Callable | |
| if !enter_callable.is_null(): | |
| enter_callable.call() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Throwing my hat in the ring with a simpler version using State objects defined inside the StateMachine class. I include an example of how .. concise it can be used. Granted, you dont have to use only lambdas like i am here, but I think it is pretty neat that you can.
https://gist.github.com/alkemann/481252a7f8d3d84e606a049a3d6c6b9d