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 相关文章推荐
Django1.3添加app提示模块不存在的解决方法
Aug 26 Python
Python3中使用PyMongo的方法详解
Jul 28 Python
Python基础之getpass模块详细介绍
Aug 10 Python
详解pandas库pd.read_excel操作读取excel文件参数整理与实例
Feb 17 Python
OpenCV搞定腾讯滑块验证码的实现代码
May 18 Python
浅析Python3中的对象垃圾收集机制
Jun 06 Python
Python中IP地址处理IPy模块的方法
Aug 16 Python
Python hashlib常见摘要算法详解
Jan 13 Python
python 回溯法模板详解
Feb 26 Python
pandas DataFrame运算的实现
Jun 14 Python
Python 字典一个键对应多个值的方法
Sep 29 Python
利用Python pandas对Excel进行合并的方法示例
Nov 04 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
手把手教你使用DedeCms的采集的图文教程
2007/03/11 PHP
PHP 简易输出CSV表格文件的方法详解
2013/06/20 PHP
使用HMAC-SHA1签名方法详解
2013/06/26 PHP
ASP和PHP实现生成网站快捷方式并下载到桌面的方法
2014/05/08 PHP
windows server 2008/2012安装php iis7 mysql环境搭建教程
2016/06/30 PHP
Yii框架函数简单用法分析
2019/09/09 PHP
JavaScript 异步调用框架 (Part 1 - 问题 &amp; 场景)
2009/08/03 Javascript
jquery实现滑动图片自己测试的例子
2013/11/05 Javascript
分享一个常用的javascript静态类
2014/12/31 Javascript
基于jQuery实现的旋转彩圈实例
2015/06/26 Javascript
基于AngularJS前端云组件最佳实践
2016/10/20 Javascript
基于JavaScript实现新增内容滚动播放效果附完整代码
2017/08/24 Javascript
VueJs 搭建Axios接口请求工具
2017/11/20 Javascript
浅谈React中组件间抽象
2018/01/27 Javascript
mpvue小程序仿qq左滑置顶删除组件
2018/08/03 Javascript
详解js静态检查工具eslint配置文件
2018/11/23 Javascript
Vue中import from的来源及省略后缀与加载文件夹问题
2020/02/09 Javascript
Vue通过getAction的finally来最大程度避免影响主数据呈现问题
2020/04/24 Javascript
Python中使用ConfigParser解析ini配置文件实例
2014/08/30 Python
在Python的Django框架中为代码添加注释的方法
2015/07/16 Python
Python的Django框架下管理站点的基本方法
2015/07/17 Python
Python常用知识点汇总
2016/05/08 Python
今天 平安夜 Python 送你一顶圣诞帽 @微信官方
2017/12/25 Python
python opencv 图像尺寸变换方法
2018/04/02 Python
python实现监控某个服务 服务崩溃即发送邮件报告
2018/06/21 Python
python Pandas如何对数据集随机抽样
2019/07/29 Python
python 画出使用分类器得到的决策边界
2019/08/21 Python
使用PyCharm安装pytest及requests的问题
2020/07/31 Python
实习生自我评价
2014/01/18 职场文书
婚礼司仪主持词
2014/03/14 职场文书
铁路安全反思材料
2014/12/24 职场文书
交通事故赔偿起诉书
2015/05/20 职场文书
春风化雨观后感
2015/06/11 职场文书
《植物妈妈有办法》教学反思
2016/02/23 职场文书
Python实现数据的序列化操作详解
2022/07/07 Python
阿里云服务器(windows)手动部署FTP站点详细教程
2022/08/05 Servers