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 27 Python
python数组过滤实现方法
Jul 27 Python
Python二分查找详解
Sep 13 Python
Python正则获取、过滤或者替换HTML标签的方法
Jan 28 Python
python 删除指定时间间隔之前的文件实例
Apr 24 Python
Python 保存矩阵为Excel的实现方法
Jan 28 Python
python 对字典按照value进行排序的方法
May 09 Python
python 魔法函数实例及解析
Sep 25 Python
Django实现文件上传下载
Oct 06 Python
在django中实现choices字段获取对应字段值
Jul 12 Python
OpenCV图片漫画效果的实现示例
Aug 18 Python
上手简单,功能强大的Python爬虫框架——feapder
Apr 27 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开发文件系统实例讲解
2006/10/09 PHP
教你识别简单的免查杀PHP后门
2015/09/13 PHP
ThinkPHP5.1框架数据库链接和增删改查操作示例
2019/08/03 PHP
laravel model 两表联查示例
2019/10/24 PHP
a标签的css样式四个状态
2021/03/09 HTML / CSS
动态加载js的几种方法
2006/10/23 Javascript
模仿JQuery.extend函数扩展自己对象的js代码
2009/12/09 Javascript
跨域请求之jQuery的ajax jsonp的使用解惑
2011/10/09 Javascript
一行代码告别document.getElementById
2012/06/01 Javascript
javascript基础之查找元素的详细介绍(访问节点)
2013/07/05 Javascript
DIV始终居中的js代码
2014/02/17 Javascript
JS中使用apply方法通过不同数量的参数调用函数的方法
2016/05/31 Javascript
浅谈JavaScript中变量和函数声明的提升
2016/08/09 Javascript
相册展示PhotoSwipe.js插件实现
2016/08/25 Javascript
vue-baidu-map 进入页面自动定位的解决方案(推荐)
2018/04/28 Javascript
jQuery实现的卷帘门滑入滑出效果【案例】
2019/02/18 jQuery
JS实现横向跑马灯效果代码
2020/04/20 Javascript
[42:22]DOTA2上海特级锦标赛C组小组赛#1 OG VS Archon第一局
2016/02/27 DOTA
Python实现partial改变方法默认参数
2014/08/18 Python
Python的Flask框架中实现分页功能的教程
2015/04/20 Python
Python list操作用法总结
2015/11/10 Python
python爬虫入门教程--快速理解HTTP协议(一)
2017/05/25 Python
python装饰器使用实例详解
2019/12/14 Python
使用Python 自动生成 Word 文档的教程
2020/02/13 Python
测试工程师职业规划书
2014/02/06 职场文书
挂职自我鉴定
2014/02/26 职场文书
广告词串烧
2014/03/19 职场文书
病人慰问信范文
2015/02/15 职场文书
公积金贷款承诺书
2015/04/30 职场文书
清明祭英烈活动总结
2015/05/11 职场文书
初中家长意见
2015/06/03 职场文书
治庸问责工作总结
2015/08/11 职场文书
2016教师廉洁从教心得体会
2016/01/13 职场文书
解决golang 关于全局变量的坑
2021/05/06 Golang
Python合并pdf文件的工具
2021/07/01 Python
mysql全面解析json/数组
2022/07/07 MySQL