def quitHandler(engineReference, eventHandler): '''quitHandler will be called at the end of the program as well as the handler for a pygame.QUIT event. It sound only run once.''' if quitHandler.quitting: return quitHandler.quitting = True menulock.acquire() io.tsprint('MAIN: quit handler started.') engineReference.stopEngine() io.tsprint("MAIN: stopping sound and music...") SoundHandler.stopAll() SoundHandler.stopMusic() io.tsprint("MAIN: done") pygame.quit() if profiling: io.tsprint("MAIN: Stopping profiler and getting data....") fout = open(quitHandler.profilingDest, 'a+') l = yappi.get_stats(yappi.SORTTYPE_TTOTAL, yappi.SORTORDER_DESCENDING, yappi.SHOW_ALL) yappi.stop() if fout: for s in l: fout.write(s+'\n') fout.close() io.tsprint("MAIN: Profiling data written.") else: io.tserr("MAIN ERROR: Error opening file for profiling data") io.tsprint("MAIN: Exiting!")
def __init__(self, Sound=None): self.spritesheet = Image.SpriteSheet(path="res\\testSheet.png", spriteSize=32) self.OffsetX, self.OffsetY = 0, 0 self.animTiles = [] self.backRendered = False self.playerInputs = Constants.PlayerControls self.Entities = [] super().__init__() self.TileMap, caverns = Mapper.generateCellularAutomata() self.entitypositions = Mapper.placeEnemiesCellular(caverns) for position in self.entitypositions: self.Entities.append( Entities.TestEnemy(x=position[1], y=position[0], Map=self.TileMap)) playerPos = choice(caverns[0]) while playerPos in self.entitypositions: playerPos = choice(caverns[0]) self.player = Entities.Player(x=playerPos[1], y=playerPos[0], map=self.TileMap) self.graph = Pathfinding.Graph(self.TileMap) self.Sound = SoundHandler.Sound() self.Sound.PlayMusic('res/SFX/music.wav') self.offsetScene()
def runLevel(): SoundHandler.playMusic('un owen.wav') ''' Takes a reference to the engine and runs the level ''' f = [enemy.Fairy((250, 200), getVel()) for i in range(0,5)] f.extend([enemy.Fairy((75, 200-i*20), getVel()) for i in range(0,10)]) currentEngine.addEntities(f, engine.enemyType) f = [enemy.Fairy((75, i*20), getVel()) for i in range(0,10)] currentEngine.addEntities(f, engine.enemyType) for i in range(10): while currentEngine.entityCount(engine.enemyType) > 5: currentEngine.sleepSeconds(1) f = [enemy.Fairy((75, i*20), getVel()) for i in range(0,15)] currentEngine.addEntities(f, engine.enemyType)
def __init__( self ) : pygame.mixer.init() self.gamesettings = GameSettings() self.sound_handler = SoundHandler( self.gamesettings ) self.pause_time = 0 self.time = 0 self.garbage_body_list = [] self.garbage_joint_list = [] self.defaultZoom = 80.0 self.minZoom = 15 self.maxZoom = 285 super(Game, self).__init__() self.current_scene = 0 self.world.gravity = (0,0) self.image_handler = ImageHandler( self ) #self.change_scene(SCENE_TYPE_GAME, 'res/maps/compiled_map1.js') self.reset_zoom() #-100 is the mouse self.pressed_keys = [ -100 ] self.change_scene( SCENE_TYPE_MENU )
def __init__(self): super().__init__() self.Font = pygame.font.SysFont("Lucida Console", 56) self.TitleFont = pygame.font.SysFont("Lucida Console", 82) self.backgroundColour = (80, 180, 100) self.menuPointer = 0 self.Title = self.TitleFont.render('Coursework', True, (200, 200, 100)) self.offset = 120 # Dictionary that holds both the text to be displayed in # the menu as well as the corresponding function that # the option should call self.dictOptions = { 0: ('Start', self.start), 1: ('Settings', self.settings), 2: ('Leaderboard', self.leaderboard), 3: ('Exit', self.exit) } self.menu = [] self.Sound = SoundHandler.Sound()
def __init__(self, x: int, y: int, spriteSheet: str, spriteSize: int, interval: int): self.x, self.y = x, y self.name: str # Animation Attributes # Size represents the size of the spritesheets sprites not the sprites ingame self.size = spriteSize # Interval is the time each frame is rendered for self.interval = interval # The spritesheet the entity reads from self.spritesheet = Image.SpriteSheet(spriteSheet, self.size) # Pygame allows flipping surfaces, which will be useful for left / right self.flipped = False # The number of frames can inferred from the width of the spritesheet divided by the size of the sprites self.frames = int(self.spritesheet.returnSize()[0] / self.size) # The length it takes to run through all the sprites in the row self.animLength = self.frames * self.interval # The row the sprites should be taken from self.row = 0 # A value that will dictate what sprite should be shown self.tick = 0 # A default sprite so the program has something to render on the first frame self.sprite = self.spritesheet.returnSprite(0, self.row) self.Sound = SoundHandler.Sound()
class Game (Framework): def __init__( self ) : pygame.mixer.init() self.gamesettings = GameSettings() self.sound_handler = SoundHandler( self.gamesettings ) self.pause_time = 0 self.time = 0 self.garbage_body_list = [] self.garbage_joint_list = [] self.defaultZoom = 80.0 self.minZoom = 15 self.maxZoom = 285 super(Game, self).__init__() self.current_scene = 0 self.world.gravity = (0,0) self.image_handler = ImageHandler( self ) #self.change_scene(SCENE_TYPE_GAME, 'res/maps/compiled_map1.js') self.reset_zoom() #-100 is the mouse self.pressed_keys = [ -100 ] self.change_scene( SCENE_TYPE_MENU ) def change_scene( self, type, map_file = False ) : if self.current_scene != 0 : self.current_scene.destroy() self.take_out_garbage() self.total_reset() if type == SCENE_TYPE_MENU or type == SCENE_TYPE_DEFETED : self.sound_handler.stop_music( 'demons_acecream' ) self.sound_handler.stop_music( 'default' ) self.sound_handler.play_music( 'default' ) self.player_handler = PlayerHandler( self ) self.check_joysticks() self.current_scene = MenuScene( self ) if type == SCENE_TYPE_MENU: self.current_scene.run_top() elif type == SCENE_TYPE_DEFETED: self.current_scene.run_defeated() return True self.player_handler.check_player_opt_in( self.pressed_keys ) if os.path.isfile( map_file ) == False : self.current_scene = 0 return False with open (map_file, "r") as myfile : map_data = myfile.read().replace('\n', '') self.sound_handler.stop_music( 'demons_acecream' ) self.sound_handler.stop_music( 'default' ) self.sound_handler.play_music( 'demons_acecream' ) self.current_scene = GameScene( self, self.world, json.loads( map_data ) ) def reset_zoom( self ) : #This property manages zoom level self.viewZoom = self.defaultZoom def total_reset( self ) : while len( self.world.joints ) != 0 : garbage_joint = self.world.joints[0] self.world.DestroyJoint( garbage_joint ) while len( self.world.bodies ) != 0 : garbage_body = self.world.bodies[0] self.world.DestroyBody( garbage_body ) def take_out_garbage( self ) : while len( self.garbage_joint_list ) != 0: garbage_joint = self.garbage_joint_list[0] self.world.DestroyJoint( garbage_joint ) self.garbage_joint_list.remove( garbage_joint ) while len( self.garbage_body_list ) != 0: garbage_body = self.garbage_body_list[0] self.world.DestroyBody( garbage_body ) self.garbage_body_list.remove( garbage_body ) def Step(self, settings): if self.pause_time > 0 : self.pause_time -= 1 return self.time += 1 self.take_out_garbage() background_colour = (55,55,55) self.screen.fill( background_colour ) if self.current_scene != 0 : self.current_scene.Step() super( Game, self ).Step( settings ) self.current_scene.draw( self.viewZoom, self.viewOffset, settings ) self.player_handler.update( self.pressed_keys ) for contact in self.world.contacts : if contact.touching == False : continue fixtureA = contact.fixtureA fixtureB = contact.fixtureB if fixtureA.body.userData == None or fixtureB.body.userData == None : continue if fixtureA.body.userData.get( 'owner' ) == None or fixtureB.body.userData.get( 'owner' ) == None : continue fixtureA.body.userData.get( 'owner' ).handle_collision( fixtureA, fixtureB ) fixtureB.body.userData.get( 'owner' ).handle_collision( fixtureB, fixtureA ) def add_garbage_body( self, garbage_body ) : if garbage_body == None : return False if self.garbage_body_list.__contains__( garbage_body ) : return False self.garbage_body_list.append( garbage_body ) return True def remove_garbage_body( self, garbage_body ) : if self.garbage_body_list.__contains__( garbage_body ) : self.garbage_body_list.remove( garbage_body ) return True return False def add_garbage_joint( self, garbage_joint ) : if garbage_joint == None : return False if self.garbage_joint_list.__contains__( garbage_joint ) : return False self.garbage_joint_list.append( garbage_joint ) return True def remove_garbage_joint( self, garbage_joint ) : if self.garbage_joint_list.__contains__( garbage_joint ) : self.garbage_joint_list.remove( garbage_joint ) return True return False def check_joysticks( self ) : pygame.joystick.init() for i in range(pygame.joystick.get_count()): joystick = pygame.joystick.Joystick( i ) joystick.init() self.player_handler.joystick_list.append( joystick ) def Keyboard(self, key): if key in self.pressed_keys : return False self.pressed_keys += [ key ] return True def KeyboardUp(self, key): if key in self.pressed_keys : self.pressed_keys.remove( key ) return True return False def MousePos(self): return pygame.mouse.get_pos() def MouseDown(self, p): key = -101 if key in self.pressed_keys : return False self.pressed_keys += [ key ] def MouseUp(self, p): key = -101 if key in self.pressed_keys : self.pressed_keys.remove( key ) return True return False def checkEvents(self): for event in pygame.event.get(): if event.type == QUIT : return False elif (event.type == KEYDOWN and event.key == Keys.K_ESCAPE) : self.change_scene(SCENE_TYPE_MENU) elif event.type == KEYDOWN: self._Keyboard_Event(event.key, down=True) elif event.type == KEYUP: self._Keyboard_Event(event.key, down=False) elif event.type == MOUSEBUTTONDOWN: p = self.ConvertScreenToWorld(*event.pos) if event.button == 1: # left mods = pygame.key.get_mods() if mods & KMOD_LSHIFT: self.ShiftMouseDown( p ) else: self.MouseDown( p ) elif event.button == 2: #middle pass elif event.button == 3: #right self.rMouseDown = True elif event.button == 4: self.viewZoom += 1 if self.viewZoom > self.maxZoom : self.viewZoom = self.maxZoom self.image_handler.zoom_images() elif event.button == 5: self.viewZoom -= 1 if self.viewZoom < self.minZoom : self.viewZoom = self.minZoom self.image_handler.zoom_images() elif event.type == MOUSEBUTTONUP: p = self.ConvertScreenToWorld(*event.pos) if event.button == 3: #right self.rMouseDown = False else: self.MouseUp(p) elif event.type == MOUSEMOTION: p = self.ConvertScreenToWorld(*event.pos) self.MouseMove(p) if self.rMouseDown: self.viewCenter -= (event.rel[0]/5.0, -event.rel[1]/5.0) return True
"""Play one specific sound.""" def put(self, sound_id): if soundhandler.play_sound(sound_id): return sound_id, 202 else: abort('404', message='Sound {} not found'.format(sound_id)) # Resource Routing api.add_resource(OctoBlaGeneral, "/") api.add_resource(OctoBlaSound, '/sound/<string:sound_id>', '/sound') api.add_resource(OctoBlaPlayer, '/play/<string:sound_id>') api.add_resource(OctoBlaVolume, '/volume/<float:volume>', "/volume") if __name__ == "__main__": # read configuration, configure environment base_path =os.path.dirname(__file__) config_path = os.path.join(base_path, 'settings.cfg') config = conf.ConfigParser() config.read(config_path) soundhandler = sh.SoundHandler(os.path.join(base_path, config.get('Paths', 'SoundDir'))) soundhandler.set_volume(config.get('Audio', 'DefaultVolume')) # only accessible from localhost. # Don't use in productive environment! app.run(debug=True) # global accessible with optional ip range filter #app.run(host=config.get('General', 'Host'), port=config.get('General', 'Port'))
def setSound(self, state, sound): ''' INTERNAL USE ''' checkState(state) self.transitionSounds[state] = SoundHandler.load(sound)