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使用cookielib库示例分享
Mar 03 Python
Python实现的检测web服务器健康状况的小程序
Sep 17 Python
Linux环境下MySQL-python安装过程分享
Feb 02 Python
在类Unix系统上开始Python3编程入门
Aug 20 Python
Python中字符串的常见操作技巧总结
Jul 28 Python
python list元素为tuple时的排序方法
Apr 18 Python
如何优雅地改进Django中的模板碎片缓存详解
Jul 04 Python
python输入多行字符串的方法总结
Jul 02 Python
python Tcp协议发送和接收信息的例子
Jul 22 Python
python 利用pywifi模块实现连接网络破解wifi密码实时监控网络
Sep 16 Python
信号生成及DFT的python实现方式
Feb 25 Python
安装python依赖包psycopg2来调用postgresql的操作
Jan 01 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把时间戳转换成多少时间之前函数的实例
2016/11/16 PHP
php+layui数据表格实现数据分页渲染代码
2019/10/26 PHP
js Date自定义函数 延迟脚本执行
2010/03/10 Javascript
Javascript中的delete介绍
2012/09/02 Javascript
javascript修改表格背景色实例代码分享
2013/12/10 Javascript
JavaScript中的函数嵌套使用
2015/06/04 Javascript
jQuery插件pagewalkthrough实现引导页效果
2015/07/05 Javascript
jQuery右下角旋转环状菜单特效代码
2015/08/10 Javascript
解决JavaScript数字精度丢失问题的方法
2015/12/03 Javascript
javascript中闭包(Closure)详解
2016/01/06 Javascript
AngularJS实现数据列表的增加、删除和上移下移等功能实例
2016/09/05 Javascript
Bootstrap响应式导航由768px变成992px的实现代码
2017/06/15 Javascript
JS 仿支付宝input文本输入框放大组件的实例
2017/11/14 Javascript
JavaScript实现淘宝京东6位数字支付密码效果
2018/08/18 Javascript
vue-router的使用方法及含参数的配置方法
2018/11/13 Javascript
node运行js获得输出的三种方式示例详解
2020/07/02 Javascript
Vue使用CDN引用项目组件,减少项目体积的步骤
2020/10/30 Javascript
微信小程序onShareTimeline()实现分享朋友圈
2021/01/07 Javascript
[43:41]VP vs RNG 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.21.mp4
2020/07/19 DOTA
Python在Windows和在Linux下调用动态链接库的教程
2015/08/18 Python
Python pandas常用函数详解
2018/02/07 Python
详解用python写网络爬虫-爬取新浪微博评论
2019/05/10 Python
Django 表单模型选择框如何使用分组
2019/05/16 Python
python opencv 读取图片 返回图片某像素点的b,g,r值的实现方法
2019/07/03 Python
python爬虫的一个常见简单js反爬详解
2019/07/09 Python
用css3制作纸张效果(外翻卷角)
2013/02/01 HTML / CSS
CSS3实现的渐变幻灯片效果
2020/12/07 HTML / CSS
html5使用canvas实现跟随光标跳动的火焰效果
2014/01/07 HTML / CSS
HTML5实现多张图片上传功能
2016/03/11 HTML / CSS
Notino希腊:购买香水和美容产品
2019/07/25 全球购物
大学毕业感言50字
2014/02/07 职场文书
2016高考冲刺决心书
2015/09/23 职场文书
员工升职自我评价
2019/03/26 职场文书
SpringRetry重试框架的具体使用
2021/07/25 Java/Android
实现一个简单得数据响应系统
2021/11/11 Javascript
Java存储没有重复元素的数组
2022/04/29 Java/Android