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常见格式化字符串方法小结【百分号与format方法】
Sep 18 Python
python中hashlib模块用法示例
Oct 30 Python
Python 和 JS 有哪些相同之处
Nov 23 Python
Python实现生成随机日期字符串的方法示例
Dec 25 Python
PyQt5每天必学之事件与信号
Apr 20 Python
利用Python进行数据可视化常见的9种方法!超实用!
Jul 11 Python
Python列表(list)所有元素的同一操作解析
Aug 01 Python
Pytorch 实现focal_loss 多类别和二分类示例
Jan 14 Python
python画图常规设置方式
Mar 05 Python
python 爬虫爬取京东ps4售卖情况
Dec 18 Python
python实现录制全屏和选择区域录屏功能
Feb 05 Python
python 三种方法提取pdf中的图片
Feb 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中取得image按钮传递的name值
2006/10/09 PHP
discuz 首页四格:最新话题+最新回复+热门话题+精华文章插件
2007/08/19 PHP
PHP similar_text 字符串的相似性比较函数
2010/05/26 PHP
php的数组与字符串的转换函数整理汇总
2013/07/18 PHP
浅谈php中include文件变量作用域
2015/06/18 PHP
php set_include_path函数设置 include_path 配置选项
2016/10/30 PHP
php简单检测404页面的方法示例
2019/08/23 PHP
javascript实现的在当前窗口中漂浮框的代码
2010/03/15 Javascript
js截取固定长度的中英文字符的简单实例
2013/11/22 Javascript
jQuery简单实现遍历数组的方法
2015/04/14 Javascript
JavaScrip常见的一些算法总结
2015/12/28 Javascript
基于vue框架手写一个notify插件实现通知功能的方法
2019/03/31 Javascript
vue项目部署到nginx/tomcat服务器的实现
2019/08/26 Javascript
微信小程序一周时间表功能实现
2019/10/17 Javascript
vue打开新窗口并实现传参的图文实例
2021/03/04 Vue.js
python赋值操作方法分享
2013/03/23 Python
Centos5.x下升级python到python2.7版本教程
2015/02/14 Python
django fernet fields字段加密实践详解
2019/08/12 Python
python实现ip地址的包含关系判断
2020/02/07 Python
在matplotlib中改变figure的布局和大小实例
2020/04/23 Python
解决pymysql cursor.fetchall() 获取不到数据的问题
2020/05/15 Python
Python实现随机爬山算法
2021/01/29 Python
英国最大的自有市场,比亚马逊便宜:Flubit
2019/03/19 全球购物
垃圾回收的优点和原理
2014/05/16 面试题
Boolean b = new Boolean(“abcde”); 会编译错误码
2013/11/27 面试题
思想品德自我鉴定
2013/10/12 职场文书
大学生应聘推荐信范文
2013/11/19 职场文书
烹调加工管理制度
2014/02/04 职场文书
铁路工务反思材料
2014/02/07 职场文书
幼儿园大班家长评语
2014/04/17 职场文书
合作协议书怎么写
2014/04/18 职场文书
法学自荐信
2014/06/20 职场文书
会计工作检讨书
2015/02/19 职场文书
电影开国大典观后感
2015/06/04 职场文书
初中团委工作总结
2015/08/13 职场文书
浅谈react useEffect闭包的坑
2021/06/08 Javascript