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实现的可以拷贝或剪切一个文件列表中的所有文件
Apr 30 Python
Python实现的端口扫描功能示例
Apr 08 Python
利用Python实现微信找房机器人实例教程
Mar 10 Python
详解Python图像处理库Pillow常用使用方法
Sep 02 Python
python中的TCP(传输控制协议)用法实例分析
Nov 15 Python
详解python中各种文件打开模式
Jan 19 Python
解决pytorch-yolov3 train 报错的问题
Feb 18 Python
django filter过滤器实现显示某个类型指定字段不同值方式
Jul 16 Python
python 获取字典键值对的实现
Nov 12 Python
Python大批量搜索引擎图像爬虫工具详解
Nov 16 Python
python 如何停止一个死循环的线程
Nov 24 Python
Python中使用Lambda函数的5种用法
Apr 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
2020显卡排行榜天梯图 显卡天梯图2020年3月最新版
2020/04/02 数码科技
PHP限制HTML内容中图片必须是本站的方法
2015/06/16 PHP
浅谈php+phpStorm+xdebug配置方法
2015/09/17 PHP
Yii2框架dropDownList下拉菜单用法实例分析
2016/07/18 PHP
js动态创建、删除表格示例代码
2013/08/07 Javascript
jquery中的查找parents与closest方法之间的区别
2013/12/02 Javascript
Js实现双击鼠标自动滚动屏幕的示例代码
2013/12/14 Javascript
js实现发送验证码后的倒计时功能
2015/05/28 Javascript
简介JavaScript中用于处理正切的Math.tan()方法
2015/06/15 Javascript
基于javascript代码实现通过点击图片显示原图片
2015/11/29 Javascript
AngularJS基础 ng-class-odd 指令示例
2016/08/01 Javascript
xtemplate node.js 的使用方法实例解析
2016/08/22 Javascript
Node.js用readline模块实现输入输出
2016/12/16 Javascript
Node.js中如何合并两个复杂对象详解
2016/12/31 Javascript
详解vue与后端数据交互(ajax):vue-resource
2017/03/16 Javascript
利用JavaScript的%做隔行换色的实例
2017/11/25 Javascript
在vue中使用Autoprefixed的方法
2018/07/27 Javascript
微信{"errcode":48001,"errmsg":"api unauthorized, hints: [ req_id: 1QoCla0699ns81 ]"}
2018/10/12 Javascript
分析在Python中何种情况下需要使用断言
2015/04/01 Python
python制作企业邮箱的爆破脚本
2016/10/05 Python
pandas实现选取特定索引的行
2018/04/20 Python
Python实现base64编码的图片保存到本地功能示例
2018/06/22 Python
python opencv判断图像是否为空的实例
2019/01/26 Python
Python定义函数功能与用法实例详解
2019/04/08 Python
python获取Pandas列名的几种方法
2019/08/07 Python
Python3 元组tuple入门基础
2020/02/09 Python
使用CSS变量实现炫酷惊人的悬浮效果
2019/04/26 HTML / CSS
HTML5中使用postMessage实现两个网页间传递数据
2016/06/22 HTML / CSS
美国女孩洋娃娃店:American Girl
2017/10/24 全球购物
UNIONBAY官网:美国青少年服装品牌
2019/03/26 全球购物
TecoBuy澳大利亚:在线电子和小工具商店
2020/06/25 全球购物
2014年防汛工作总结
2014/12/08 职场文书
计划生育目标责任书
2015/05/09 职场文书
暖春观后感
2015/06/08 职场文书
2016年主题党日活动总结
2016/04/05 职场文书
html form表单基础入门案例讲解
2021/07/21 HTML / CSS