def active(self, active): if active != self._active: self._active = active if self._entity != None: if self._active: self.entity.add(self) Gilbert().gameLoop.startComponent(self) else: self.entity.refreshTags() self.entity.removeProperties(self) Gilbert().gameLoop.stopComponent(self)
def sceneInit(self): # Add bunnies self.gravity = 2 self.lastBunny = None self.firstBunny = None self.nBunnies = 0 self.ft = 0 self.ftc = 0 super(Bunnies, self).sceneInit() maxx, maxy = Gilbert().renderer.screenSize self.size = {'width': maxx, 'height': maxy} self.resolution = {'width': maxx, 'height': maxy} Gilbert().renderer.scrollTo(0,0) self.addBunnies()
def addBunnies(self, num=500): data = {"components":[ { "type":"Sprite", "file":u"images/wabbit_alpha.png", "x": 0, "y": 0 }, ]} r = Random() for x in range(0,num): bunny = Entity.create(id = 'bunny %d' % x, scene=self, **data) if self.firstBunny is None: self.firstBunny = bunny if self.lastBunny is not None: self.lastBunny.nextBunny = bunny bunny.x = r.random()*self.size['width'] bunny.y = self.size['height'] bunny.speedx = int(r.random()*70.0) - 35 bunny.speedy = int(r.random()*70.0) bunny.angle = 90 - r.random() * 90 bunny.z = int(r.random()*100) bunny.nextBunny = None self.lastBunny = bunny self.entities[bunny.id] = bunny Gilbert().startEntity(bunny) self.nBunnies+=num fps = self.getComponent("fps") if fps != None: fps.text = str(self.nBunnies)
def run(): try: Log(0) bunnies = Bunnies() Gilbert().init(BACKENDS.sdl, bunnies) except: pass
def addListener(self, url, obj): #if DEBUG and (__LINUX__ or __OSX__ or __MINGW__) watchURL = self._urlToWatchUrl(url) if watchURL is not None and watchURL not in self.watches: Gilbert().gameLoop.addWatch(watchURL) self.watches.append(watchURL) #endif super(DataManager, self).addListener(url, obj)
def process(self, data=None): """Process buffered incoming calls The data parameter is ignored, it's there for compatibility with init/update from the Entity/Components classes as this function is going to be called within a greenlet """ if self.inBuf and not self.staticglobals: # We change the namespace available on each call, kinda hacky and certainly slow...but hey, it works and the scene is dinamically available to you from ignifuga.Gilbert import Gilbert from ignifuga.rfoo.utils.rconsole import BufferedInterpreter import rlcompleter gilbert = Gilbert() while self.inBuf: handler, proxy, data = self.inBuf.pop(0) sys.stdin = proxy sys.stdout = proxy sys.stderr = proxy try: if not self.staticglobals: if gilbert.scene is not None: self._handler_context = gilbert.scene.runEnv else: self._handler_context = globals() handler._namespace = self._handler_context handler._interpreter = BufferedInterpreter( handler._namespace) handler._completer = rlcompleter.Completer( handler._namespace) handler._interpreter.runsource(data) error = None except: print traceback.format_exc() # Use exc_info for py2.x py3.x compatibility. t, v, tb = sys.exc_info() if t in BUILTIN_EXCEPTIONS: error = (t.__name__, v.args) else: error = (repr(t), v.args) result = None # if handler._interpreter.buffout != '': # conn.sendall(handler._interpreter.buffout) # handler._interpreter.buffout = '' # # if error is not None: # conn.sendall(str(error)) sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__
def getMusic(self, url): if url not in self.cache: if url.startswith('embedded:'): data = Gilbert().getEmbedded(url[9:]) if data != None: self.cache[url] = MixMusic(embedded=data) else: error('Error loading embedded data with id: %s', url) return None else: self.cache[url] = MixMusic(srcURL=join(ROOT_DIR, url)) #if DEBUG and (__LINUX__ or __OSX__ or __MINGW__) watchURL = self._urlToWatchUrl(url) if watchURL not in self.watches: Gilbert().gameLoop.addWatch(watchURL) self.watches.append(watchURL) #endif return self.cache[url]
def refreshTags(self): # Refresh the entity tags oldTags = set(self.tags) self.tags = [] for component in self._components.itervalues(): if component.active: self.addTags(component.entityTags) # Update tag index in the Gilbert overlord newTags = set(self.tags) Gilbert().refreshEntityTags(self, list(newTags - oldTags), list(oldTags - newTags))
def removeTags(self, tags): """ Remove one tag or a list of tags to the entity""" if isinstance(tags, basestring): tags = [ tags, ] for tag in tags: if tag in self.tags: self.tags.remove(tag) Gilbert().refreshEntityTags(self, [], tags)
def addTags(self, tags): """ Add one tag or a list of tags to the entity""" if isinstance(tags, basestring): tags = [ tags, ] for tag in tags: if tag not in self.tags: self.tags.append(tag) Gilbert().refreshEntityTags(self, tags)
def update(self, data): """ Move bunnies """ maxx = self.size['width'] maxy = self.size['height'] bunny = self.firstBunny ft = Gilbert().gameLoop.frame_time if ft < Gilbert().gameLoop.ticks_second / 100: scene.addBunnies(1500) elif ft < Gilbert().gameLoop.ticks_second / 30: scene.addBunnies(500) while True: if bunny._initialized: bunny.speedy += self.gravity bunny.x += bunny.speedx bunny.y += bunny.speedy bunny.alpha = 0.3 + 0.7 * bunny.y / maxy if bunny.x > maxx: bunny.x = maxx bunny.speedx = -bunny.speedx elif bunny.x <= 0: bunny.x = 0 bunny.speedx = -bunny.speedx if bunny.y > maxy: bunny.y = maxy bunny.speedy = -bunny.speedy elif bunny.y <= 0: bunny.y = 0 bunny.speedy = 0 bunny.updateRenderer() if bunny.nextBunny: bunny = bunny.nextBunny else: break
def start(self, onStart=None, onStop=None, onLoop=None): """ Fire up the action chain """ if onStart != None: self._onStart = onStart if onStop != None: self._onStop = onStop if onLoop != None: self._onLoop = onLoop if not self._running and not self._done and self._entity != None: self._tasksStatus = {} if self._type == Action.TYPE_NORMAL: for target in self._targets: self._tasksStatus[target] = {} for task in self._tasks: if not hasattr(target, task): raise Exception("Could not start action %s, %s does not have an attribute %s" % (self, target, task)) self._tasksStatus[target][task] = { 'targetValue': self._tasks[task], 'initValue': getattr(target, task) } elif self._type == Action.TYPE_ROCKET: for target in self._targets: self._tasksStatus[target] = {} for task in self._tasks: prop, prop_type = self._valueToCSSProperty(target.GetProperty(task)) propt, propt_type = self._valueToCSSProperty(self._tasks[task]) if prop_type != propt_type: # We can't animate between different units types... if propt_type == Action.CSS_COLOR: prop = {'r':0.0, 'g': 0.0, 'b': 0.0} else: prop = 0.0 self._tasksStatus[target][task] = { 'targetValue': propt, 'initValue': prop, 'type': propt_type } else: raise Exception("Unknown associated entity type %s" % (self.entity,)) self._running = True for a in self._runWith: a.start() self.run(self._onStart) if self._root: Gilbert().gameLoop.startComponent(self)
def process(self, data=None): """Process buffered incoming calls The data parameter is ignored, it's there for compatibility with init/update from the Entity/Components classes as this function is going to be called within a greenlet """ if self.inBuf and not self.staticglobals: # We change the namespace available on each call, kinda hacky and certainly slow...but hey, it works and the scene is dinamically available to you from ignifuga.Gilbert import Gilbert from ignifuga.rfoo.utils.rconsole import BufferedInterpreter import rlcompleter gilbert = Gilbert() while self.inBuf: handler, conn, type, name, args, kwargs = self.inBuf.pop(0) try: if not self.staticglobals: if gilbert.scene is not None: self._handler_context = gilbert.scene.runEnv else: self._handler_context = globals() handler._namespace = self._handler_context handler._interpreter = BufferedInterpreter( handler._namespace) handler._completer = rlcompleter.Completer( handler._namespace) foo = handler._methods.get(name, None) or handler._get_method(name) result = foo(*args, **kwargs) error = None except Exception: print 'Caught exception raised by callable.' # Use exc_info for py2.x py3.x compatibility. t, v, tb = sys.exc_info() if t in BUILTIN_EXCEPTIONS: error = (t.__name__, v.args) else: error = (repr(t), v.args) result = None if type == CALL: response = dumps((result, error)) conn.write(response)
def loadJsonFile(self, url): if url not in self.cache: data = json.loads(readFile(join(ROOT_DIR, url))) ret_data = {} for k,v in data.items(): key, value = sanitizeData(k,v) ret_data[key] = value self.cache[url] = ret_data #if DEBUG and (__LINUX__ or __OSX__ or __MINGW__) watchURL = self._urlToWatchUrl(url) if watchURL not in self.watches: Gilbert().gameLoop.addWatch(watchURL) self.watches.append(watchURL) #endif return self.cache[url]
bunny.speedy = -bunny.speedy elif bunny.y <= 0: bunny.y = 0 bunny.speedy = 0 bunny.updateRenderer() if bunny.nextBunny: bunny = bunny.nextBunny else: break def run(): try: Log(0) bunnies = Bunnies() Gilbert().init(BACKENDS.sdl, bunnies) except: pass if __name__ == '__main__': from optparse import OptionParser parser = Gilbert().parser (options, args) = parser.parse_args() if options.profile: import cProfile, pstats profileFileName = 'profile_data.pyprof' cProfile.runctx("run()", globals(), locals(), profileFileName) pstats.Stats(profileFileName).strip_dirs().sort_stats("time").print_stats() else: run()
def reset(self): Gilbert().gameLoop.stopEntity(self) for component in self._components.itervalues(): Gilbert().gameLoop.stopEntity(component)