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

作者:chongq 时间:2022-08-20 14:13:44 

本文实例讲述了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,状态,框架,方法
0
投稿

猜你喜欢

  • 深入了解Python iter() 方法的用法

    2023-11-05 02:12:37
  • php字符串使用详细了解

    2023-06-06 04:19:07
  • aspJpeg图片水印有杂点的完美解决方法

    2011-02-05 10:55:00
  • 效控制C#中label输出文字的长度,自动换行

    2023-07-22 04:02:49
  • PHPExcel冻结(锁定)表头的简单实现方法

    2023-08-18 02:35:21
  • 如何将Python字符串转换为JSON的实现方法

    2022-07-11 02:58:37
  • 初学者学习Python好还是Java好

    2021-03-16 21:48:32
  • window.open被浏览器拦截后的自定义提示

    2007-11-23 12:31:00
  • python实现录音功能(可随时停止录音)

    2023-07-29 05:15:06
  • SQL语句练习实例之三——平均销售等待时间

    2011-10-24 20:11:47
  • Mysql触发器处理本表数据

    2010-10-25 19:56:00
  • 十幅图告诉你什么是PHP引用

    2023-10-04 06:16:56
  • Python 网页请求之requests库的使用详解

    2021-01-30 23:42:06
  • PHP实现定时生成HTML网站首页实例代码

    2023-06-12 05:39:40
  • 如何用css制作有趣的按钮

    2008-03-17 13:54:00
  • python子类如何继承父类的实例变量

    2022-05-07 08:41:26
  • 小谈访客浏览器分辨率

    2007-10-18 13:12:00
  • 设计72变——寻求banner制作的变化

    2009-11-12 12:56:00
  • CSS隐藏文字的方法

    2008-10-03 12:08:00
  • 使用python实现excel的Vlookup功能

    2023-05-01 20:15:15
  • asp之家 网络编程 m.aspxhome.com