微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python实现简单状态框架的方法

这篇文章主要介绍了Python实现简单状态框架的方法,涉及Python状态框架的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了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         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         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))

    de上一篇:Python深入学习之对象的属性下一篇:Win10下python3.7.3安装教程图解 热门搜索

的简单方法 

单态方法 

实现方法 

js正则实现的密码框简单制作 

[JS]实现动态增加框架!未完成 

相关文章

Python实现简单状态框架的方法

2021-09-10阅读(7381)评论(0)推荐()

这篇文章主要介绍了Python实现简单状态框架的方法,涉及Python状态框架的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

用js代码改变单选框选中状态的简单实例

2021-10-10阅读(3653)评论(0)推荐()

这篇文章主要介绍了js代码改变单选框选中状态的简单实例,有需要的朋友可以参考一下

PHP简单的MVC框架实现方法

2021-11-13阅读(4324)评论(0)推荐()

PHP中使用MVC越来越流行了,特别是在一些开源的框架当中。本篇给大家介绍PHP简单的mvc框架实现方法,对PHP简单的mvc框架相关知识感兴趣的朋友一起学习...

python中Flask框架简单入门实例

2021-11-11阅读(5955)评论(0)推荐()

这篇文章主要介绍了python中Flask框架简单入门实例,以一个hello程序简单分析了Flask框架的使用技巧,需要的朋友可以参考下

Yii2框架可逆加密简单实现方法

2021-10-08阅读(4969)评论(0)推荐()

这篇文章主要介绍了Yii2框架可逆加密简单实现方法,涉及Yii框架encryptByPassword()与decryptByPassword()函数简单使用方法...

Laravel 框架返回状态拦截代码

2021-11-17阅读(4562)评论(0)推荐()

今天小编就为大家分享一篇Laravel 框架返回状态拦截代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

python框架flask入门之路由及简单实现方法

2021-11-04阅读(9494)评论(0)推荐()

这篇文章主要介绍了python框架flask入门路由及路由简单实现方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...

取消

有人回复邮件通知

提交评论

© 2021 编程之家 

工信部备案号:琼ICP备2022000316号

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐