Python实现简单状态框架的方法
作者:chongq 发布时间:2022-08-20 14:13:44
标签: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 <= 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程序设计有所帮助。
0
投稿
猜你喜欢
- 作者认为最快的学习区块链的方式是自己创建一个,本文就跟随作者用Python来创建一个区块链。对数字货币的崛起感到新奇的我们,并且想知道其背后
- 本文实例讲述了Python面向对象之继承原理与用法。分享给大家供大家参考,具体如下:目标单继承多继承面向对象三大特性封装 根据 职责 将 属
- 代码如下:< % Set fso=Server.CreateObject("Scripting
- 前几天开始原来的google pr查询接口已经失效,导致很多站长工具pr查询功能不能使用原始pr查询接口:$string =&nb
- Server对象提供对服务器上访问的方法和属性.大多数方法和属性是作为实用程序的功能提供的。语法:Server.property|metho
- 如何在线修改表?具体代码如下:<%Set conn1 = Server.CreateObject(&qu
- 比如一个汉字也只会算一个字节,在排版时如果全是汉字,好说,反正没什么差别,但是如果 * 作的字符串有汉字又有英文字母时,就不方便了,以下三个函
- 前言本文主要给大家介绍了关于golang解析网页利器goquery使用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介
- 什么是JSON http://www.json.org/json-zh.htmlJSON(Javascript Object Notatio
- 在mysql网站时拿到的rpm包只能用root安装,不支持relocate用源码安装后./configure --prefix=/home/
- 滑动验证码介绍本篇涉及到的验证码为滑动验证码,不同于极验证,本验证码难度略低,需要的将滑块拖动到矩形区域右侧即可完成。这类验证码不常见了,官
- 今天来说一下,有些刚刚接触python的朋友,在使用pip install安装python 第三方库的过程中会出现网速很慢,或者是安装下载到
- 本文整理了一部分我们平时在项目中经常遇到的关于go语言JSON数据与结构体之间相互转换的问题及解决办法。基本的序列化首先我们来看一下Go语言
- 如果你忘记了你的MYSQL的root口令的话,你可以通过下面的过程恢复。1. 向mysqld server 发
- 安装很简单pip install psutil官网地址为:https://pythonhosted.org/psutil/ (文档上有详细的
- 看过数据库的备份与还原。大多数都是用组件来完成的。其实可通过sql语句来完成。 由于时间关系,未对参数进行验证和界面美化。代码
- 监控中,通常要使用图片更直观的看出集群的运行状况。以下是一个简单的demo,通过rrdtool生成动态的图片。Python3, tornad
- 本文实例为大家分享了Python实现五子棋游戏的具体代码,供大家参考,具体内容如下class CheckerBoard(): &
- 1、有一个论坛,帖子的数据巨大,请简要说明如何提高用户搜索帖子的效率。 在程序方面,可以使用页面缓存技术。在前台界面着设计方面也可以让用户输
- 这篇文章主要介绍了Python中使用gflags实例及原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,