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实现的简单hangman游戏实例
Jun 28 Python
Python使用urllib2模块抓取HTML页面资源的实例分享
May 03 Python
python3中的md5加密实例
May 29 Python
python 实现字符串下标的输出功能
Feb 13 Python
Python面向对象实现方法总结
Aug 12 Python
详解Python中的路径问题
Sep 02 Python
python识别验证码的思路及解决方案
Sep 13 Python
Python 微信公众号文章爬取的示例代码
Nov 30 Python
Pandas中DataFrame交换列顺序的方法实现
Dec 14 Python
python中使用asyncio实现异步IO实例分析
Feb 26 Python
python实现腾讯滑块验证码识别
Apr 27 Python
从np.random.normal()到正态分布的拟合操作
Jun 02 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字符转义相关函数小结(php下的转义字符串)
2007/04/12 PHP
PHP取整数函数常用的四种方法小结
2012/07/05 PHP
php自动提交表单的方法(基于fsockopen与curl)
2016/05/09 PHP
JavaScript 新手24条实用建议[TUTS+]
2009/06/21 Javascript
10个实用的脚本代码工具
2010/05/04 Javascript
HTML颜色选择器实现代码
2010/11/23 Javascript
用jquery实现的模拟QQ邮箱里的收件人选取及其他效果(一)
2011/01/06 Javascript
JQuyer $.post 与 $.ajax 访问WCF ajax service 时的问题需要注意的地方
2011/09/20 Javascript
使用Math.floor与Math.random取随机整数的方法详解
2013/05/07 Javascript
javascript弹出层输入框(示例代码)
2013/12/11 Javascript
基于jQuery的JavaScript模版引擎JsRender使用指南
2014/12/29 Javascript
从零学习node.js之mysql数据库的操作(五)
2017/02/24 Javascript
详解bootstrap导航栏.nav与.navbar区别
2017/11/23 Javascript
JS使用setInterval实现的简单计时器功能示例
2018/04/19 Javascript
Angular学习教程之RouterLink花式跳转
2018/05/03 Javascript
浅谈手写node可读流之流动模式
2018/06/01 Javascript
Vue中对拿到的数据进行A-Z排序的实例
2018/09/25 Javascript
layui文件上传控件带更改后数据传值的方法
2019/09/23 Javascript
js中addEventListener()与removeEventListener()用法案例分析
2020/03/02 Javascript
Vue 解决通过this.$refs来获取DOM或者组件报错问题
2020/07/28 Javascript
[07:49]2014DOTA2国际邀请赛 Newbee夺冠后采访xiao8坦言奖金会上交
2014/07/23 DOTA
Python实现好友全头像的拼接实例(推荐)
2017/06/24 Python
Django项目中用JS实现加载子页面并传值的方法
2018/05/28 Python
pytorch实现CNN卷积神经网络
2020/02/19 Python
10 套华丽的CSS3 按钮小结
2012/10/03 HTML / CSS
使用CSS3设计地图上的雷达定位提示效果
2016/04/05 HTML / CSS
婚鞋、新娘鞋、礼服鞋、童鞋:Nina Shoes
2019/09/04 全球购物
微型企业创业投资计划书
2014/01/10 职场文书
查环查孕证明
2014/01/10 职场文书
拔河比赛口号
2014/06/10 职场文书
转让协议书
2015/01/27 职场文书
小学校长开学致辞
2015/07/29 职场文书
求职自我评价参考范文
2019/05/16 职场文书
个人落户申请书怎么写?
2019/06/28 职场文书
PyCharm配置KBEngine快速处理代码提示冲突、配置命令问题
2021/04/03 Python
Canvas三种动态画圆实现方法说明(小结)
2021/04/16 Javascript