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 20 Python
对于Python装饰器使用的一些建议
Jun 03 Python
一个基于flask的web应用诞生 组织结构调整(7)
Apr 11 Python
Python+request+unittest实现接口测试框架集成实例
Mar 16 Python
python实现京东秒杀功能
Jul 30 Python
Python生成器的使用方法和示例代码
Mar 04 Python
python类的实例化问题解决
Aug 31 Python
Python 3.8正式发布重要新功能一览
Oct 17 Python
python [:3] 实现提取数组中的数
Nov 27 Python
python如何代码集体右移
Jul 20 Python
pytorch 带batch的tensor类型图像显示操作
May 20 Python
解决pytorch 损失函数中输入输出不匹配的问题
Jun 05 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核心代码分析require和include的区别
2011/01/02 PHP
PHP在引号前面添加反斜杠(PHP去除反斜杠)
2013/09/28 PHP
Thinkphp实现MySQL读写分离操作示例
2014/06/25 PHP
PHP错误和异常处理功能模块示例
2016/11/12 PHP
Zend Framework基于Command命令行建立ZF项目的方法
2017/02/18 PHP
CakePHP框架Model关联对象用法分析
2017/08/04 PHP
jQuery使用手册之三 CSS操作
2007/03/24 Javascript
Js 获取当前日期时间及其它操作实现代码
2021/03/04 Javascript
js正确获取元素样式详解
2009/08/07 Javascript
浏览器的JavaScript引擎的识别方法
2013/10/20 Javascript
Javascript基础知识(二)事件
2014/09/29 Javascript
jQuery中unwrap()方法用法实例
2015/01/16 Javascript
AJAX实现瀑布流触发分页与分页触发瀑布流的方法
2016/05/23 Javascript
微信小程序三级联动地址选择器的实例代码
2017/07/12 Javascript
jQuery实现的响应鼠标移动方向插件用法示例【附源码下载】
2018/08/28 jQuery
vue中tab选项卡的实现思路
2018/11/25 Javascript
详解Vue中组件传值的多重实现方式
2019/08/16 Javascript
vue 翻页组件vue-flip-page效果
2020/02/05 Javascript
vue 表单输入框不支持focus及blur事件的解决方案
2020/11/17 Vue.js
[02:28]DOTA2英雄基础教程 灰烬之灵
2013/12/19 DOTA
Python 文件和输入输出小结
2013/10/09 Python
Python随机函数random()使用方法小结
2018/04/29 Python
tensorflow实现图像的裁剪和填充方法
2018/07/27 Python
Python读取xlsx文件的实现方法
2019/07/04 Python
flask 实现token机制的示例代码
2019/11/07 Python
python实现滑雪游戏
2020/02/22 Python
pycharm导入源码的具体步骤
2020/08/04 Python
python实现canny边缘检测
2020/09/14 Python
WWE美国职业摔角官方商店:WWE Shop
2018/11/15 全球购物
加拿大在线旅游公司:Flighthub
2019/03/11 全球购物
奥利奥广告词
2014/03/20 职场文书
中职生自荐信范文
2014/06/15 职场文书
职位证明模板
2015/06/23 职场文书
2016年党员公开承诺书范文
2016/03/24 职场文书
MySQL如何使用使用Xtrabackup进行备份和恢复
2021/06/21 MySQL
Java SSM配置文件案例详解
2021/08/30 Java/Android