Python实现简单状态框架的方法
本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下:
这里使用Python实现一个简单的状态框架,代码需要在python3.2环境下运行
fromtimeimportsleep fromrandomimportrandint,shuffle classStateMachine(object): '''Usage: CreateaninstanceofStateMachine,useset_starting_state(state)togiveitan initialstatetoworkwith,thencalltick()oneachsecond(orwhateveryourdesired timeintervalmightbe.''' defset_starting_state(self,state): '''Theentrystateforthestatemachine.''' state.enter() self.state=state deftick(self): '''Callsthecurrentstate'sdo_work()andchecksforatransition''' next_state=self.state.check_transitions() ifnext_stateisNone: #Stickwiththisstate self.state.do_work() else: #Nextstatefound,transitiontoit self.state.exit() next_state.enter() self.state=next_state classBaseState(object): '''Usage:SubclassBaseStateandoverridetheenter(),do_work(),andexit()methods. enter() --Setupforyourstateshouldoccurhere. Thislikelyincludesadding transitionsorinitializingmembervariables. do_work() --Meatandpotatoesofyourstate. Theremaybesomelogicherethatwill causeatransitiontotrigger. exit() --Anycleanuporfinalactionsshouldoccurhere. Thisiscalledjust beforetransitiontothenextstate. ''' defadd_transition(self,condition,next_state): '''Addsanewtransitiontothestate. The"condition"parammustcontainacallable object. Whenthe"condition"evaluatestoTrue,the"next_state"paramissetas theactivestate.''' #Enforcetransitionvalidity 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)) #Addtransition ifnothasattr(self,"transitions"): self.transitions=[] self.transitions.append((condition,next_state)) defcheck_transitions(self): '''ReturnsthefirstStatethatsconditionevaluatestrue(conditionorderisrandomized)''' ifhasattr(self,"transitions"): shuffle(self.transitions) fortransitioninself.transitions: condition,state=transition ifcondition(): returnstate defenter(self): pass defdo_work(self): pass defexit(self): pass ################################################################################################## ###############################EXAMPLEUSAGEOFSTATEMACHINE################################### ################################################################################################## classWalkingState(BaseState): defenter(self): print("WalkingState:enter()") defcondition():returnrandint(1,5)==5 self.add_transition(condition,JoggingState()) self.add_transition(condition,RunningState()) defdo_work(self): print("Walking...") defexit(self): print("WalkingState:exit()") classJoggingState(BaseState): defenter(self): print("JoggingState:enter()") self.stamina=randint(5,15) defcondition():returnself.stamina<=0 self.add_transition(condition,WalkingState()) defdo_work(self): self.stamina-=1 print("Jogging({0})...".format(self.stamina)) defexit(self): print("JoggingState:exit()") classRunningState(BaseState): defenter(self): print("RunningState:enter()") self.stamina=randint(5,15) defwalk_condition():returnself.stamina<=0 self.add_transition(walk_condition,WalkingState()) deftrip_condition():returnrandint(1,10)==10 self.add_transition(trip_condition,TrippingState()) defdo_work(self): self.stamina-=2 print("Running({0})...".format(self.stamina)) defexit(self): print("RunningState:exit()") classTrippingState(BaseState): defenter(self): print("TrippingState:enter()") self.tripped=False defcondition():returnself.tripped self.add_transition(condition,WalkingState()) defdo_work(self): print("Tripped!") self.tripped=True defexit(self): print("TrippingState:exit()") if__name__=="__main__": state=WalkingState() state_machine=StateMachine() state_machine.set_starting_state(state) whileTrue: state_machine.tick() sleep(1)
希望本文所述对大家的Python程序设计有所帮助。