Package MeatEngine :: Package Logic :: Module fsmMgr
[hide private]
[frames] | no frames]

Source Code for Module MeatEngine.Logic.fsmMgr

 1  """Meat Engine Hierarchical Finite State Machine (hFSM) Manager 
 2   
 3  This could be refactored so that a fsmMgr is an instatiatable class, 
 4  but for now it uses the "lazy singleton" pattern - the state stack is 
 5  a module global, and methods are just module functions. This is 
 6  adequate for my needs so far. 
 7   
 8  Use: create State objects, push them on the stack. Periodically call 
 9  the update and draw functions, and pass the handleKey and 
10  handleMouseButton events in as appropriate. The top state will get 
11  delegated to, which may choose to delegate further. For example, a 
12  dialog box may choose to call the next state's draw code first, before 
13  drawing itself. 
14  """ 
15   
16   
17 -class State:
18 - def __init__(self):
19 self.parent=None
20
21 - def handleMouseButton(self, bDown, buttonIndex):
22 return False
23
24 - def handleKey(self, key, unicode):
25 return False
26
27 - def init(self):
28 pass
29
30 - def activateApp(self, bNowActive):
31 return False
32 33 34 35 gStateStack=[] 36
37 -def pushState(newState):
38 try: 39 oldTop=gStateStack[-1] 40 except: 41 oldTop=None 42 43 gStateStack.append(newState) 44 newState.parent=oldTop 45 newState.init()
46 47
48 -def popState():
49 gStateStack.pop()
50 51
52 -def popAll():
53 global gStateStack 54 gStateStack=[]
55 56
57 -def handleKey(k, unicode):
58 for s in reversed(gStateStack): 59 if s.handleKey(k, unicode): 60 return True 61 return False
62
63 -def handleActivate(bNowActive):
64 for s in reversed(gStateStack): 65 if s.activateApp(bNowActive): 66 return True 67 return False
68
69 -def handleMouseButton(bDown, button):
70 for s in reversed(gStateStack): 71 if s.handleMouseButton(bDown, button): 72 return True 73 return False
74
75 -def update(ms):
76 if not len(gStateStack): 77 return False 78 79 gStateStack[-1].update(ms) 80 return True
81
82 -def draw():
83 if not len(gStateStack): 84 return 85 86 gStateStack[-1].draw()
87
88 -def isTop(state):
89 return len(gStateStack)>0 and state==gStateStack[-1]
90