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读取键盘输入的2种方法
Jun 16 Python
利用python获取Ping结果示例代码
Jul 06 Python
python学习——内置函数、数据结构、标准库的技巧(推荐)
Apr 18 Python
django框架基于模板 生成 excel(xls) 文件操作示例
Jun 19 Python
对Django url的几种使用方式详解
Aug 06 Python
TensorFlow Saver:保存和读取模型参数.ckpt实例
Feb 10 Python
将数据集制作成VOC数据集格式的实例
Feb 17 Python
Python如何使用bokeh包和geojson数据绘制地图
Mar 21 Python
Python实现Wordcloud生成词云图的示例
Mar 30 Python
Python实现数字的格式化输出
Aug 01 Python
python自动化八大定位元素讲解
Jul 09 Python
python处理json数据文件
Apr 11 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
php面向对象全攻略 (四)构造方法与析构方法
2009/09/30 PHP
xss防御之php利用httponly防xss攻击
2014/03/21 PHP
JavaScript数组函数unshift、shift、pop、push使用实例
2014/08/27 Javascript
jquery单行文字向上滚动效果的实现代码
2014/09/05 Javascript
让人蛋疼的JavaScript语法特性
2014/09/30 Javascript
js实现匹配时换色的输入提示特效代码
2015/08/17 Javascript
jQuery垂直多级导航菜单代码分享
2015/08/18 Javascript
跟我学习javascript解决异步编程异常方案
2015/11/23 Javascript
jquery自定义表格样式
2015/11/23 Javascript
详解基于Bootstrap扁平化的后台框架Ace
2015/11/27 Javascript
jstl中判断list中是否包含某个值的简单方法
2016/10/14 Javascript
JS实现点击网页判断是否安装app并打开否则跳转app store
2016/11/18 Javascript
微信小程序中单位rpx和rem的使用
2016/12/06 Javascript
用jQuery实现可输入多选下拉组合框实例代码
2017/01/18 Javascript
微信小程序 在线支付功能的实现
2017/03/14 Javascript
Angularjs之ngModel中的值验证绑定方法
2018/09/13 Javascript
vue项目中使用Svg的方法
2018/10/24 Javascript
详解vue中在循环中使用@mouseenter 和 @mouseleave事件闪烁问题解决方法
2020/04/07 Javascript
js实现从右往左匀速显示图片(无缝轮播)
2020/06/29 Javascript
Python的Django框架中设置日期和字段可选的方法
2015/07/17 Python
浅析Python基础-流程控制
2016/03/18 Python
python利用dir函数查看类中所有成员函数示例代码
2017/09/08 Python
利用Python读取txt文档的方法讲解
2018/06/23 Python
VSCode Python开发环境配置的详细步骤
2019/02/22 Python
Python中格式化字符串的四种实现
2020/05/26 Python
python使用ctypes库调用DLL动态链接库
2020/10/22 Python
英国顶级足球鞋的领先零售商:Lovell Soccer
2019/08/27 全球购物
澳大利亚香水在线商店:City Perfume
2020/09/02 全球购物
NFL官方在线商店:NFLShop
2020/07/29 全球购物
四年的大学生生活自我评价
2013/12/09 职场文书
小学后勤管理制度
2014/01/14 职场文书
拾金不昧通报表扬范文
2015/05/05 职场文书
2019假期福利管理制度!
2019/07/15 职场文书
Redis如何一键部署脚本
2021/04/12 Redis
什么是Python装饰器?如何定义和使用?
2022/04/11 Python
如何Tomcat中使用ipv6地址
2022/05/06 Servers