Script demo_scratchBridge_py
[hide private]
[frames] | no frames]

Source Code for Script script-demo_scratchBridge_py

 1  from joy import * 
 2  import re 
 3   
4 -class ScratchBridge(JoyApp):
5 - def __init__(self,count=None,names={},walk=False):
6 JoyApp.__init__(self,scr={}, 7 robot=dict(count=count,names=names,walk=walk))
8 9 REX_CLP = re.compile("\Ackbot://(\S+)\Z") 10
11 - def onStart( self ):
12 self.cache = {}
13
14 - def newSetter( self, key ):
15 # Pattern match with CLP pattern 16 m = self.REX_CLP.match(key) 17 if m is None: 18 self.cache[key] = None 19 return None 20 # Search for extracted CLP 21 clp = m.group(1) 22 try: 23 fun = self.robot.setterOf(clp) 24 except (KeyError,AttributeError,ValueError), ex: 25 fun = ex 26 # If failed --> invalid property name 27 if isinstance(fun,StandardError): 28 self.cache[key] = False 29 return False 30 # Record new cache value 31 self.cache[key]= fun 32 return fun
33
34 - def onEvent( self, evt ):
35 if evt.type==SCRATCHUPDATE: 36 # Lookup in cache 37 fun = self.cache.get(evt.var,None) 38 # If cache hit --> call setter function 39 if fun: 40 fun(int(evt.value)) 41 elif fun is False: # cached as a bad name --> ignore 42 pass 43 else: # New --> lookup in robot, and cache result 44 assert fun is None 45 fun = self.newSetter( evt.var ) 46 if fun: 47 fun(int(evt.value)) 48 elif evt.type != TIMEREVENT: 49 self.scratchifyEvent(evt) 50 JoyApp.onEvent(self,evt)
51 52 if __name__=="__main__": 53 import sys 54 print ''' 55 Scratch to CKBot Bridge 56 ----------------------- 57 58 When running, this JoyApp exposes all properties of the CKBot 59 cluster to Scratch. In addition, it emits game controller state 60 updates into scratch. 61 62 The commandline version (which you are running now) expects 63 the number of clusters to be given as a parameter, and will 64 walk all those clusters, but the ScratchBridge class does not 65 require this. If the number of clusters is not specified, 66 the default Cluster.populate() settings are used. 67 ''' 68 if len(sys.argv)==2: 69 sb = ScratchBridge(count=int(sys.argv[1]),walk=True) 70 else: 71 sb = ScratchBridge(walk=True) 72 73 DEBUG = 'S' 74 sb.run() 75