Python method to implement simple state framework _python

Source: Internet
Author: User
Tags assert shuffle sleep time interval

This example describes Python's approach to implementing a simple state framework. Share to everyone for your reference. The specific analysis is as follows:

Using Python to implement a simple state framework, the code needs to run in a python3.2 environment

Copy Code code as follows:
From time import sleep
From random import randint, shuffle
Class StateMachine (object):
"' Usage:create An instance of StateMachine, use set_starting_state to give it
Initial state to work with, then call Tick () on each second (or whatever your
Time interval might to be. '''
def set_starting_state (self, State):
"The entry state is 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 should occur here. This likely includes adding
Transitions or initializing member variables.
Do_work ()--meat and potatoes of your state. There May is some logic here and would
Cause a transition to trigger.
Exit ()--any cleanup or final actions should 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 as
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 ' 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 ("Walkingstate: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 ("Walkingstate: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, walkingstate ())
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 walk_condition (): Return Self.stamina <= 0
Self.add_transition (Walk_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, walkingstate ())
def do_work (self):
Print ("tripped!")
self.tripped = True
def exit (self):
Print ("Trippingstate:exit ()")
if __name__ = = "__main__":
State = Walkingstate ()
State_machine = StateMachine ()
State_machine.set_starting_state (state)
While True:
State_machine.tick ()
Sleep (1)

I hope this article will help you with your 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.