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


Posted in Python onMarch 19, 2015

本文实例讲述了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 相关文章推荐
python调用shell的方法
Nov 20 Python
Python 实现简单的shell sed替换功能(实例讲解)
Sep 29 Python
Python进度条实时显示处理进度的示例代码
Jan 30 Python
python如何生成各种随机分布图
Aug 27 Python
python3实现字符串操作的实例代码
Apr 16 Python
Tensorflow实现神经网络拟合线性回归
Jul 19 Python
用python拟合等角螺线的实现示例
Dec 27 Python
python垃圾回收机制(GC)原理解析
Dec 30 Python
PyTorch中的C++扩展实现
Apr 02 Python
TensorFlow2.X结合OpenCV 实现手势识别功能
Apr 08 Python
Python中免验证跳转到内容页的实例代码
Oct 23 Python
Python实现猜拳与猜数字游戏的方法详解
Apr 06 Python
python中日期和时间格式化输出的方法小结
Mar 19 #Python
Python实现抓取城市的PM2.5浓度和排名
Mar 19 #Python
python在windows命令行下输出彩色文字的方法
Mar 19 #Python
python通过colorama模块在控制台输出彩色文字的方法
Mar 19 #Python
python实现颜色rgb和hex相互转换的函数
Mar 19 #Python
python实现从一组颜色中找出与给定颜色最接近颜色的方法
Mar 19 #Python
python遍历类中所有成员的方法
Mar 18 #Python
You might like
咖啡语言
2021/03/03 咖啡文化
hadoop常见错误以及处理方法详解
2013/06/19 PHP
PHP preg_match实现正则表达式匹配功能【输出是否匹配及匹配值】
2017/07/19 PHP
PHP文件管理之实现网盘及压缩包的功能操作
2017/09/20 PHP
PHP中Session ID的实现原理实例分析
2019/08/17 PHP
学习YUI.Ext 第六天--关于树TreePanel(Part 2异步获取节点)
2007/03/10 Javascript
在第一个input框内输入内容.textarea自动得到第一个文件框的值的javascript代码
2007/04/20 Javascript
Ajax执行顺序流程及回调问题分析
2012/12/10 Javascript
CheckBoxList多选样式jquery、C#获取选择项
2013/09/06 Javascript
jquery操作checkbox示例分享
2014/07/21 Javascript
JavaScript onkeypress事件入门实例(按下或按住一个键盘按键)
2014/10/17 Javascript
JavaScript设置、获取、清除单值和多值cookie的方法
2015/11/17 Javascript
第五篇Bootstrap 排版
2016/06/21 Javascript
微信小程序 获取微信OpenId详解及实例代码
2016/10/31 Javascript
手机软键盘弹出时影响布局的解决方法
2016/12/15 Javascript
js实现以最简单的方式将数组元素添加到对象中的方法
2017/12/20 Javascript
node.js中对Event Loop事件循环的理解与应用实例分析
2020/02/14 Javascript
vue 中的动态传参和query传参操作
2020/11/09 Javascript
python根据给定文件返回文件名和扩展名的方法
2015/03/27 Python
编写Python脚本使得web页面上的代码高亮显示
2015/04/24 Python
python抽象基类用法实例分析
2015/06/04 Python
Python爬虫爬取新浪微博内容示例【基于代理IP】
2018/08/03 Python
python通过nmap扫描在线设备并尝试AAA登录(实例代码)
2019/12/30 Python
pytorch中tensor张量数据类型的转化方式
2019/12/31 Python
pycharm 激活码及使用方式的详细教程
2020/05/12 Python
基于CSS3实现的黑色个性导航菜单效果
2015/09/14 HTML / CSS
英国著名的化妆品折扣网站:Allbeauty.com
2016/07/21 全球购物
跑步爱好者一站式服务网站:Jack Rabbit
2016/09/01 全球购物
OLEDBConnection和SQLConnection有什么区别
2013/05/31 面试题
Java面试题:Java类的Main方法如果是Private将会怎么样
2016/08/18 面试题
高一历史教学反思
2014/01/13 职场文书
公司接待方案
2014/03/08 职场文书
大学生村官演讲稿
2014/04/25 职场文书
办公用房租赁协议书
2014/11/29 职场文书
2015年政务公开工作总结
2015/05/19 职场文书
2016年世界艾滋病日宣传活动总结
2016/04/01 职场文书