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之eval()函数危险性浅析
Jul 03 Python
Django Highcharts制作图表
Aug 27 Python
Python实现在线暴力破解邮箱账号密码功能示例【测试可用】
Sep 06 Python
Scrapy的简单使用教程
Oct 24 Python
PyQt5每天必学之组合框
Apr 20 Python
Django组件cookie与session的具体使用
Jun 05 Python
pandas计数 value_counts()的使用
Jun 24 Python
python实现证件照换底功能
Aug 20 Python
调试Django时打印SQL语句的日志代码实例
Sep 12 Python
python列表返回重复数据的下标
Feb 10 Python
python和go语言的区别是什么
Jul 20 Python
了解一下python内建模块collections
Sep 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
PHP 已经成熟
2006/12/04 PHP
php park、unpark、ord 函数使用方法(二进制流接口应用实例)
2010/10/19 PHP
解析php 版获取重定向后的地址(代码)
2013/06/26 PHP
PHP的Yii框架入门使用教程
2016/02/15 PHP
JS代码优化技巧之通俗版(减少js体积)
2011/12/23 Javascript
JS+DIV实现鼠标划过切换层效果的实例代码
2013/11/26 Javascript
12种JavaScript常用的MVC框架比较分析
2015/11/16 Javascript
javascript实现别踩白块儿小游戏程序
2015/11/22 Javascript
基于BootStrap环境写jQuery tabs插件
2016/07/12 Javascript
easyUI实现(alert)提示框自动关闭的实例代码
2016/11/07 Javascript
详解如何在Vue2中实现组件props双向绑定
2017/03/29 Javascript
webpack学习教程之前端性能优化总结
2017/12/05 Javascript
手写Node静态资源服务器的实现方法
2018/03/20 Javascript
[原创]微信小程序获取网络类型的方法示例
2019/03/01 Javascript
Python自定义函数的创建、调用和函数的参数详解
2014/03/11 Python
在Python上基于Markov链生成伪随机文本的教程
2015/04/17 Python
Python读取Json字典写入Excel表格的方法
2018/01/03 Python
python根据unicode判断语言类型实例代码
2018/01/17 Python
Django权限机制实现代码详解
2018/02/05 Python
Python中super函数用法实例分析
2019/03/18 Python
python 使用while写猜年龄小游戏过程解析
2019/10/07 Python
python基于celery实现异步任务周期任务定时任务
2019/12/30 Python
tensorflow实现训练变量checkpoint的保存与读取
2020/02/10 Python
Python SMTP配置参数并发送邮件
2020/06/16 Python
英国著名的小众美容品牌网站:Alyaka
2017/08/08 全球购物
Lookfantastic意大利官网:英国知名美妆购物网站
2019/05/31 全球购物
SIMON MILLER官网:洛杉矶的生活方式品牌
2020/10/19 全球购物
数控专业推荐信范文
2013/12/02 职场文书
市场开发与营销专业求职信
2013/12/31 职场文书
支部鉴定材料
2014/06/02 职场文书
2014年英语教研组工作总结
2014/12/06 职场文书
世界卫生日宣传活动总结
2015/02/09 职场文书
经销商会议开幕词
2016/03/04 职场文书
使用react+redux实现计数器功能及遇到问题
2021/06/02 Javascript
如何利用 CSS Overview 面板重构优化你的网站
2021/10/24 HTML / CSS
使用Redis做预定库存缓存功能
2022/04/02 Redis