Python implements a simple State framework.

Source: Internet
Author: User

Python implements a simple State framework.

This example describes how to implement a simple state framework in Python. Share it with you for your reference. The specific analysis is as follows:

Python is used to implement a simple State framework. The code needs to be run in the python3.2 environment.

Copy codeThe Code is as follows: from time import sleep
From random import randint, shuffle
Class StateMachine (object ):
'''Usage: Create an instance of StateMachine, use set_starting_state (state) to give it
Initial state to work with, then call tick () on each second (or whatever your desired
Time interval might be .'''
Def set_starting_state (self, state ):
'''The entry state for The state machine .'''
State. enter ()
Self. state = state
Def tick (self ):
'''Calls the current state's do_work () and checks for a transition '''
Next_state = self. state. check_transitions ()
If next_state is None:
# Stick with this state
Self. state. do_work ()
Else:
# Next state found, transition to it
Self. state. exit ()
Next_state.enter ()
Self. state = next_state
Class BaseState (object ):
'''Usage: Subclass BaseState and override the enter (), do_work (), and exit () methods.
Enter () -- Setup for your state shocould occur here. This likely between des adding
Transitions or initializing member variables.
Do_work () -- Meat and potatoes of your state. There may be some logic here that will
Cause a transition to trigger.
Exit () -- Any cleanup or final actions shoshould occur here. This is called just
Before transition to the next state.
'''
Def add_transition (self, condition, next_state ):
'''Adds a new transition to the state. The "condition" param must contain a callable
Object. When the "condition" evaluates to True, the "next_state" param is set
The active state .'''
# Enforce transition validity
Assert (callable (condition ))
Assert (hasattr (next_state, "enter "))
Assert (callable (next_state.enter ))
Assert (hasattr (next_state, "do_work "))
Assert (callable (next_state.do_work ))
Assert (hasattr (next_state, "exit "))
Assert (callable (next_state.exit ))
# Add transition
If not hasattr (self, "transitions "):
Self. transitions = []
Self. transitions. append (condition, next_state ))
Def check_transitions (self ):
'''Returns the first State thats condition evaluates true (condition order is randomized )'''
If hasattr (self, "transitions "):
Shuffle (self. transitions)
For transition in self. transitions:
Condition, state = transition
If condition ():
Return state
Def enter (self ):
Pass
Def do_work (self ):
Pass
Def exit (self ):
Pass
######################################## ######################################## ##################
############################# Example usage of state machine #### ###############################
######################################## ######################################## ##################
Class WalkingState (BaseState ):
Def enter (self ):
Print ("receivingstate: enter ()")
Def condition (): return randint (1, 5) = 5
Self. add_transition (condition, JoggingState ())
Self. add_transition (condition, RunningState ())
Def do_work (self ):
Print ("Walking ...")
Def exit (self ):
Print ("receivingstate: exit ()")
Class JoggingState (BaseState ):
Def enter (self ):
Print ("JoggingState: enter ()")
Self. stamina = randint (5, 15)
Def condition (): return self. stamina <= 0
Self. add_transition (condition, configuringstate ())
Def do_work (self ):
Self. stamina-= 1
Print ("Jogging ({0})...". format (self. stamina ))
Def exit (self ):
Print ("JoggingState: exit ()")
Class RunningState (BaseState ):
Def enter (self ):
Print ("RunningState: enter ()")
Self. stamina = randint (5, 15)
Def performance_condition (): return self. stamina <= 0
Self. add_transition (condition _condition, WalkingState ())
Def trip_condition (): return randint (1, 10) = 10
Self. add_transition (trip_condition, TrippingState ())
Def do_work (self ):
Self. stamina-= 2
Print ("Running ({0})...". format (self. stamina ))
Def exit (self ):
Print ("RunningState: exit ()")
Class TrippingState (BaseState ):
Def enter (self ):
Print ("TrippingState: enter ()")
Self. tripped = False
Def condition (): return self. tripped
Self. add_transition (condition, configuringstate ())
Def do_work (self ):
Print ("Tripped! ")
Self. tripped = True
Def exit (self ):
Print ("TrippingState: exit ()")
If _ name _ = "_ main __":
State = mongoingstate ()
State_machine = StateMachine ()
State_machine.set_starting_state (state)
While True:
State_machine.tick ()
Sleep (1)

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.