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 基础学习教程
Feb 08 Python
phpsir 开发 一个检测百度关键字网站排名的python 程序
Sep 17 Python
Python中实现远程调用(RPC、RMI)简单例子
Apr 28 Python
python中Flask框架简单入门实例
Mar 21 Python
基于Python3 逗号代码 和 字符图网格(详谈)
Jun 22 Python
Python二叉搜索树与双向链表转换算法示例
Mar 02 Python
简单了解Python生成器是什么
Jul 02 Python
Python 旋转打印各种矩形的方法
Jul 09 Python
Python数学形态学实例分析
Sep 06 Python
python tkinter图形界面代码统计工具
Sep 18 Python
pytest进阶教程之fixture函数详解
Mar 29 Python
Python基本数据类型之字符串str
Jul 21 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
memcached 和 mysql 主从环境下php开发代码详解
2010/05/16 PHP
PHP中加速、缓存扩展的区别和作用详解(eAccelerator、memcached、xcache、APC )
2016/07/09 PHP
简述php环境搭建与配置
2016/12/05 PHP
实例讲解PHP中使用命名空间
2019/01/27 PHP
PHP递归算法的简单实例
2019/02/28 PHP
Aster vs Newbee BO5 第一场2.19
2021/03/10 DOTA
语义化 H1 标签
2008/01/14 Javascript
一段利用WSH修改和查看IP配置的代码
2008/05/11 Javascript
Jquery+WebService 校验账号是否已被注册的代码
2010/07/12 Javascript
javascript学习笔记(十) js对象 继承
2012/06/19 Javascript
js实现简单登录功能的实例代码
2013/11/09 Javascript
JS+CSS 制作的超级简单的下拉菜单附图
2013/11/22 Javascript
javascript中定义私有方法说明(private method)
2014/01/27 Javascript
JavaScript检测浏览器cookie是否已经启动的方法
2015/02/27 Javascript
基于jQuery+JSON的省市二三级联动效果
2015/06/05 Javascript
JS延时提示框实现方法详解
2015/11/26 Javascript
深入理解angularjs过滤器
2016/05/25 Javascript
BootStrap使用file-input插件上传图片的方法
2016/09/05 Javascript
JS实现的五级联动菜单效果完整实例
2017/02/23 Javascript
nodejs中向HTTP响应传送进程的输出
2017/03/19 NodeJs
关于vue-router的beforeEach无限循环的问题解决
2017/09/09 Javascript
基于Datatables跳转到指定页的简单实例
2017/11/09 Javascript
js实现九宫格抽奖
2020/03/19 Javascript
[06:20]2015国际邀请赛第三日top10
2015/08/08 DOTA
利用Python2下载单张图片与爬取网页图片实例代码
2017/12/25 Python
pandas使用get_dummies进行one-hot编码的方法
2018/07/10 Python
Python3 Tkinkter + SQLite实现登录和注册界面
2019/11/19 Python
python创建n行m列数组示例
2019/12/02 Python
python3 logging日志封装实例
2020/04/08 Python
翻转数列python实现,求前n项和,并能输出整个数列的案例
2020/05/03 Python
python 制作本地应用搜索工具
2021/02/27 Python
CSS3教程(6):创建网站多列
2009/04/02 HTML / CSS
审计工作个人的自我评价
2013/12/25 职场文书
中学运动会广播稿
2014/01/19 职场文书
德语专业求职信
2014/03/12 职场文书
2014年社会实践活动总结范文
2014/04/29 职场文书