# # state machine # class State: INITIAL = 0 YIELDING = 1 # pseudo-state TERMINAL = 2 FIRSTUSER = 3 def __init__(self, id, on_entry, todo, on_exit, arcs): self._id = id self._on_entry = on_entry self._todo = todo self._on_exit = exit self._arcs = arcs def on_entry( machine, context ): if self._on_entry: return self._on_entry( machine, context ) else: return True class Arc: def __init__(self, dest_id, trigger, guard, action): self._dest_id = dest_id self._trigger = trigger self._guard = guard self._action = action class Event: def __init__(self): self._mask = Event.NULL def produce(self, mask): self._mask |= mask return self._mask def inspect(self, mask): return self._mask & mask def consume(self, mask): _mask = self._mask self._mask &= ~mask return _mask Event.NULL = 0x00000000 Event.ENTRY_FAIL = 0x01000000 class Machine: def __init__(self, states, context): self._states = states self._stack = [] self._events = Event() self._cur_state = State.INITIAL self._context = context def run(self): state = self._states[self._cur_state] while state != State.TERMINAL: if not state.on_entry( self, context): self._events.produce( Event.ENTRY_FAIL ) print( Event.NULL ) print( "0x%08x" % Event.ENTRY_FAIL )
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question