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 django集成cas验证系统
Jul 14 Python
Python解析json文件相关知识学习
Mar 01 Python
编写Python爬虫抓取暴走漫画上gif图片的实例分享
Apr 20 Python
Python入门_浅谈字符串的分片与索引、字符串的方法
May 16 Python
python如何爬取网站数据并进行数据可视化
Jul 08 Python
python读取指定字节长度的文本方法
Aug 27 Python
如何基于Python获取图片的物理尺寸
Nov 25 Python
解决Pycharm 运行后没有输出的问题
Feb 05 Python
解决python绘图使用subplots出现标题重叠的问题
Apr 30 Python
python 多态 协议 鸭子类型详解
Nov 27 Python
opencv深入浅出了解机器学习和深度学习
Mar 17 Python
详解OpenCV曝光融合
Apr 29 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
Zend Studio (eclipse)使用速度优化方法
2011/03/23 PHP
Notice: Trying to get property of non-object problem(PHP)解决办法
2012/03/11 PHP
使用PHP破解防盗链图片的一个简单方法
2014/06/07 PHP
自己写的php中文截取函数mb_strlen和mb_substr
2015/02/09 PHP
javascript getElementsByClassName 和js取地址栏参数
2010/01/02 Javascript
javascript最常用与实用的创建类的代码
2010/08/12 Javascript
js实现运动logo图片效果及运动元素对象sportBox使用方法
2012/12/25 Javascript
借助javascript代码判断网页是静态还是伪静态
2014/05/05 Javascript
jQuery中end()方法用法实例
2015/01/08 Javascript
跟我学习javascript的函数调用和构造函数调用
2015/11/16 Javascript
JavaScript原生xmlHttp与jquery的ajax方法json数据格式实例
2015/12/04 Javascript
浅析JavaScript中命名空间namespace模式
2016/06/22 Javascript
微信小程序实现实时圆形进度条的方法示例
2017/02/24 Javascript
微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传
2017/04/18 Javascript
深究AngularJS如何获取input的焦点(自定义指令)
2017/06/12 Javascript
Angularjs 根据一个select的值去设置另一个select的值方法
2018/08/13 Javascript
vue实现重置表单信息为空的方法
2018/09/29 Javascript
vue中$refs, $emit, $on, $once, $off的使用详解
2019/05/26 Javascript
使用vue实现各类弹出框组件
2019/07/03 Javascript
Vue实现商品分类菜单数量提示功能
2019/07/26 Javascript
vue router 传参获取不到的解决方式
2019/11/13 Javascript
[00:23]DOTA2群星共贺开放测试 25日无码时代来袭
2013/09/23 DOTA
Python入门篇之函数
2014/10/20 Python
Python实现从SQL型数据库读写dataframe型数据的方法【基于pandas】
2019/03/18 Python
PyCharm 创建指定版本的 Django(超详图解教程)
2019/06/18 Python
python求绝对值的三种方法小结
2019/12/04 Python
python numpy矩阵信息说明,shape,size,dtype
2020/05/22 Python
python实现批处理文件
2020/07/28 Python
HTML5调用手机发短信和打电话功能
2020/04/29 HTML / CSS
TripAdvisor日本:全球领先的旅游网站
2019/02/14 全球购物
高中毕业自我鉴定
2013/12/16 职场文书
电子信息专业自荐书
2014/02/04 职场文书
借款协议书范本
2014/04/22 职场文书
Django项目如何正确配置日志(logging)
2021/04/29 Python
MySQL8.0升级的踩坑历险记
2021/11/01 MySQL
python编程实现清理微信重复缓存文件
2021/11/01 Python