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本地与全局命名空间用法实例
Jun 16 Python
Python脚本实现12306火车票查询系统
Sep 30 Python
django基础之数据库操作方法(详解)
May 24 Python
解决Linux系统中python matplotlib画图的中文显示问题
Jun 15 Python
使用python编写简单的小程序编译成exe跑在win10上
Jan 15 Python
Python生成器generator用法示例
Aug 10 Python
利用Python将数值型特征进行离散化操作的方法
Nov 06 Python
python面向对象实现名片管理系统文件版
Apr 26 Python
Django models.py应用实现过程详解
Jul 29 Python
Python 点击指定位置验证码破解的实现代码
Sep 11 Python
基于Python实现ComicReaper漫画自动爬取脚本过程解析
Nov 11 Python
利用For循环遍历Python字典的三种方法实例
Mar 25 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/25 PHP
Laravel框架查询构造器 CURD操作示例
2019/09/04 PHP
Alliance vs Liquid BO3 第一场2.13
2021/03/10 DOTA
javascript应用:Iframe自适应其加载的内容高度
2007/04/10 Javascript
jquery 简单的进度条实现代码
2010/03/11 Javascript
js 函数调用模式小结
2011/12/26 Javascript
分享几个超级震憾的图片特效
2012/01/08 Javascript
用js替换除数字与逗号以外的所有字符的代码
2014/06/07 Javascript
JavaScript中的substr()方法使用详解
2015/06/06 Javascript
原生JS实现平滑回到顶部组件
2016/03/16 Javascript
ReactNative列表ListView的用法
2017/08/02 Javascript
利用JQUERY实现多个AJAX请求等待的实例
2017/12/14 jQuery
node实现的爬虫功能示例
2018/05/04 Javascript
nodejs实现获取本地文件夹下图片信息功能示例
2019/06/22 NodeJs
[02:34]DOTA2英雄基础教程 幽鬼
2014/01/02 DOTA
Python httplib模块使用实例
2015/04/11 Python
Python中序列的修改、散列与切片详解
2017/08/27 Python
Python+matplotlib绘制不同大小和颜色散点图实例
2018/01/19 Python
windows下python和pip安装教程
2018/05/25 Python
Python操作Excel插入删除行的方法
2018/12/10 Python
深入理解Django-Signals信号量
2019/02/19 Python
Python字符串内置函数功能与用法总结
2019/04/16 Python
python Tcp协议发送和接收信息的例子
2019/07/22 Python
python3+opencv生成不规则黑白mask实例
2020/02/19 Python
解决python3输入的坑——input()
2020/12/05 Python
CSS3中Animation动画属性用法详解
2016/07/04 HTML / CSS
瑞士香水购物网站:Parfumcity.ch
2017/01/14 全球购物
Feelunique美国:欧洲大型的在线美妆零售电商
2018/11/04 全球购物
Goodee官方商店:迷你投影仪
2021/03/15 全球购物
安全责任书范本
2014/04/15 职场文书
放飞中国梦演讲稿
2014/04/23 职场文书
花坛标语大全
2014/06/30 职场文书
政工例会汇报材料
2014/08/26 职场文书
Python绘制分类图的方法
2021/04/20 Python
用Java实现简单计算器功能
2021/07/21 Java/Android
Python可视化神器pyecharts绘制水球图
2022/07/07 Python