Python实现简单状态框架的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下:

这里使用Python实现一个简单的状态框架,代码需要在python3.2环境下运行

复制代码 代码如下:
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 an
        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 should occur here.  This likely includes 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 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 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("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)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python开发之IDEL(Python GUI)的使用方法图文详解

python开发之IDEL(Python GUI)的使用方法图文详解

本文讲述了python开发之IDEL(Python GUI)的使用方法。分享给大家供大家参考,具体如下: 在安装完Python后,我们希望能够运用python GUI来运行一些我们编写的...

深入理解python中的浅拷贝和深拷贝

深入理解python中的浅拷贝和深拷贝

在讲什么是深浅拷贝之前,我们先来看这样一个现象: a = ['scolia', 123, [], ] b = a[:] b[2].append(666) print a print...

Python实现翻转数组功能示例

本文实例讲述了Python实现翻转数组功能。分享给大家供大家参考,具体如下: 题目描述 给定一个长度为n的整数数组a,元素均不相同,问数组是否存在这样一个片段,只将该片段翻转就可以使整个...

Python实现Smtplib发送带有各种附件的邮件实例

Python实现Smtplib发送带有各种附件的邮件实例

这两天对Python的邮件模块比较感兴趣,于是就查了查资料。同时在实际的编码过程中也遇到了各种各样的问题。下面我就来分享一下我与smtplib的故事。 前提条件 我的上一篇博文里面讲解了...

Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作

本文实例讲述了Python在字符串的开头或结尾处进行文本匹配操作。分享给大家供大家参考,具体如下: 问题:在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、URL协议...