22import traceback
33
44from RestrictedPython import safe_builtins , limited_builtins , utility_builtins , Guards
5- from threading import Thread , Event , Condition
5+ from threading import Thread , Event , Lock
66from time import sleep
77from .instrument import Instrument
88from types import CodeType , MethodType
1313import dis
1414import inspect
1515
16+ class GameFinishedException (Exception ):
17+ pass
18+
1619class RobotThread (Thread ):
1720 def __init__ (self , runner ):
1821 Thread .__init__ (self )
@@ -30,17 +33,18 @@ def run(self):
3033 if not self .running :
3134 return
3235
36+ #print("bytecode before", self.runner.bytecode)
3337 if not self .runner .initialized :
3438 self .runner .init_robot ()
35-
36- # print("bytecode before", self.runner.bytecode)
3739 self .runner .do_turn ()
38- # print("bytecode after", self.runner.bytecode)
40+ #print("bytecode after", self.runner.bytecode)
3941
4042 self .run_event .clear ()
4143 self .finished_event .set ()
4244
4345 def wait (self ):
46+ if not self .running :
47+ raise GameFinishedException
4448 self .paused = True
4549 self .finished_event .set () # External signal that we are finished for now
4650 self .pause_event .wait () # Wait for unpause
@@ -62,6 +66,7 @@ def __init__(self, code, game_methods, log_method, error_method, bytecode_limit,
6266 '__name__' : '__main__'
6367 }
6468
69+ self .globals ['__builtins__' ]['range' ] = range
6570 self .globals ['__builtins__' ]['__metaclass__' ] = type
6671 self .globals ['__builtins__' ]['instrument' ] = self .instrument_call
6772 self .globals ['__builtins__' ]['__multinstrument__' ] = self .multinstrument_call
@@ -234,10 +239,9 @@ def do_turn(self):
234239 if 'turn' in self .locals and isinstance (self .locals ['turn' ], type (lambda : 1 )):
235240 try :
236241 exec (self .locals ['turn' ].__code__ , self .globals , self .locals )
237- except :
238- # print("in except block")
239- # print(dis.dis(self.locals['turn'].__code__, show_caches=True, adaptive=False))
240- self .error_method (traceback .format_exc (limit = 5 ))
242+ except Exception as e :
243+ if not isinstance (e , GameFinishedException ):
244+ self .error_method (traceback .format_exc (limit = 5 ))
241245 else :
242246 self .error_method ('Couldn\' t find turn function.' )
243247
@@ -257,3 +261,4 @@ def run(self):
257261
258262 def kill (self ):
259263 self .thread .kill ()
264+ self .thread .join ()
0 commit comments