def __init__(self): debug.msg('Initializing game scene') super(GameScene, self).__init__() # All map layers are kept in the scrolling manager for obvious reasons self.scroller = cocos.layer.ScrollingManager() self.add(self.scroller)
def walkit(alist): debug.msg(1,"op",alist[0]) for e in alist[1:]: if isinstance(e, list): walkit(e) else: pass
def on_jump_land(self): debug.msg('landed') self.jumping = False vx = self.body.velocity[0] self.body.reset_forces() self.body.velocity = ((vx, 0)) self.update_forces()
def run(self): logger.debug(msg("running.")) self.stop_event_loop() while True: self._process_children() if self.srv_command_pipe.poll(): req = self.srv_command_pipe.recv() logger.debug(msg("incoming data on command pipe ", req)) if req.message_name == 'create_object': try: obj_id = self._create_object(req.object_class, *req.args, **req.kwargs) response = rpc('created_object') response.object_id = obj_id except Exception, e: logger.warn(msg("Object could not be created, exception thrown: ", e)) response = rpc('created_object') response.object_id = None response.exception = e self.srv_command_pipe.send(response) elif req.message_name == 'terminate_object': self._server_terminate_object(req.object_id) elif req.message_name == 'terminate': for obj in self.children: self._server_terminate_object(obj) response = rpc('terminated') self.srv_command_pipe.send(response)
def __call__(self,*args): debug.msg(1,"call args are ",args) if len(args) > self.maxarg: raise TypeError," operator %s takes at most %s args, %s given" % (self.name,self.maxarg,len(args)) if len(args) < self.minarg: raise TypeError," operator %s takes at least %s args, %s given" % (self.name,self.minarg,len(args)) return self.function(*args)
def save(self): debug.msg('Saving level geometry') builder = ElementTree.TreeBuilder() builder.start('physics', {'name': 'physics'}) for shape in self.physics.space.shapes: if shape.collision_type != physics.COLLTYPE_STATIC: continue if isinstance(shape, pymunk.Poly): builder.start('polygon', {}) for v in shape.get_points(): x = str(int(v.x)) y = str(int(v.y)) builder.start('vertex', {'x': x, 'y': y}) builder.end('vertex') builder.end('polygon') builder.end('physics') tree = ElementTree.ElementTree(builder.close()) filename = util.resource.path(self.parent.tiledmap.properties['physics']) tree.write(filename)
def delete_polygon(self, polygon): if polygon in self.poly2shape: debug.msg('Deleting polygon') shape = self.poly2shape[polygon] del self.poly2shape[polygon] del self.shape2poly[shape] self.polygon_layer.remove(polygon) self.physics.space.remove(shape)
def bind(*args): debug.msg(1, "bind args are: ") debug.msg(1, args) res = numpy.array(args) if len(res.shape) == 3: if res.shape[0] == 1: res=res[0] return res
def __init__(self): debug.msg('Initializing game') self.config = None # Add paths for pyglet to use for resources pyglet.resource.path.append('data/') pyglet.resource.path.append('data/maps/') pyglet.resource.reindex()
def __set(self): debug.msg("RSSM - set - Enter") path = os.path.join(sys.path[0], (RSStateManager.appname + self.__name + ".ini")) file = open(path, "wb") pickle.dump(self.__statedict, file) file.close() debug.msg("RSSM - set - Exit")
def _process_children(self): for i in self.children.keys(): if self.children[i]['pipe'].poll(): response = self.children[i]['pipe'].recv() self.children[i]['parent_pipe'].send(response) logger.debug(msg("Child ", i, " sending response.")) if self.children[i]['parent_pipe'].poll(): req = self.children[i]['parent_pipe'].recv() self.children[i]['pipe'].send(req) logger.debug(msg("Child ", i, " receiving request."))
def on_character_jump_land(self, space, arbiter): '''Handles characters that jump and land on static geometry. ''' debug.msg("%s, %s" % (arbiter.contacts[0].normal, len(arbiter.contacts))) #if arbiter.contacts[0].normal.dot(arbiter.contacts[1].normal) > 0: actor = arbiter.shapes[1].actor() physics = actor.get_component('physics') physics.on_jump_land() return True
def _recv_command(self,block=False): if not block and not self.pipe.poll(): return try: logger.debug(msg("Receiving from pipe")) command = self.pipe.recv() logger.debug(msg("Got command ", command.message_name, " priority = ", command.priority)) _insert_sorted(self.command_queue, command, self._compute_priority(command)) logger.debug(msg("Saved command ", command.message_name, " priority = ", command.priority)) except Exception, e: logger.error(msg("Error when receiving command:", e))
def __init__(self): debug.msg('Initializing editor') super(EditorLayer, self).__init__() self.polygon = None # bi-directional mapping for polygons to pymunk shapes self.poly2shape = {} self.shape2poly = {} self.active_color = (1.0, 0.0, 0.0, 1.0) self.inactive_color = (1.0, 1.0, 1.0, 1.0)
def __init__(self): debug.msg('Initializing physics') self.space = pymunk.Space() self.space.gravity = pymunk.Vec2d(0.0, -900.0) self.update_physics = True # Register a bunch of collision callbacks self.space.add_collision_handler(COLLTYPE_STATIC, COLLTYPE_CHARACTER, self.on_character_jump_land, None, None, None) self.space.add_collision_handler(COLLTYPE_OBJECT, COLLTYPE_CHARACTER, self.on_character_jump_land, None, None, None)
def __get(self): path = os.path.join(sys.path[0], (RSStateManager.appname + self.__name + ".ini")) if os.path.isfile(path): file = open(path, "rb") d = pickle.load(file) debug.msg(d) self.__statedict = d file.close() else: self.__set()
def _create_object(self, object_class, *args, **kwargs): local_end, child_end = Pipe() parent_pipe = self.server_router.create() self.children[parent_pipe.id] = { 'object':remote_object( child_end, object_class, *args, **kwargs ), 'pipe':local_end, 'parent_pipe':parent_pipe, } logger.debug(msg("starting object ", object_class, " communication on pipe id ", parent_pipe.id, "...")) res = self.children[parent_pipe.id]['object'].start() logger.debug(msg("started successfully, result == ", res)) return parent_pipe.id
def _process_incoming(self,req): if req.message_name == 'transport' and req.pipe_id in self.queues: logger.debug(msg("processing transport on pipe ", req.pipe_id, "(data ==", req.data,")")) self.queues[req.pipe_id].append(req.data) return req.pipe_id elif req.message_name == 'close': logger.debug(msg("closing on pipe ", req.pipe_id)) if req.pipe_id in self.queues: del self.queues[req.pipe_id] else: pass logger.debug(msg("unexpected message type ", req.message_name, " on pipe ", req.pipe_id)) return None
def populate(self): debug.msg('Populating physics editor') for shape in self.physics.space.shapes: if shape.collision_type != physics.COLLTYPE_STATIC: continue if isinstance(shape, pymunk.Poly): polygon = Polygon() for p in shape.get_points(): polygon.add_vertex((p.x, p.y)) self.polygon_layer.add(polygon) self.poly2shape[polygon] = shape self.shape2poly[shape] = polygon
def evaluate(alist): debug.msg(1, "evaluate:") debug.msg(1,alist) op = alist[0] args = [] for e in alist[1:]: debug.msg(1," partial: ",e) if isinstance(e,list): debug.msg(1,"recursing:",alist) args.append(evaluate(e)) else: debug.msg(1,"appending ",e) args.append(e) return op(*args)
def __init__(self, parent, rc): ''' ''' debug.msg("Chords __init__ Enter") #default settings self.settings = { "draw": 1, "channel": 1, "velocity": 96, "highlight": 1, "invert_above": 6 } self.stateManager_Start("ChordSection", self.settings) self.parent = parent self.rc = rc self.init_widgets() debug.msg("Chords __init__ Exit")
def drawChord( self, midiTake, chord, currentPos, chordLength, chordIndex ): #velocity,x,position,startPosition,rd,chordattack,selectNote): debug.msg('drawChord - Enter') # alwaysRootPosition: # True = always draw chords in root position, False = randomize between root position and second inversion alwaysRootPosition = False ## if chordIndex == 0: # todo: "smooth chord progr." ## firstChord = chord if not alwaysRootPosition: randomChPosL = [ "rootPosition", "inversion2nd" ] # ["rootPosition", "inversion1st", "inversion2nd"] chordPos = choice(randomChPosL) else: chordPos = "rootPosition" velocity = self.velocity.get() chordattack = self.chordAttack.get() selectNote = self.highlight.get() step = 0 debug.msg(chordattack) if chordattack == 'Fast': step = 120 #fast elif chordattack == 'Slow': step = 480 #slow channel = self.settings["channel"] noteOffset = -12 # root position if chordPos == "rootPosition": note1Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset note2Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset note3Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset # first inversion if chordPos == "inversion1st": note1Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset - 12 note2Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset - 12 note3Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset # second inversion if chordPos == "inversion2nd": note1Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset - 12 note2Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset note3Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset debug.msg("wtf2") RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos),\ note1Pitch, int(chordLength), selectNote) RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos+step),\ note2Pitch, int(chordLength)-step, selectNote) RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos+(step*2)),\ note3Pitch, int(chordLength)-(step*2), selectNote) debug.msg('drawChord - Exit') return currentPos
def _close(self, pipe_id): if pipe_id in self.queues: logger.debug(msg("Closing pipe", pipe_id)) req = rpc('close') req.pipe_id = pipe_id self.pipe.send(req) del self.queues[pipe_id]
def _server_terminate_object(self, object_id): logger.debug(msg("Terminating object ...", object_id)) self.children[object_id]['pipe'].close() self.children[object_id]['object'].terminate() self.children[object_id]['parent_pipe'].close() del self.children[object_id] logger.debug("Object terminated")
def commit_polygon(self): debug.msg('Committing polygon') if self.polygon in self.poly2shape: shape = self.poly2shape[self.polygon] del self.poly2shape[self.polygon] del self.shape2poly[shape] self.physics.space.remove(shape) self.polygon.color = self.inactive_color # Add to physics space shape = physics.make_static_polygon(self.polygon.vertices) self.poly2shape[self.polygon] = shape self.shape2poly[shape] = self.polygon self.physics.space.add(shape) # Polygon committed. Let user make a new one. self.polygon = None
def _send(self, pipe_id, data): logger.debug(msg("Router._send: sending data on pipe ", pipe_id, "(data ==", data,")")) if pipe_id not in self.queues: raise Exception("I/O Error: Non-existing or closed pipe") req = rpc('transport') req.pipe_id = pipe_id req.data = data self.pipe.send(req)
def _process_command(self, block=False, return_response_to=None): if not block and not self.pipe.poll(): return try: command = self.pipe.recv() except Exception, e: logger.error(msg("Error when receiving command:", e)) return None
def drawChord(self,midiTake, chord, currentPos, chordLength, chordIndex): #velocity,x,position,startPosition,rd,chordattack,selectNote): debug.msg('drawChord - Enter') # alwaysRootPosition: # True = always draw chords in root position, False = randomize between root position and second inversion alwaysRootPosition = False ## if chordIndex == 0: # todo: "smooth chord progr." ## firstChord = chord if not alwaysRootPosition: randomChPosL = ["rootPosition", "inversion2nd"] # ["rootPosition", "inversion1st", "inversion2nd"] chordPos = choice(randomChPosL) else: chordPos = "rootPosition" velocity = self.velocity.get() chordattack = self.chordAttack.get() selectNote = self.highlight.get() step = 0 debug.msg(chordattack) if chordattack == 'Fast': step=120 #fast elif chordattack == 'Slow': step=480 #slow channel = self.settings["channel"] noteOffset = -12 # root position if chordPos == "rootPosition": note1Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset note2Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset note3Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset # first inversion if chordPos == "inversion1st": note1Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset - 12 note2Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset - 12 note3Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset # second inversion if chordPos == "inversion2nd": note1Pitch = int(self.rc.ChordDict[chord][2]) + noteOffset - 12 note2Pitch = int(self.rc.ChordDict[chord][0]) + noteOffset note3Pitch = int(self.rc.ChordDict[chord][1]) + noteOffset debug.msg("wtf2") RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos),\ note1Pitch, int(chordLength), selectNote) RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos+step),\ note2Pitch, int(chordLength)-step, selectNote) RSMidi.addNote(midiTake, channel, int(velocity), int(currentPos+(step*2)),\ note3Pitch, int(chordLength)-(step*2), selectNote) debug.msg('drawChord - Exit') return currentPos
def on_mouse_release(self, x, y, button, modifiers): x, y = self.parent.scroller.pixel_from_screen(x, y) if button == pyglet.window.mouse.LEFT: if modifiers & pyglet.window.key.MOD_CTRL: # Make a new polygon if need be if self.polygon == None: self.polygon = Polygon() self.polygon.color = self.active_color self.polygon_layer.add(self.polygon) # Add vertex to polygon self.polygon.add_vertex((x, y)) else: # Select a polygon to edit shape = self.physics.space.point_query_first((x, y)) debug.msg('Select shape') if shape != None: if self.polygon != None: self.commit_polygon() if shape in self.shape2poly: self.polygon = self.shape2poly[shape] self.polygon.color = self.active_color else: if self.polygon != None: self.commit_polygon() elif button == pyglet.window.mouse.RIGHT: if modifiers & pyglet.window.key.MOD_CTRL: # Remove a single vertex if self.polygon != None and len(self.polygon.vertices) != 0: del self.polygon.vertices[-1] else: # Add polygon to scene or replace the existing one if self.polygon != None: self.commit_polygon() elif button == pyglet.window.mouse.MIDDLE: # Select and delete polygon shape = self.physics.space.point_query_first((x, y)) if shape != None: self.delete_polygon(shape)
def load_map(self): debug.msg('Loading map') self.map_filename = 'maps/test.tmx' self.tiledmap = tiled.tiled.load_map( util.resource.path(self.map_filename)) self.scroller.add(self.tiledmap.layers['middleground'], z=1) self.scroller.add(self.tiledmap.layers['background'], z=0) background = cocos.layer.ScrollableLayer() image = cocos.sprite.Sprite('backgrounds/forest.jpg', anchor=(0, 0)) background.add(image) background.parallax = 0.8 background.px = image.width background.py = image.height self.scroller.add(background, z=-1) debug.msg('Loading level geometry') physics_file = util.resource.path(self.tiledmap.properties['physics']) self.physics = physics.from_xml(physics_file) debug.msg('Creating test actor layer') self.actors = actorlayer.ActorLayer() self.actors.push_handlers(self) self.scroller.add(self.actors, z=1) self.test_actor() self.dispatch_event('on_map_load')
def load_map(self): debug.msg('Loading map') self.map_filename = 'maps/test.tmx' self.tiledmap = tiled.tiled.load_map(util.resource.path(self.map_filename)) self.scroller.add(self.tiledmap.layers['middleground'], z=1) self.scroller.add(self.tiledmap.layers['background'], z=0) background = cocos.layer.ScrollableLayer() image = cocos.sprite.Sprite('backgrounds/forest.jpg', anchor=(0,0)) background.add(image) background.parallax = 0.8 background.px = image.width background.py = image.height self.scroller.add(background, z=-1) debug.msg('Loading level geometry') physics_file = util.resource.path(self.tiledmap.properties['physics']) self.physics = physics.from_xml(physics_file) debug.msg('Creating test actor layer') self.actors = actorlayer.ActorLayer() self.actors.push_handlers(self) self.scroller.add(self.actors, z=1) self.test_actor() self.dispatch_event('on_map_load')
def _dispatch_method(self, method_name, *args, **kwargs): if '_priority' in kwargs: p = kwargs['_priority'] del kwargs['_priority'] else: p = rpc.PRIORITY_NORMAL if '_async' in kwargs: async = kwargs['_async'] del kwargs['_async'] else: async = True if '_timeout' in kwargs: timeout = kwargs['_timeout'] del kwargs['_timeout'] async = False if '_default' in kwargs: default_ret = kwargs['_default'] del kwargs['_default'] else: default_ret = None else: timeout = None logger.debug(msg("Timeout == ", timeout)) command = rpc(method_name, *args, **kwargs) command.priority = p logger.debug(msg("Dispatching rpc for ", method_name)) self.pipe.send(command) time_start = time() if timeout is not None: logger.debug(msg("Time start == ", time_start)) while not async: ret = self._process_command(block=False, return_response_to=command.message_id) if ret is not None: return ret if timeout is not None and time() - time_start > timeout: return default_ret if time() % 10 == 0: logger.debug(msg(self, "Time:", time()))
def _process( self, min_priority_level = None ): if len(self.command_queue) == 0: return else: command, p = self.command_queue.pop(0) if min_priority_level is None or self._compute_priority(command) >= min_priority_level: logger.debug(msg("Processing command ", command.message_name, " priority = ", command.priority)) if command.rpc_type == rpc.OBJECT_MESSAGE: method = self._get_method(command.message_name) call_id = command.message_id try: ret = method(*command.args, **command.kwargs) response = rpc( command.message_name, ret, response_to = call_id, rpc_type = rpc.OBJECT_MESSAGE_RESPONSE ) self.pipe.send(response) except Exception, e: logger.warn(msg("Exception while running command ", command.message_name, " exception == ", e)) response = rpc( 'error', response_to = call_id, rpc_type = rpc.ERROR_MESSAGE) response.error_typ = 'exception' try: response.error_description = str(e) except: pass response.exception = e self.pipe.send(response)
def run(self): self.object = self.object_class(*self.init_args, **self.init_kwargs) self.object.__process_interrupts = self._proc_interrupts self.object._wait = self._wait self.object.isolated_init() self._connect_all() #self.event_loop = ThreadedEventLoop() #self.event_loop.register_hook(self._single_step) #self.event_loop.start() # Print the stacktrace when we receive the SIGUSR1 signal #import signal #import traceback #import sys #signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack, file=sys.__stderr__)) while True: logger.debug(msg("remote_object.run: waiting for command ...")) self._single_step(block=True)
def load_config(self, filename): debug.msg('Loading configuration') self.config = config.GameConfig(filename)
def __updateSettings(self, key, controlVar): debug.msg("Key = " + key) debug.msg("Value = " + str(controlVar.get())) debug.msg("In Dict: " + key + " " + str(controlVar.get())) self.__statedict[key] = controlVar.get()
def run(self): debug.msg('Starting game') # Load configuration file self.load_config(util.resource.path('game.conf')) # Create window debug.msg('Creating window') director.init(width=self.config.getint('Graphics', 'screen_width'), height=self.config.getint('Graphics', 'screen_height'), do_not_scale=True, resizable=True, fullscreen=self.config.getboolean( 'Graphics', 'fullscreen')) director.show_FPS = True debug.msg('Chipmunk version ' + pymunk.chipmunk_version) debug.msg('Pymunk version ' + pymunk.version) # Run game scene scene = gamescene.GameScene() #scene.add(editor.EditorLayer(), z=1) scene.add(gameplay.GameplayLayer(), z=1) debug.msg('Starting game director') director.run(scene) debug.msg('Exiting game')
def __init__(self): debug.msg("PowerProjectPlugin init")
def activate(self, window): debug.msg("PowerProjectPlugin activate %s" % str(window)) window.set_data(CORE_INSTANCE_KEY, PowerProjectCore())
def deactivate(self, window): debug.msg("PowerProjectPlugin deactivate") window.get_data(CORE_INSTANCE_KEY)
def __init__(self): debug.msg('Initializing gameplay layer') super(GameplayLayer, self).__init__()