Created
October 2, 2012 23:27
-
-
Save zackdever/3823971 to your computer and use it in GitHub Desktop.
a simple python state machine
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
class StateMachine(object): | |
"""the brain - manages states""" | |
def __init__(self): | |
self.states = {} | |
self.active_state = None | |
def add_state(self, state): | |
"""Adds a new state""" | |
self.states[state.name] = state | |
def think(self): | |
""" | |
Does whatever the current state instructs | |
and changes to new state if needed. | |
""" | |
if self.active_state is not None: | |
self.active_state.do_actions() | |
new_state_name = self.active_state.check_conditions() | |
if new_state_name is not None: | |
self.set_state(new_state_name) | |
def set_state(self, new_state_name): | |
"""Changes states and performs appropriate exit and entry actions.""" | |
if self.active_state is not None: | |
self.active_state.exit_actions() | |
self.active_state = self.states[new_state_name] | |
self.active_state.__entry_actions__() | |
class State(object): | |
"""An abstract state.""" | |
def __init__(self, name): | |
self.name = name | |
def __entry_actions__(self): | |
"""Perform these actions when this state is first entered.""" | |
self.entry_actions() | |
def do_actions(self): | |
"""Perform these actions when in this state.""" | |
pass | |
def check_conditions(self): | |
"""Check these conditions to see if state should be changed.""" | |
pass | |
def entry_actions(self): | |
"""Perform these actions when this state is first entered.""" | |
pass | |
def exit_actions(self): | |
"""Perform these actions when this state is exited.""" | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment