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
投稿
猜你喜欢
- Pydub是一个基于ffmpeg的Python音频处理模块,封装了许多ffmpeg底层接口,因此用它来做音乐歌曲文件格式转换会非常方便,如果
- Opera, 作为 A-Grade 浏览器,在现在的前端开发中务必支持。它很优秀,很不幸,bug是每个浏览器都不可避免的问题,Opera亦难
- 其实在很久很久之前就发现search类型的input,该属性值是WebKit私有,不过一直没去查相关的属性,介于XXX原因,我找出其属性,回
- 写在前面虽然 make 和 new 都是能够用于初始化数据结构,但是它们两者能够初始化的
- 本文实例讲述了PHP实现对数组分页处理方法。分享给大家供大家参考,具体如下:最近用到了用数组数据分页,这里整理了一下,具体代码如下:<
- 1.概述Go的字符串是一个不可改变的数据结构,这和其他语言如JAVA,C++等的设定很类似.总体来说,有如下五种拼接方式,下面我们将论述各种
- #!/usr/bin/env python#coding=utf-8import osfrom pyinotify import Watch
- python循环语句求和1.for循环求和sum1 = 0for i in range(1,101):? ? if i % 2 == 0:?
- 本文实例为大家分享了Python实现图片格式转换的具体代码,供大家参考,具体内容如下碰上这样一个情景:我从网络上下载了一张表情包图片,存放在
- pandas函数中pandas.DataFrame.from_dict 直接从字典构建DataFrame 。参数解析DataFrame fr
- 有一个表user,字段分别有id、nick_name、password、email、phone。一、单字段(nick_name)查出所有有重
- example: for item in warehouse_list: warehouse_id =
- 1.问:在DW中如何设置页面边距为0?答:在DW中似乎没有直接设置的方法,你只有在Html文档中插入以
- 在做项目的时候,遇到这样的数据:"trends": [ { &nb
- Oracle sql语句执行日志查询在Oracle数据中,我们经常编写sql语句,有时我们会编写一些特别长的sql语句,而有一些意外导致sq
- 本文实例讲述了Python使用django获取用户IP地址的方法。分享给大家供大家参考。具体如下:函数实现:def get_client_i
- 本文转自微信公众号:"算法与编程之美"1、问题描述使用HBuilder做一个简单的社区浏览界面。2、解决方案这是对HBu
- 最基本的MMM安装必须至少需要2个数据库服务器和一个监控服务器下面要配置的MySQL Cluster环境包含四台数据库服务器和一台监控服务器
- 也许光从字面上来说,版式设计中的“亲密性”似乎不太好理解,正常的情况下,我们都会把“亲密性”理解为人与人之间的关系的一种表现,事实上在版式设
- ORA-01578:Oracle data block corrupted(file # num,block # num)产生原