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 HTTP客户端自定义Cookie实现实例
Apr 28 Python
高效使用Python字典的清单
Apr 04 Python
Python使用pyodbc访问数据库操作方法详解
Jul 05 Python
基于随机梯度下降的矩阵分解推荐算法(python)
Aug 31 Python
python中多个装饰器的调用顺序详解
Jul 16 Python
基于django传递数据到后端的例子
Aug 16 Python
Python学习笔记之函数的参数和返回值的使用
Nov 20 Python
Python实现银行账户资金交易管理系统
Jan 03 Python
基于python实现对文件进行切分行
Apr 26 Python
使用python创建Excel工作簿及工作表过程图解
May 27 Python
利用python 下载bilibili视频
Nov 13 Python
忆童年!用Python实现愤怒的小鸟游戏
Jun 07 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
电脑硬件及电脑配置知识大全
2020/03/17 数码科技
php模拟ping命令(php exec函数的使用方法)
2013/10/25 PHP
PHP实现登陆并抓取微信列表中最新一组微信消息的方法
2017/07/10 PHP
js 巧妙去除数组中的重复项
2010/01/25 Javascript
js注意img图片的onerror事件的分析
2011/01/01 Javascript
javascript学习基础笔记之DOM对象操作
2011/11/03 Javascript
从面试题学习Javascript 面向对象(创建对象)
2012/03/30 Javascript
选择器中含有空格在使用示例及注意事项
2013/07/31 Javascript
Express实现前端后端通信上传图片之存储数据库(mysql)傻瓜式教程(二)
2015/12/10 Javascript
AngularJS入门教程之AngularJS模型
2016/04/18 Javascript
JS清除字符串中重复值的实现方法
2016/08/03 Javascript
BootStrap框架个人总结(bootstrap框架、导航条、下拉菜单、轮播广告carousel、栅格系统布局、标签页tabs、模态框、菜单定位)
2016/12/01 Javascript
jQuery实现Table表格隔行变色及高亮显示当前选择行效果示例
2017/02/14 Javascript
微信小程序之蓝牙的链接
2017/09/26 Javascript
Angular实现的简单查询天气预报功能示例
2017/12/27 Javascript
在vue中v-bind使用三目运算符绑定class的实例
2018/09/29 Javascript
JavaScript使用小插件实现倒计时的方法讲解
2019/03/11 Javascript
解决layer.msg 不居中 ifram中的问题
2019/09/05 Javascript
用Golang运行JavaScript的实现示例
2019/11/25 Javascript
如何构建 vue-ssr 项目的方法步骤
2020/08/04 Javascript
在vs code 中如何创建一个自己的 Vue 模板代码
2020/11/10 Javascript
python技能之数据导出excel的实例代码
2017/08/11 Python
wxPython实现文本框基础组件
2019/11/18 Python
pymysql 插入数据 转义处理方式
2020/03/02 Python
浅谈Python中的生成器和迭代器
2020/06/19 Python
Python装饰器结合递归原理解析
2020/07/02 Python
Python logging日志库空间不足问题解决
2020/09/14 Python
纯CSS3实现漂亮的input输入框动画样式库(Text input love)
2018/12/29 HTML / CSS
深入了解canvas在移动端绘制模糊的问题解决
2019/04/30 HTML / CSS
美国著名童装品牌:OshKosh B’gosh
2016/08/05 全球购物
德国高性价比网上药店:medpex
2017/07/09 全球购物
英国地毯卖家:The Rug Seller
2019/07/18 全球购物
出国留学自荐信
2013/10/25 职场文书
《曹刿论战》教学反思
2014/03/02 职场文书
普通党员对照检查材料
2014/09/24 职场文书
党的群众路线对照检查材料思想汇报
2014/09/25 职场文书