def __init__(self,screen,backgr,rcdic,basepath,libdir): Img.screen = screen Img.backgr = backgr CPinit(Img.screen,Img.backgr)# mandatory when using anything from the SpriteUtils ## Keep a original surface, because the background will be changed Img.backorg = backgr.convert() self.rcdic = rcdic self.clock = pygame.time.Clock() self.eventget = pygame.event.get self.basedir = basepath self.libdir = libdir self.ttf = None # using pygame standard font self.gamelevels = range(1,4) self.gameitems = range(4) self.score = 0 self.stop = 0 file = os.path.join(self.libdir,'NumbersData','balloon.png') Img.balloon = load_image(file,1) file = os.path.join(self.libdir,'NumbersData','shot.wav') Snd.boom = load_sound(file) file = os.path.join(DATADIR,'wahoo.wav') Snd.wahoo = load_sound(file) file = os.path.join(DATADIR,'bummer.wav') Snd.bummer = load_sound(file) self._setup()
def start(self): """Mandatory method.""" self.GoodSound=utils.load_sound(os.path.join(self.CPdatadir, 'good.ogg')) self.WrongSound=utils.load_sound(os.path.join(self.CPdatadir, 'wrong.ogg')) p = os.path.join(self.CPdatadir,'good_%s.png' % self.lang) if not os.path.exists(p): p = os.path.join(self.CPdatadir,'thumbs.png') self.ThumbsUp = SPSpriteUtils.MySprite(utils.load_image(p)) i = utils.load_image(os.path.join(self.my_datadir, 'hint.png')) i_ro = utils.load_image(os.path.join(self.my_datadir, 'hint_ro.png')) self.HintBut = SimpleTransImgButton(i,i_ro, (370, 200)) if int(self.rchash[self.theme]['show_errors']): self.wrongImg = SPSpriteUtils.MySprite(utils.load_image(os.path.join(self.my_datadir, 'incorrect.png'))) else: self.wrongImg = None prev = os.path.join(self.my_datadir, 'findit_prev.png') prev_ro = os.path.join(self.my_datadir, 'findit_prev_ro.png') next = os.path.join(self.my_datadir, 'findit_next.png') next_ro = os.path.join(self.my_datadir, 'findit_next_ro.png') self.prevnextBut = TransPrevNextButton((370, 460), \ self._cbf_prevnext_button, \ prev, prev_ro, next, next_ro) self.imgdir = os.path.join(self.my_datadir, 'images', self.theme) if not os.path.exists(self.imgdir): self.imgdir = os.path.join(self.my_datadir, 'images','default') self.score = 0 self.AreWeDT = False # get language code loclang = utils.get_locale_local()[0]
def start(self): """Mandatory method.""" self.GoodSound = utils.load_sound( os.path.join(self.CPdatadir, 'good.ogg')) self.WrongSound = utils.load_sound( os.path.join(self.CPdatadir, 'wrong.ogg')) p = os.path.join(self.CPdatadir, 'good_%s.png' % self.lang) if not os.path.exists(p): p = os.path.join(self.CPdatadir, 'thumbs.png') self.ThumbsUp = SPSpriteUtils.MySprite(utils.load_image(p)) i = utils.load_image(os.path.join(self.my_datadir, 'hint.png')) i_ro = utils.load_image(os.path.join(self.my_datadir, 'hint_ro.png')) self.HintBut = SimpleTransImgButton(i, i_ro, (370, 200)) if int(self.rchash[self.theme]['show_errors']): self.wrongImg = SPSpriteUtils.MySprite( utils.load_image(os.path.join(self.my_datadir, 'incorrect.png'))) else: self.wrongImg = None prev = os.path.join(self.my_datadir, 'findit_prev.png') prev_ro = os.path.join(self.my_datadir, 'findit_prev_ro.png') next = os.path.join(self.my_datadir, 'findit_next.png') next_ro = os.path.join(self.my_datadir, 'findit_next_ro.png') self.prevnextBut = TransPrevNextButton((370, 460), \ self._cbf_prevnext_button, \ prev, prev_ro, next, next_ro) self.imgdir = os.path.join(self.my_datadir, 'images', self.theme) if not os.path.exists(self.imgdir): self.imgdir = os.path.join(self.my_datadir, 'images', 'default') self.score = 0 self.AreWeDT = False # get language code loclang = utils.get_locale_local()[0]
def __init__(self, screen, config, spawn_x, spawn_y, all_sprites): super(Mob, self).__init__() self.screen = screen # LOAD ASSETS # mandatory self.config = config self.all_sprites = all_sprites self.death_sounds = [] for death_file in config.death_sound_files: sound = load_sound(death_file) self.death_sounds.append(sound) # optional (but common) if hasattr(config, 'img_file'): self.image = load_image(config.img_file) if hasattr(config, 'bullet_img_file'): self.bullet_image = load_image(config.bullet_img_file) self.shoot_sounds = [] if hasattr(config, 'shoot_sound_files'): self.shoot_sounds = [] for shoot_file in config.shoot_sound_files: sound = load_sound(shoot_file) self.shoot_sounds.append(sound) # get rects if hasattr(self, "image"): self.rect = self.image.get_rect() self.rect.x = spawn_x self.rect.y = spawn_y self.screen_rect = self.screen.get_rect()
def __init__(self): #pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.mixer.init() if pygame.mixer: self.waka = load_sound('sounds/waka.wav') self.waka.set_volume(0.01) self.fruit = load_sound('sounds/fruit.wav') self.fruit.set_volume(0.01)
def initialise(self): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" #Initialize Everything pygame.display.flip() #Load options try: self.options = pickle.load(open('options.p', 'rb')) except: print "No options" self.options = {'Difficulty':'Hard', 'Music':'Off'} self.game_paused = False #sounds self.sounds = {}; self.sounds['glass'] = utils.load_sound('glass.ogg') self.sounds['throw'] = utils.load_sound('throw.ogg') #Create The Backgound self.background, foo = utils.load_image('back.png') #game variables self.clients_served = 0 self.speed = 50 #the lower the faster self.score = 0 self.mugs = 10 self.time = 0 #to check the stage for clients self.client_score = 500 self.mug_score = 500 #Display The Background self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.level = Stage('level_1') #The player's ship self.bartender = Bartender() #The dash indicators #group that stores all enemies self.beers = pygame.sprite.Group() #group that stores all powerups self.clients = pygame.sprite.Group() #group for information sprites in the screen, should be rendered the last one self.hud = pygame.sprite.Group() self.font = utils.load_font('saloon.ttf', 20) self.game_started = False self.game_finished = False self.level_finished = False
def initialise(self): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" #Initialize Everything pygame.init() self.screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('VacuumFire') pygame.mouse.set_visible(0) #icon icon, foo = utils.load_image('icon.png') pygame.display.set_icon(icon) self.game_paused = False #sounds self.sounds = {}; self.sounds['music'] = utils.load_sound('archivo.ogg') self.sounds['warning'] = utils.load_sound('warning.wav') self.sounds['powerup'] = utils.load_sound('powerup.wav') self.sounds['music'].play() #Create The Backgound self.background = Background(self.screen.get_size()) #game variables self.score = 0 #Display The Background self.screen.blit(self.background, (0, 0)) pygame.display.flip() #The player's ship self.ship = Ship() #The player's ship self.lifemeter = LifeMeter() self.player = pygame.sprite.RenderPlain((self.ship)) #group that stores all enemies self.enemies = pygame.sprite.Group() #group that stores all powerups self.powerups = pygame.sprite.Group() #group that stores all the lasers the player shoots self.fire = pygame.sprite.Group() #group for information sprites in the screen, should be rendered the last one self.hud = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.hud.add(self.lifemeter) #The level self.level = Stage('level_1') self.font = utils.load_font('4114blasterc.ttf', 36) self.clock = pygame.time.Clock() self.game_started = False self.game_finished = False
def initialise(self): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" #Initialize Everything pygame.display.flip() #Load options try: self.options = pickle.load(open('options.p', 'rb')) except: print "No options" self.options = {'Difficulty': 'Hard', 'Music': 'Off'} self.game_paused = False #sounds self.sounds = {} self.sounds['glass'] = utils.load_sound('glass.ogg') self.sounds['throw'] = utils.load_sound('throw.ogg') #Create The Backgound self.background, foo = utils.load_image('back.png') #game variables self.clients_served = 0 self.speed = 50 #the lower the faster self.score = 0 self.mugs = 10 self.time = 0 #to check the stage for clients self.client_score = 500 self.mug_score = 500 #Display The Background self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.level = Stage('level_1') #The player's ship self.bartender = Bartender() #The dash indicators #group that stores all enemies self.beers = pygame.sprite.Group() #group that stores all powerups self.clients = pygame.sprite.Group() #group for information sprites in the screen, should be rendered the last one self.hud = pygame.sprite.Group() self.font = utils.load_font('saloon.ttf', 20) self.game_started = False self.game_finished = False self.level_finished = False
def __init__(self,SPGoodies): """SPGoodies is a class object that SP sets up and will contain references to objects, callback methods and observers TODO: add more explaination""" self.logger = logging.getLogger("childsplay.numbers_sp.Activity") self.logger.info("Activity started") self.SPG = SPGoodies self.lang = self.SPG.get_localesetting()[0][:2] self.scoredisplay = self.SPG.get_scoredisplay() self.theme = self.SPG.get_theme() self.screen = self.SPG.get_screen() self.screenclip = self.SPG.get_screenclip() self.blit_pos = self.screenclip.left, self.screenclip.top self.orgscreen = pygame.Surface(self.screenclip.size) # we use this to restore the screen self.orgscreen.blit(self.screen, (0, 0), self.screenclip) self.backgr = self.SPG.get_background() # The location of the activities Data dir self.my_datadir = os.path.join(self.SPG.get_libdir_path(),'CPData','Numbers_spData') # Location of the CPData dir which holds some stuff used by multiple activities self.CPdatadir = os.path.join(self.SPG.get_libdir_path(),'CPData') # Location of the alphabet sounds dir self.absdir = self.SPG.get_absdir_path()# alphabet sounds dir self.rchash = utils.read_rcfile(os.path.join(self.my_datadir, 'numbers_sp.rc')) self.logger.debug("rchash: " + str(self.rchash)) # You MUST call SPInit BEFORE using any of the SpriteUtils stuff # it returns a reference to the special CPGroup self.actives = SPSpriteUtils.SPInit(self.screen,self.backgr) self.GoodSound=utils.load_sound(os.path.join(self.CPdatadir, 'good.ogg')) self.WrongSound=utils.load_sound(os.path.join(self.CPdatadir, 'wrong.ogg')) self.Done=utils.load_sound(os.path.join(self.CPdatadir, 'wahoo.wav')) b = os.path.join(self.CPdatadir, '200px_80px_blue.png') b_ro = os.path.join(self.CPdatadir, '200px_80px_black.png') self.beginbut = SPWidgets.TransImgButton(b, b_ro, \ (300, 510), fsize=24, text= _("Begin"),\ fcol=WHITE) self.beginbut.connect_callback(self._cbf_begin, MOUSEBUTTONDOWN) self.cheatbut = SPWidgets.TransImgButton(b, b_ro, \ (300, 510), fsize=24, text= _("Cheat"),\ fcol=WHITE) self.cheatbut.connect_callback(self._cbf_cheat, MOUSEBUTTONDOWN) self.playfield = utils.load_image(os.path.join(self.my_datadir, "playfield.png")).convert() self.playfield_position = (40, 120) self.list_pos = [] r = self.playfield.get_rect() x, y = self.playfield_position for i in range(((r.w - 10) / 70)): for j in range(((r.h - 10) / 70)): self.list_pos.append(((i * 70) + x + 10, (j* 70) + y + 10))
def jump(self): self.rect.y += 2 # verifica se houve colisao ao subir (bater a cabeca em alguma coisa) platform_hit_list = pygame.sprite.spritecollide( self, self.level.platform_list, False ) self.rect.y -= 2 list_len = len(platform_hit_list) if (list_len > 0 or self.rect.bottom >= const.SCREEN_HEIGHT): self.move_y = -10 utils.load_sound("jump.wav").play()
def __init__(self): # initialize pygame, setup screen pygame.init() pygame.mixer.init() self.save = shelve.open('game_save') self.running = True self.can_restart = False self.manage_death = False self.manage_victory = False self.god_mode = Game.god_mode self.current_level = self.save['current_level'] self.sounds = {} self.msg = {} self.sounds['level_completed'] = utils.load_sound( 'level_completed.wav') self.sounds['game_completed'] = utils.load_sound('game_completed.wav') self.screen = pygame.display.set_mode(Game.screen_res) pygame.display.set_caption(Game.caption) self.interface_font = pygame.font.match_font(Game.interface_font_name) self.background_img = utils.load_image(Game.background_img_file) self.background_rect = self.background_img.get_rect() self.clock = pygame.time.Clock() # initialize sprites self.all_sprites = pygame.sprite.Group() self.enemy_bullets = pygame.sprite.Group() self.enemy_sprites = pygame.sprite.Group() self.player_sprites = pygame.sprite.Group() self.player = Player(self.screen, self.all_sprites) self.player.add(self.all_sprites, self.player_sprites) self.player_score = ScoreCounter(self.player, self.save['player_score'], self.screen, self.interface_font, 25, RGB.BLACK) self.msg['game_completed'] = Msg(self.screen, self.interface_font, 65, 90, 1, RGB.GREEN, "Congratulations! Game completed!", Msg.MSG_PULSE) self.msg['lvl_completed'] = Msg(self.screen, self.interface_font, 100, 175, 2, RGB.GREEN, "Victory!", Msg.MSG_PULSE) self.msg['player_killed'] = Msg(self.screen, self.interface_font, 100, 175, 2, RGB.RED, "Game Over!", Msg.MSG_FADE) self.endgame_initiated = None self.player_score.add(self.all_sprites) self.player_bullets = pygame.sprite.Group() self.enemy_rows = [] self.read_xml()
def initialise(self): # Initialize Everything pygame.display.flip() self.game_paused = False # sounds self.sounds = {} self.sounds["plop"] = utils.load_sound("plop.wav") # Create The Backgound self.background, foo = utils.load_image("background.png") # Display The Background self.screen.blit(self.background, (0, 0)) pygame.display.flip() # group that stores all bubbles self.bubbles = pygame.sprite.Group() self.flying_scores = pygame.sprite.Group() # game variables self.score = Score_Meter((10, 10, 10, 10)) self.flying_scores.add(self.score) self.bubble_grid = Bubblegrid(13, 20, self.bubbles) # group for information sprites in the screen, should be rendered the last one self.font = utils.load_font("chitown.ttf", 20) self.game_started = False self.game_finished = False self.level_finished = False
def __init__(self, position, create_bullet_callback): self.create_bullet_callback = create_bullet_callback self.blaster_sound = load_sound("blaster") # Make a copy of the original UP vector self.direction = Vector2(LEFT_TO_RIGHT) super().__init__(position, load_sprite("disinfector"), Vector2(0))
def __init__(self, screen, bg, cancion=None, cuerdas=None): self.cancion = cancion self.sounds = [load_sound(s) for s in SOUNDS] self.screen = screen self.screen.blit(bg, (0,0)) self.exit = False self.clock = pygame.time.Clock()
def __init__(self, position, create_bullet_callback): self.create_bullet_callback = create_bullet_callback self.laser_sound = load_sound("laser") # Make a copy of the original UP vector self.direction = Vector2(UP) super().__init__(position, load_sprite("spaceship"), Vector2(0))
def __init__(self, allsprites, song): self.state = 'prestart' self.allsprites = allsprites self.keyboard_button = [] self.song = song self.font = load_font(song.get_font_filename(), 36) self.notes_are_dropping = False self.song_is_finished = False # Reads and plays audio from notes files self.music_player = MusicPlayer(song, self) # Responsible for loading and animating the background self.background_handler = BackgroundHandler(song) # Assigns falling notes to correct hitbox self.note_dropper = NoteDropper(self.music_player) # Responsible for managing (high) scores self.scoreHandler = ScoreHandler(self.allsprites,self, self.song) # Load sound which plays when a note is missed self.sounds_miss = load_sound(song.get_sound_miss()) # Define Hitboxes input_keys = ['a', 's', 'd', 'f'] self.hitboxes = [ Hitbox('hitbox-example.png', 0, input_keys[0], self.allsprites), Hitbox('hitbox-example.png', 1, input_keys[1], self.allsprites), Hitbox('hitbox-example.png', 2, input_keys[2], self.allsprites), Hitbox('hitbox-example.png', 3, input_keys[3], self.allsprites), ]
def __init__(self, nextScene, teamColor): """ @param nextScene: The scene which should come after this win screen @param teamColor: The color of the winning team @summary: Initializes win screen for the winning team """ Scene.__init__(self) self.nextScene = nextScene self.frame = Frame() text = "!!! Congratulations !!!\n" text += "\n" text += "The " + teamColor + " team has won" labelText = Label(text) labelText.rect.center = (self.frame.rect.width / 2, self.frame.rect.height / 2) buttonBack = Button("Back", self.runNextScene) buttonBack.rect.size = (128, 32) buttonBack.rect.centerx = self.frame.rect.width / 2 buttonBack.rect.bottom = self.frame.rect.height - 32 self.frame.addWidget(labelText) self.frame.addWidget(buttonBack) self.victory_sound = load_sound("victory.ogg") self.victory_sound.play()
def __init__(self, SPGoodies): """SPGoodies is a class object that SP sets up and will contain references to objects, callback methods and observers TODO: add more explaination""" self.logger = logging.getLogger("childsplay.electro_sp.Activity") self.logger.info("Activity started") self.SPG = SPGoodies self.theme = self.SPG.get_theme() self.screen = self.SPG.get_screen() self.screenclip = self.SPG.get_screenclip() self.blit_pos = self.screenclip.left, self.screenclip.top self.orgscreen = pygame.Surface( self.screenclip.size) # we use this to restore the screen self.orgscreen.blit(self.screen, (0, 0), self.screenclip) self.backgr = self.SPG.get_background() # The location of the activities Data dir self.my_datadir = os.path.join(self.SPG.get_libdir_path(), 'CPData', 'Electro_spData') self.rchash = utils.read_rcfile( os.path.join(self.my_datadir, 'electro_sp.rc')) self.rchash['theme'] = self.theme self.logger.debug("rchash: %s" % self.rchash) # Location of the CPData dir which holds some stuff used by multiple activities self.CPdatadir = os.path.join(self.SPG.get_libdir_path(), 'CPData') # Location of the alphabet sounds dir self.absdir = self.SPG.get_absdir_path() # alphabet sounds dir # You MUST call SPInit BEFORE using any of the SpriteUtils stuff # it returns a reference to the special CPGroup self.actives = SPSpriteUtils.SPInit(self.screen, self.backgr) self.scoredisplay = self.SPG.get_scoredisplay() files = ('dealcard1.wav', 'good.ogg', 'wrong.ogg', 'button_hover.wav') self.Sound = Snd() for file in files: setattr(self.Sound, file[:-4], utils.load_sound(os.path.join(self.CPdatadir, file)))
def __init__(self,SPGoodies): """SPGoodies is a class object that SP sets up and will contain references to objects, callback methods and observers TODO: add more explaination""" self.logger = logging.getLogger("childsplay.electro_sp.Activity") self.logger.info("Activity started") self.SPG = SPGoodies self.theme = self.SPG.get_theme() self.screen = self.SPG.get_screen() self.screenclip = self.SPG.get_screenclip() self.blit_pos = self.screenclip.left, self.screenclip.top self.orgscreen = pygame.Surface(self.screenclip.size) # we use this to restore the screen self.orgscreen.blit(self.screen, (0, 0), self.screenclip) self.backgr = self.SPG.get_background() # The location of the activities Data dir self.my_datadir = os.path.join(self.SPG.get_libdir_path(),'CPData','Electro_spData') self.rchash = utils.read_rcfile(os.path.join(self.my_datadir, 'electro_sp.rc')) self.rchash['theme'] = self.theme self.logger.debug("rchash: %s" % self.rchash) # Location of the CPData dir which holds some stuff used by multiple activities self.CPdatadir = os.path.join(self.SPG.get_libdir_path(),'CPData') # Location of the alphabet sounds dir self.absdir = self.SPG.get_absdir_path()# alphabet sounds dir # You MUST call SPInit BEFORE using any of the SpriteUtils stuff # it returns a reference to the special CPGroup self.actives = SPSpriteUtils.SPInit(self.screen,self.backgr) self.scoredisplay = self.SPG.get_scoredisplay() files = ('dealcard1.wav','good.ogg','wrong.ogg','button_hover.wav') self.Sound = Snd() for file in files: setattr(self.Sound, file[:-4], utils.load_sound(os.path.join(self.CPdatadir, file)))
def __init__(self, space_game, **kwargs): kwargs['orientation'] = 0 SpaceShip.__init__(self, space_game, **kwargs) self.score = 0 self.gun_fire_interval = 0.1 if self._keyboard == None and platform not in ("android", "ios"): self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self.gun = RepeaterGun(space_game=self.space_game) self.add_widget(self.gun) self.gun.center_x = self.center_x self.gun.center_y = self.center_y self.boom = load_sound('sounds/boom.ogg', volume=FX_VOLUME) # Add touch events layer self.player_speed = Vector(0, 0) self.bullet_rate = 0.0 self.player_motion = None self.bullet_fire = None touch_layer = FloatLayout(pos_hint=(0, 0), size_hint=(1., 1.)) touch_layer.bind( on_touch_down=self.on_touch_down, on_touch_move=self.on_touch_move, on_touch_up=self.on_touch_up, ) self.add_widget(touch_layer) self._update_event = Clock.schedule_interval(self.update, FPS)
def __init__(self, position, sprite, velocity): self.sprite = rotozoom(sprite, 0, 0.05) super().__init__(position, self.sprite, velocity) self.click_sound = load_sound("click_new2") self.bounces = 0 self.clipping = 0 return
def __init__(self, pos, volume=None, voice_unmute=True, defval=50): """defval - value between 0, silent, and 100, maximum, volume level.""" Widget.__init__(self) self.logger = logging.getLogger("childsplay.SPWidgets.VolumeAdjust") self.logger.debug("VolumeAdjust called with volume level %s" % volume) self.soundcheck = utils.load_sound(os.path.join(ACTIVITYDATADIR, 'CPData','volumecheck.wav')) self.theme = self.THEME['theme'] if volume or int(volume) == 0: #print "we have volume" self.volume = int(volume) elif self.WEHAVEAUMIX: #print "we have aumix" self.volume = int(self.WEHAVEAUMIX) else: #print "else defval" self.volume = int(defval) self.logger.debug("setting volume string to %s" % self.volume) self.volstr = '%02d' % self.volume + "%" # TODO: set fgcol and bgcol kwargs ? self.logger.debug("setting voice unmute to %s" % voice_unmute) imgup = os.path.join(THEMESPATH, self.theme,'core_volup_button.png') imgup_ro = os.path.join(THEMESPATH, self.theme,'core_volup_button_ro.png') imgdown = os.path.join(THEMESPATH, self.theme,'core_voldown_button.png') imgdown_ro = os.path.join(THEMESPATH, self.theme,'core_voldown_button_ro.png') px, py = pos prev = os.path.join(THEMESPATH, self.theme, 'core_volume_button.png') prev_ro = os.path.join(THEMESPATH, self.theme, 'core_volume_button_ro.png') next = os.path.join(THEMESPATH, self.theme, 'core_volmute_button.png') next_ro = os.path.join(THEMESPATH, self.theme, 'core_volmute_button_ro.png') self.lbl0 = Label(_("Quiz voice"), pos, fsize=18, padding=4, minh=48) px += self.lbl0.rect.w + 10 self.voicetoggle = TransPrevNextButton((px, py), self._cbf_toggle_voice, \ prev, prev_ro,\ next, next_ro, states=[True,False]) py += self.voicetoggle.rect.h + 20 px = pos[0] self.lbl1 = Label(self.volstr, pos, fsize=18, padding=4, border=1, minh=48) self.volumetoggle = TransPrevNextButton((px, py), self._cbf_toggle_volume, \ prev, prev_ro,\ next, next_ro) px += self.volumetoggle.rect.w + 20 self.voldownbut = TransImgButton(imgdown, imgdown_ro, (px, py)) self.voldownbut.mouse_hover_leave_action = True self.voldownbut.connect_callback(self._cbf, MOUSEBUTTONUP, -5) px += self.voldownbut.rect.w self.lbl1.moveto((px , py+4)) px += self.lbl1.rect.w self.volupbut = TransImgButton(imgup, imgup_ro, (px, py)) self.volupbut.mouse_hover_leave_action = True self.volupbut.connect_callback(self._cbf, MOUSEBUTTONUP, 5) if self.volume == 0: self.volumetoggle.toggle() self.volumetoggle.display_sprite() if not voice_unmute: self.voicetoggle.toggle() self.voicetoggle.display_sprite()
def __init__(self, **kwargs): kwargs["transition"] = FadeTransition() super(ShooterGame, self).__init__(**kwargs) self.bg_music = load_sound('sounds/StarCommander1.ogg') if self.bg_music: self.bg_music.play() self.bg_music.loop = True
def initialize(self): print(f"Initializing the '{self.sceneName}' level...") # Loading resources (images, audio, etc.) before beginning scene Player.image = load_image("player.gif") Player.shootSound = load_sound("laser.ogg") Laser.image = load_image("laser.gif") Enemy.image = load_image("spider.gif") self.background = load_image("background2.gif").convert() # Initialize sprite group self.lasers = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.all = pygame.sprite.RenderUpdates() # Assign groups to sprites Laser.containers = self.lasers, self.all Enemy.containers = self.aliens, self.all Player.containers = self.all Score.containers = self.all Lives.containers = self.all self.player = Player() self.score = Score() self.lives = Lives(self.player.lives) self.all.add(self.score) self.all.add(self.lives) self.generate_enemies()
def __init__(self): if not pygame.font: print 'Warning, fonts disabled' if not pygame.mixer: print 'Warning, sound disabled' """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" #Initialize Everything pygame.init() #self.screen = pygame.display.set_mode((640, 480), pygame.FULLSCREEN | pygame.DOUBLEBUF) self.screen = pygame.display.set_mode((640, 480), pygame.HWSURFACE) pygame.display.set_caption('VacuumFire') #pygame.display.toggle_fullscreen() pygame.mouse.set_visible(0) #icon icon, foo = utils.load_image('icon.png') pygame.display.set_icon(icon) intro = Intro(self.screen) vacuum = False self.clock = pygame.time.Clock() #Load musics self.music = {} self.music['game'] = utils.load_sound('level_1.ogg') self.music_game_playing = False self.music['intro'] = utils.load_sound('intro.ogg') self.music['intro'].play() #Loop intro or game depending on intro's state while 1: self.clock.tick(50) if intro.menu_finished == False: intro.loop() else: self.music['intro'].stop() if self.music_game_playing == False: self.music['game'].play() self.music_game_playing = True if vacuum == False: vacuum = Vacuum(self.screen) if vacuum.scene_finished == True: intro = Intro(self.screen) vacuum = False else: vacuum.loop() pygame.display.flip()
def __init__(self, screen, mode): ''' Constructor Create table to play match a and all necessary variables ''' # Texts font = utils.load_font("monof55.ttf", 18) font_big = utils.load_font("monof55.ttf", 22) score = TextItem("Score", font_big, INFO_X, SCORE_Y) score_val = TextItem("0", font, INFO_X, SCORE_VAL_Y) self.texts = [score, score_val] if mode == MODE_MOVE: self.texts.append(TextItem("Moves", font_big, INFO_X, COUNT_Y)) self.texts.append( TextItem(str(MAX_MOVES), font, INFO_X, COUNT_VAL_Y)) elif mode == MODE_TIME: self.texts.append(TextItem("Time", font_big, INFO_X, COUNT_Y)) self.texts.append( TextItem(str(MAX_TIME), font, INFO_X, COUNT_VAL_Y)) self.move_sound = utils.load_sound("move.wav") self.square_sound = utils.load_sound("square.wav") self.table = [] # Table of squares for r in range(TAB_H): self.table.append([]) for c in range(TAB_W): self.table[r].append(Square(r, c)) self.screen = screen self.mode = mode self.score = 0 self.moves = 0 self.start_time = time.time() # Variables to handle the gameplay self.button_down = False # Is the mouse left button clicked? self.current_color = (0, 0, 0 ) # Color being selected after a mouse click self.chain = [] # Chain of selected squares self.chain_sorted = { } # Useful dictionary to be used when deleting squares self.all_same_color = [ ] # All squares not in chain to be deleted because of a BigSquare self.before_square = None # To store the last place before a square was composed self.count_after_square = 0
def start(self): """Mandatory method.""" self.SPG.tellcore_set_dice_minimal_level(6) fs = 36 self.scoreboard = ScoreBoard(self.rc_dic, size=fs) Img.winner = utils.load_image(os.path.join(self.my_datadir,'winner.jpg'),1) Img.loser = utils.load_image(os.path.join(self.my_datadir,'loser.jpg'),1) self.skipstart = None# used when the user sets a predefined game play in the config file self.skipsplash = None if self.rc_dic['sound'].lower() == 'no': Snd.pong = utils.load_sound(os.path.join(self.my_datadir,'')) Snd.winner = utils.load_sound(os.path.join(self.my_datadir,'')) Snd.goal = utils.load_sound(os.path.join(self.my_datadir,'')) Snd.bump = utils.load_sound(os.path.join(self.my_datadir,'')) else: Snd.pong = utils.load_sound(os.path.join(self.my_datadir,'pick.wav')) Snd.winner = utils.load_music(os.path.join(self.my_datadir,'winner.ogg')) Snd.goal = utils.load_sound(os.path.join(self.my_datadir,'goal.wav')) Snd.bump = utils.load_sound(os.path.join(self.my_datadir,'bump.wav')) #set kind of game play # we only check for multi and multipc, anything else is considerd single play # which is the default if self.rc_dic['gameplay'] == 'multi': self.restart([[None,'2']]) self.skipstart = 1 elif self.rc_dic['gameplay'] == 'multipc': self.restart([[None,'3']]) self.skipstart = 1
def __init__(self, position, create_bullet_callback): # Create a callback for bullets self.create_bullet_callback = create_bullet_callback # Load the sound file for the lasers self.laser_sound = load_sound("laser") # Add a direction to the spaceship, make a copy of the constant UP self.direction = Vector2(UP) # Call to parent class constructor super().__init__(position, load_sprite("spaceship"), Vector2(0))
def checkHealth(self): """ Check the health of the current snail. If the snail hits less or equal than 0 HP, play a sound and set attribut isAlive to false This method is called in Snail.update """ if self.hitpoints <= 0: kill_sound = load_sound("kill.ogg") kill_sound.play() self.isAlive = False
def __init__(self, text, callback, *args): """ @param text: The text that should be showed on the button @param callback: This function will be called when someone clicks the button @param args: The parameters for the callback @summary: Initializes a button """ self.font_size = 25 self.font = pygame.font.Font(None, self.font_size) self.rect = pygame.Rect(0,0,1,1) self.text = text self.callback = callback self.pressed = False self.args = None self.button_sound = load_sound("button.ogg") argSize = len(args) if(0 < argSize): self.args = args self.button_sound = load_sound("button.ogg")
def __init__(self, screen, cuerdas, cancion): self.cuerdas = cuerdas self.sounds = [load_sound(s) for s in SOUNDS] self.cancion = [] #hasta 18 cuerdas self.objetivo = cancion self.screen = screen self.load_bg() self.draw_cuerdas() self.widgets = pygame.sprite.OrderedUpdates() self.exit = False self.clock = pygame.time.Clock()
def __init__(self, screen, mode): ''' Constructor Create table to play match a and all necessary variables ''' # Texts font = utils.load_font("monof55.ttf", 18) font_big = utils.load_font("monof55.ttf", 22) score = TextItem("Score", font_big, INFO_X, SCORE_Y) score_val = TextItem("0", font, INFO_X, SCORE_VAL_Y) self.texts = [score, score_val] if mode == MODE_MOVE: self.texts.append(TextItem("Moves", font_big, INFO_X, COUNT_Y)) self.texts.append(TextItem(str(MAX_MOVES), font, INFO_X, COUNT_VAL_Y)) elif mode == MODE_TIME: self.texts.append(TextItem("Time", font_big, INFO_X, COUNT_Y)) self.texts.append(TextItem(str(MAX_TIME), font, INFO_X, COUNT_VAL_Y)) self.move_sound = utils.load_sound("move.wav") self.square_sound = utils.load_sound("square.wav") self.table = [] # Table of squares for r in range(TAB_H): self.table.append([]) for c in range(TAB_W): self.table[r].append(Square(r,c)) self.screen = screen self.mode = mode self.score = 0 self.moves = 0 self.start_time = time.time() # Variables to handle the gameplay self.button_down = False # Is the mouse left button clicked? self.current_color = (0,0,0) # Color being selected after a mouse click self.chain = [] # Chain of selected squares self.chain_sorted = {} # Useful dictionary to be used when deleting squares self.all_same_color = [] # All squares not in chain to be deleted because of a BigSquare self.before_square = None # To store the last place before a square was composed self.count_after_square = 0
def __init__(self, screen, cuerdas, cancion, cancionwav, next): self.cuerdas = cuerdas self.sounds = [load_sound(s) for s in SOUNDS] self.cancion = [] #hasta 16 cuerdas self.cancionwav = cancionwav self.objetivo = cancion self.screen = screen self.load_bg() self.next = next self.draw_cuerdas() self.exit = False self.clock = pygame.time.Clock()
def start(self): """Mandatory method.""" self.snd_butts = [] backdir = os.path.join(self.my_datadir,'backgrounds', self.lang) yellow_sound = utils.load_sound(os.path.join(self.my_datadir,'1.ogg')) red_sound = utils.load_sound(os.path.join(self.my_datadir,'2.ogg')) blue_sound = utils.load_sound(os.path.join(self.my_datadir,'3.ogg')) green_sound = utils.load_sound(os.path.join(self.my_datadir,'4.ogg')) self.good_sound=utils.load_sound(os.path.join(self.my_datadir,'good.ogg')) self.wrong_sound=utils.load_sound(os.path.join(self.my_datadir,'wrong.ogg')) self.backgr_normal = utils.load_image(os.path.join(backdir,'background.png')) self.backgr_start = utils.load_image(os.path.join(backdir,'background_start.png')) self.backgr_tussen = utils.load_image(os.path.join(backdir,'background_repeat.png')) self.backgr_good = utils.load_image(os.path.join(backdir,'background_correct.png')) self.backgr_wrong = utils.load_image(os.path.join(backdir,'background_wrong.png')) yellow_on = utils.load_image(os.path.join(self.my_datadir,'yellow.png')) yellow_off = utils.load_image(os.path.join(self.my_datadir,'yellow_off.png')) self.yellow_but = SndButton(yellow_off, yellow_on, yellow_sound,(14,245+self.yTop),\ self.snd_but_observer, CYELLOW) #self.yellow_but.set_use_current_background(True) self.snd_butts.append(self.yellow_but) red_on = utils.load_image(os.path.join(self.my_datadir,'red.png')) red_off = utils.load_image(os.path.join(self.my_datadir,'red_off.png')) self.red_but = SndButton(red_off, red_on, red_sound,(400,16+self.yTop), \ self.snd_but_observer, CRED) #self.red_but.set_use_current_background(True) self.snd_butts.append(self.red_but) blue_on = utils.load_image(os.path.join(self.my_datadir,'blue.png')) blue_off = utils.load_image(os.path.join(self.my_datadir,'blue_off.png')) self.blue_but = SndButton(blue_off, blue_on, blue_sound,(14,16+self.yTop),\ self.snd_but_observer, CBLUE) #self.blue_but.set_use_current_background(True) self.snd_butts.append(self.blue_but) green_on = utils.load_image(os.path.join(self.my_datadir,'green.png')) green_off = utils.load_image(os.path.join(self.my_datadir,'green_off.png')) self.green_but = SndButton(green_off, green_on, green_sound, (400,245+self.yTop),\ self.snd_but_observer, CGREEN) #self.green_but.set_use_current_background(True) self.snd_butts.append(self.green_but) img = utils.load_image(os.path.join(self.my_datadir,self.lang,'start.png')) self.start_but = CenterButton(img, (232, 148+self.yTop)) self.start_but.connect_callback(self._cbf_start_button, MOUSEBUTTONDOWN) img = utils.load_image(os.path.join(self.my_datadir,self.lang,'simon.png')) self.simon_but = CenterButton(img, (232, 148+self.yTop)) img = utils.load_image(os.path.join(self.my_datadir,self.lang,'good.png')) self.good_but = CenterButton(img, (232, 148+self.yTop)) img = utils.load_image(os.path.join(self.my_datadir,self.lang,'wrong.png')) self.wrong_but = CenterButton(img, (232, 148+self.yTop)) # lookup hash for the sounds dbase field, see generate_sequence for the # number of sounds in each level self.level_sounds_hash = {1:2, 2:3, 3:3, 4:4, 5:5, 6:6} self.scoredisplay.clear_score() self.AreWeDT = False self.score = 0
def score_observer(self, score): self.aquarium_counter = 0 self.WeAreAquarium = False self.aquarium_text.erase_sprite() self.actives.remove(self.aquarium_text) # if self.aquariumsound: # self.aquariumsound.stop() snd = utils.load_sound(os.path.join(self.my_datadir,'sounds', 'poolsplash.wav')) snd.play() if score < 0: score = 1 self.scoredisplay.increase_score(score + self.level*6)
def __init__(self, player): Level.__init__(self, player) self.background = utils.load_image("background_01.jpg") self.sound = utils.load_sound("level1.ogg") """ Array com o tipo de plataforma, posicao x, y e localizado dentro do sprite """ level = [ [platforms.GRASS_LEFT, 500, 500], [platforms.GRASS_MIDDLE, 570, 500], [platforms.GRASS_RIGHT, 640, 500], [platforms.GRASS_LEFT, 800, 400], [platforms.GRASS_MIDDLE, 870, 400], [platforms.GRASS_RIGHT, 940, 400], [platforms.GRASS_LEFT, 1000, 500], [platforms.GRASS_MIDDLE, 1070, 500], [platforms.GRASS_RIGHT, 1140, 500], [platforms.STONE_PLATFORM_LEFT, 1120, 280], [platforms.STONE_PLATFORM_MIDDLE, 1190, 280], [platforms.STONE_PLATFORM_RIGHT, 1260, 280], [platforms.YELLOW_BOX, 1360, 20], [platforms.ARROW_RIGHT, 0, 530], [platforms.EXIT, 1900, 530]] # criando uma travessia de corda for x in xrange(1, 8): level.append([platforms.ROPE, 1360 + 70 * x, 300]), # Recupera as plataformas a partir das coordernadas em level for platform in level: block = platforms.Platform(platform[0]) block.rect.x = platform[1] block.rect.y = platform[2] block.player = self.player self.platform_list.add(block) # Adiciona movimento personalizado as plataformas block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 1350 block.rect.y = 280 block.boundary_left = 1350 block.boundary_right = 1600 block.change_x = 1 block.player = self.player block.level = self self.platform_list.add(block)
def __init__(self, owner): if Laser.sound_laser == 0: Laser.sound_laser = utils.load_sound('laser-01.wav') pygame.sprite.Sprite.__init__(self) #call Sprite intializer Laser.sound_laser.play() Laser.num+=1 self.owner = owner #this makes the animation self.images = ('laser.gif', 'laser.gif', 'laser2.gif', 'laser2.gif', 'laser.gif', 'laser2.gif') self.image_anim_counter = 0 self.image, self.rect = utils.load_image(self.images[0], -1) self.rect = owner.rect.copy() self.rect.top+= owner.rect.height/2-10 self.rect.left+= owner.rect.width*0.5
def __init__(self,SPGoodies): """SPGoodies is a class object that SP sets up and will contain references to objects, callback methods and observers TODO: add more explaination""" self.logger = logging.getLogger("childsplay.fishtank.Activity") self.logger.info("Activity started") self.SPG = SPGoodies self.scoredisplay = self.SPG.get_scoredisplay() self.theme = self.SPG.get_theme() self.screen = self.SPG.get_screen() self.screenclip = self.SPG.get_screenclip() self.blit_pos = self.screenclip.left, self.screenclip.top self.orgscreen = pygame.Surface(self.screenclip.size) # we use this to restore the screen self.orgscreen.blit(self.screen, (0, 0), self.screenclip) self.backgr = self.SPG.get_background() # The location of the activities Data dir self.my_datadir = os.path.join(self.SPG.get_libdir_path(),'CPData','FishtankData') # Location of the CPData dir which holds some stuff used by multiple activities self.CPdatadir = os.path.join(self.SPG.get_libdir_path(),'CPData') # Location of the alphabet sounds dir self.absdir = self.SPG.get_absdir_path()# alphabet sounds dir self.rchash = utils.read_rcfile(os.path.join(self.my_datadir, 'fishtank.rc')) self.rchash['theme'] = self.theme self.sounddir = os.path.join(self.my_datadir,'sounds') self.bubimg = utils.load_image(os.path.join(self.my_datadir,'backgrounds',self.theme,'blub0.png')) self.bubsnd = utils.load_sound(os.path.join(self.sounddir,'blub0.wav')) self.splashsnd = utils.load_sound(os.path.join(self.sounddir,'poolsplash.wav')) self.WeAreAquarium = False self.aquarium_counter = 0 self.aquarium_music_list = glob.glob(os.path.join(self.sounddir,'*.ogg')) # You MUST call SPInit BEFORE using any of the SpriteUtils stuff # it returns a reference to the special CPGroup self.actives = SPSpriteUtils.SPInit(self.screen,self.backgr) self.actives.set_onematch(True)
def __init__(self, bartending, lane): pygame.sprite.Sprite.__init__(self) #Load the sounds if they are not loaded #they will be load with the appeareance of the first client if len(Client.sounds) == 0: Client.sounds.append(utils.load_sound('shout_0.ogg')) Client.sounds.append(utils.load_sound('shout_1.ogg')) Client.sounds.append(utils.load_sound('shout_2.ogg')) #assign a random sound to the client shout = Client.sounds[random.randint(0, len(Client.sounds) - 1)] shout.play() self.num_client = Client.num_clients Client.num_clients += 1 pic = random.randint(0, len(Client.images) - 1) self.image, self.rect = utils.load_image(Client.images[pic]) self.cur_lane = lane self.rect.top = Client.lanes_y[lane] - 25 self.rect.left = Client.lanes_x_ini[lane] self.speed = 1 self.bartending = bartending self.age = 0 self.time_drinking = 0 self.state = Client.WAITING self.drinking_time = 25
def __init__(self, bartending, lane): pygame.sprite.Sprite.__init__(self) #Load the sounds if they are not loaded #they will be load with the appeareance of the first client if len(Client.sounds) == 0: Client.sounds.append(utils.load_sound('shout_0.ogg')) Client.sounds.append(utils.load_sound('shout_1.ogg')) Client.sounds.append(utils.load_sound('shout_2.ogg')) #assign a random sound to the client shout = Client.sounds[random.randint(0,len(Client.sounds)-1)] shout.play() self.num_client = Client.num_clients Client.num_clients += 1 pic = random.randint(0,len(Client.images)-1) self.image, self.rect = utils.load_image(Client.images[pic]) self.cur_lane = lane self.rect.top = Client.lanes_y[lane] -25 self.rect.left = Client.lanes_x_ini[lane] self.speed = 1 self.bartending = bartending self.age = 0 self.time_drinking = 0 self.state = Client.WAITING self.drinking_time = 25
def initialise(self): #Initialize Everything pygame.display.flip() self.game_paused = False #sounds self.sounds = {}; self.sounds['plop'] = utils.load_sound('plop.wav') #Create The Backgound self.background, foo = utils.load_image('background.png') #Display The Background self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.level = Level() self.platforms = pygame.sprite.Group() self.sprites = pygame.sprite.Group() self.hud = pygame.sprite.Group() first_platform_x = False #Load the platforms in the level for i in range(len(self.level.data)-1): self.level.scroll += 1 platforms = self.level.platforms() for platform in platforms: if first_platform_x == False: first_platform_x = platform * self.level.ratio self.platforms.add(Platform(pygame.Rect(platform*self.level.ratio, 640 - self.level.scroll * self.level.y_ratio,10,10))) self.player = Player(self) self.player.rect.left = first_platform_x self.sprites.add(self.player) #game variables self.score = Score_Meter((10,10,10,10)) self.hud.add(self.score) self.font = utils.load_font('chitown.ttf', 20) self.game_started = False self.game_finished = False self.level_finished = False
def __init__(self, top = -1): pygame.sprite.Sprite.__init__(self) #call Sprite intializer if Alien.sound_bomb == None: Alien.sound_bomb = utils.load_sound('bomb-02.wav') self.images = ('alien1.gif', 'alien2.gif', 'alien3.gif', 'alien4.gif') self.cycle = 0 self.value = random.randint(0,len(self.images)-1) self.image, self.rect = utils.load_image(self.images[self.value], -1) self.contains_powerup = (random.randint(1,15) == 1) if top == -1: self.rect.top = random.randint(0,480) else: self.rect.top = top self.rect.left = 640 self.move = -random.randint(1,3) self.amplitude = random.randint(1,5) self.frequency = random.random()*0.1+0.05 self.target = None
def __init__(self, player): Level.__init__(self, player) self.background = utils.load_image("background_02.jpg") self.sound = utils.load_sound("level2.ogg") level = [[platforms.STONE_PLATFORM_LEFT, 500, 550], [platforms.STONE_PLATFORM_MIDDLE, 570, 550], [platforms.STONE_PLATFORM_RIGHT, 640, 550], [platforms.STONE_PLATFORM_LEFT, 800, 400], [platforms.STONE_PLATFORM_MIDDLE, 870, 400], [platforms.STONE_PLATFORM_RIGHT, 940, 400], [platforms.STONE_PLATFORM_LEFT, 1000, 500], [platforms.STONE_PLATFORM_MIDDLE, 1070, 500], [platforms.STONE_PLATFORM_RIGHT, 1140, 500], [platforms.STONE_PLATFORM_LEFT, 1120, 280], [platforms.STONE_PLATFORM_MIDDLE, 1190, 280], [platforms.STONE_PLATFORM_RIGHT, 1260, 280], [platforms.BRIGDE, 1360, 150], [platforms.EXIT, 1900, 530]] # criando uma ponte de madeira for x in xrange(1, 10): level.append([platforms.BRIGDE, 1360 + 70 * x, 150]), for platform in level: block = platforms.Platform(platform[0]) block.rect.x = platform[1] block.rect.y = platform[2] block.player = self.player self.platform_list.add(block) block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 1500 block.rect.y = 300 block.boundary_top = 100 block.boundary_bottom = 550 block.change_y = -1 block.player = self.player block.level = self self.platform_list.add(block)
def __init__(self, top = -1): pygame.sprite.Sprite.__init__(self) #call Sprite intializer if Alien.sound_bomb == None: Alien.sound_bomb = utils.load_sound('bomb-02.wav') self.age = 0 self.cycle = 0 self.cycle_2 = 0 #Cache in the class static if Alien.images == False: images = [] for image_file in Alien.images_files: image, rect = utils.load_image(image_file, -1) images.append((image,rect)) Alien.images = images else: images = Alien.images self.value = random.randint(0,len(self.images)-1) self.image, self.rect = images[self.value] self.contains_powerup = (random.randint(1,Alien.ratio_powerup) == 1) if top == -1: self.rect.top = random.randint(0,480) else: self.rect.top = top self.rect.left = 640 #Plane, fast forward if self.value == 4: self.move = -random.randint(2,7) self.agressivity = random.randint(1,2) self.amplitude = 0 self.amplitude_2 = 0 self.frequency = 0 self.frequency_2 = 0 else: self.move = -random.randint(2,7) self.agressivity = random.randint(1,5) self.amplitude = random.randint(1,5) self.amplitude_2 = random.randint(0,5) self.frequency = random.random()*0.1+0.05 self.frequency_2 = random.random()*0.2 self.target = None
def __init__(self, snail): """ @param snail: The snail which has shooted this object. This will also be used to calculate the position of this object @summary: Initializes a shootable object """ pygame.sprite.Sprite.__init__(self) self.image = load_image("bullet.png") self.rect = self.image.get_rect() # Calculate the x and y speed of the bullet self.speed = [0,0] self.snail = snail position = [0,0] position[0] = snail.rect.centerx position[1] = snail.rect.centery self.rect.center = position self.isAlive = True self.isProtected = True self.explosionSound = load_sound("cannon.ogg")
def __init__(self): controller = mvcState.GetController() controller.gameEventListeners.append( self ) self.timeSinceSound = 0 self.shootSounds = [ load_sound( 'geyser00.ogg' ), load_sound( 'geyser01.ogg' ), ] self.ventSounds = [ load_sound( 'geyser02.ogg' ), load_sound( 'geyser03.ogg' ), ] self.chaChing = load_sound('chaching.ogg') self.win = load_sound('win.ogg')
def __init__(self): controller = mvcState.GetController() controller.gameEventListeners.append(self) self.timeSinceSound = 0 self.shootSounds = [ load_sound('geyser00.ogg'), load_sound('geyser01.ogg'), ] self.ventSounds = [ load_sound('geyser02.ogg'), load_sound('geyser03.ogg'), ] self.chaChing = load_sound('chaching.ogg') self.win = load_sound('win.ogg')
def __init__(self, player): Level.__init__(self, player) self.background = utils.load_image("background_03.png") self.sound = utils.load_sound("level3.ogg") level = [[platforms.STONE_PLATFORM_LEFT, 500, 550], [platforms.STONE_PLATFORM_MIDDLE, 570, 550], [platforms.STONE_PLATFORM_RIGHT, 640, 550], [platforms.STONE_PLATFORM_LEFT, 800, 400], [platforms.STONE_PLATFORM_MIDDLE, 870, 400], [platforms.STONE_PLATFORM_RIGHT, 940, 400], [platforms.STONE_PLATFORM_LEFT, 1000, 500], [platforms.STONE_PLATFORM_MIDDLE, 1070, 500], [platforms.STONE_PLATFORM_RIGHT, 1140, 500], [platforms.STONE_PLATFORM_LEFT, 1120, 280], [platforms.STONE_PLATFORM_MIDDLE, 1190, 280], [platforms.STONE_PLATFORM_RIGHT, 1260, 280], [platforms.GRASS_LEFT, 1700, 500], [platforms.GRASS_MIDDLE, 1770, 500], [platforms.GRASS_RIGHT, 1840, 500], [platforms.EXIT, 1950, 530]] for platform in level: block = platforms.Platform(platform[0]) block.rect.x = platform[1] block.rect.y = platform[2] block.player = self.player self.platform_list.add(block) block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) block.rect.x = 1500 block.rect.y = 300 block.boundary_top = 100 block.boundary_bottom = 550 block.change_y = -1 block.player = self.player block.level = self self.platform_list.add(block)
def __init__(self, app): logging.info('Initializing game') self.app = app self.chips = pygame.sprite.Group() self.current_consecutive_chips = deque(maxlen=4) self.red_player = objects.RedPlayer() self.yellow_player = objects.YellowPlayer() logging.info('Loading images') self.board_cell_image = utils.load_image('board_cell.png') self.board_cell_highlighted_image = utils.load_image( 'board_cell_highlighted.png') logging.info('Loading sounds') self.sounds_volume = self.app.config.getfloat('connectfour', 'sounds_volume') self.musics_volume = self.app.config.getfloat('connectfour', 'music_volume') self.placed_sound = utils.load_sound('placed.wav', volume=self.sounds_volume) self.column_change_sound = utils.load_sound('column_change.wav', volume=self.sounds_volume) self.column_full_sound = utils.load_sound('column_full.wav', volume=self.sounds_volume) self.win_sound = utils.load_sound('win.wav', volume=self.sounds_volume) self.applause_sound = utils.load_sound('applause.wav', volume=self.sounds_volume) self.boo_sound = utils.load_sound('boo.wav', volume=self.sounds_volume) logging.info('Loading fonts') self.title_font = utils.load_font('monofur.ttf', 22) self.normal_font = utils.load_font('monofur.ttf', 16) self.init_new_game()
def __load_resource_by_key(self, key): type, filename = key.split("_", 1) if type == "image": value = load_image(filename) self.__setitem__(key, value) return value elif type == "block": value = load_image(os.path.join("blocks", filename), convert_alpha=False) self.__setitem__(key, value) return value elif type == "shatter": value = load_image(os.path.join("blocks", "shattered.png"), convert_alpha=False, colorkey=True) value.set_alpha(int(filename)) self.__setitem__(key, value) return value elif type == "surface" and filename == "screen": value = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.__setitem__(key, value) return value elif type == "audio": value = load_sound(filename) self.__setitem__(key, value) return value elif type == "font": fontname, size = filename.split('/') value = load_font(fontname, int(size)) self.__setitem__(key, value) return value elif type == "livesfont": value = self["font_audiowide.ttf/28"].render(filename, True, self.ORANGE) self.__setitem__(key, value) return value elif type == "scorefont": value = self["font_audiowide.ttf/17"].render(filename, True, self.ORANGE) self.__setitem__(key, value) return value elif type == "comboplussign": value = self["font_audiowide.ttf/40"].render(filename, True, self.ORANGE) self.__setitem__(key, value) return value elif type == "clock": value = pygame.time.Clock() self.__setitem__(key, value) return value elif type == "fn": if filename == "is_time_distortion_field_active": value = self.game.is_time_distortion_field_active self.__setitem__(key, value) return value elif filename == "create_powerup": value = self.game.create_powerup self.__setitem__(key, value) return value elif filename == "add_ball": value = self.game.add_ball self.__setitem__(key, value) return value elif filename == "add_life": value = self.game.add_life self.__setitem__(key, value) return value elif filename == "add_extrapoint": value = self.game.add_extrapoint self.__setitem__(key, value) return value elif filename == "activate_time_distortion_field": value = self.game.activate_time_distortion_field self.__setitem__(key, value) return value elif filename == "double_damage": value = self.game.double_damage self.__setitem__(key, value) return value raise KeyError("Invalid resource key: " + key)
RATE_PLAYER_SPEED = 6 # Probability that determines if it's an energetic asteroid. PROB_ENERGETIC_ASTEROID = 0.4 OBJECTIVE_LVL = 100 # Destroy 100 enemies pygame.init() window = pygame.display.set_mode(DISPLAYMODE) font1 = pygame.font.SysFont("Liberation Serif", 24) font2 = pygame.font.SysFont("Liberation Serif", 20) font3 = pygame.font.SysFont("Arial", 20) font4 = pygame.font.SysFont("Times New Roman", 36) font5 = pygame.font.SysFont("Liberation Serif", 40) # Points font6 = pygame.font.SysFont("Sans Serif", 23) # Set up sounds intro_sound = load_sound('intro.ogg', 0.3) background_sound = load_sound('game_music.ogg', 1.0) explosion_sound = load_sound('explosion1.ogg', 0.3) motor_on_sound = load_sound('motor_on.ogg', 0.4) pickup_sound = load_sound('pickup.ogg', 0.3) game_over_sound = load_sound('game_over.ogg', 1.0) game_lost_sound = load_sound('game_lost.ogg', 1.0) game_won_sound = load_sound('game_won.ogg', 1.0) # We randomly select any of these sounds for the enemy lst_sound_laser = [ "laser1.ogg", "laser2.ogg", "laser3.ogg", "laser4.ogg", "laser5.ogg" ] laser_droid_sound = load_sound(random.choice(lst_sound_laser), 0.3) laser_player_sound = load_sound('laser_player.ogg', 0.3)
def __init__(self, **kwargs): super(RepeaterGun, self).__init__(**kwargs) self.gun_fire_interval = 0.3 self.gun_cooldown = time() self.laser = load_sound('sounds/laser2.ogg')
def __init__(self, **kwargs): super(SpreadGun, self).__init__(**kwargs) self.gun_cooldown = time() self.laser = load_sound('sounds/laser2.ogg')
def __init__(self, space_game, **kwargs): SpaceShip.__init__(self, space_game) Actor.__init__(self, **kwargs) self.min_y = dp(200) self.boom = load_sound("sounds/boom.ogg")
def __init__(self, pos, volume=None, voice_unmute=True, defval=50): """defval - value between 0, silent, and 100, maximum, volume level.""" Widget.__init__(self) self.logger = logging.getLogger("childsplay.SPWidgets.VolumeAdjust") self.logger.debug("VolumeAdjust called with volume level %s" % volume) self.soundcheck = utils.load_sound( os.path.join(ACTIVITYDATADIR, 'CPData', 'volumecheck.wav')) self.theme = self.THEME['theme'] if volume or int(volume) == 0: #print "we have volume" self.volume = int(volume) elif self.WEHAVEAUMIX: #print "we have aumix" self.volume = int(self.WEHAVEAUMIX) else: #print "else defval" self.volume = int(defval) self.logger.debug("setting volume string to %s" % self.volume) self.volstr = '%02d' % self.volume + "%" # TODO: set fgcol and bgcol kwargs ? self.logger.debug("setting voice unmute to %s" % voice_unmute) imgup = os.path.join(THEMESPATH, self.theme, 'core_volup_button.png') imgup_ro = os.path.join(THEMESPATH, self.theme, 'core_volup_button_ro.png') imgdown = os.path.join(THEMESPATH, self.theme, 'core_voldown_button.png') imgdown_ro = os.path.join(THEMESPATH, self.theme, 'core_voldown_button_ro.png') px, py = pos prev = os.path.join(THEMESPATH, self.theme, 'core_volume_button.png') prev_ro = os.path.join(THEMESPATH, self.theme, 'core_volume_button_ro.png') next = os.path.join(THEMESPATH, self.theme, 'core_volmute_button.png') next_ro = os.path.join(THEMESPATH, self.theme, 'core_volmute_button_ro.png') self.lbl0 = Label(_("Quiz voice"), pos, fsize=18, padding=4, minh=48) px += self.lbl0.rect.w + 10 self.voicetoggle = TransPrevNextButton((px, py), self._cbf_toggle_voice, \ prev, prev_ro,\ next, next_ro, states=[True,False]) py += self.voicetoggle.rect.h + 20 px = pos[0] self.lbl1 = Label(self.volstr, pos, fsize=18, padding=4, border=1, minh=48) self.volumetoggle = TransPrevNextButton((px, py), self._cbf_toggle_volume, \ prev, prev_ro,\ next, next_ro) px += self.volumetoggle.rect.w + 20 self.voldownbut = TransImgButton(imgdown, imgdown_ro, (px, py)) self.voldownbut.mouse_hover_leave_action = True self.voldownbut.connect_callback(self._cbf, MOUSEBUTTONUP, -5) px += self.voldownbut.rect.w self.lbl1.moveto((px, py + 4)) px += self.lbl1.rect.w self.volupbut = TransImgButton(imgup, imgup_ro, (px, py)) self.volupbut.mouse_hover_leave_action = True self.volupbut.connect_callback(self._cbf, MOUSEBUTTONUP, 5) if self.volume == 0: self.volumetoggle.toggle() self.volumetoggle.display_sprite() if not voice_unmute: self.voicetoggle.toggle() self.voicetoggle.display_sprite()
def start(self): """Mandatory method.""" self.snd_butts = [] backdir = os.path.join(self.my_datadir, 'backgrounds', self.lang) if not os.path.exists(backdir): backdir = os.path.join(self.my_datadir, 'backgrounds', 'en') yellow_sound = utils.load_sound(os.path.join(self.my_datadir, '1.ogg')) red_sound = utils.load_sound(os.path.join(self.my_datadir, '2.ogg')) blue_sound = utils.load_sound(os.path.join(self.my_datadir, '3.ogg')) green_sound = utils.load_sound(os.path.join(self.my_datadir, '4.ogg')) self.good_sound = utils.load_sound( os.path.join(self.my_datadir, 'good.ogg')) self.wrong_sound = utils.load_sound( os.path.join(self.my_datadir, 'wrong.ogg')) self.backgr_normal = utils.load_image( os.path.join(backdir, 'background.png')) self.backgr_start = utils.load_image( os.path.join(backdir, 'background_start.png')) self.backgr_tussen = utils.load_image( os.path.join(backdir, 'background_repeat.png')) self.backgr_good = utils.load_image( os.path.join(backdir, 'background_correct.png')) self.backgr_wrong = utils.load_image( os.path.join(backdir, 'background_wrong.png')) yellow_on = utils.load_image( os.path.join(self.my_datadir, 'yellow.png')) yellow_off = utils.load_image( os.path.join(self.my_datadir, 'yellow_off.png')) self.yellow_but = SndButton(yellow_off, yellow_on, yellow_sound,(14,245+self.yTop),\ self.snd_but_observer, CYELLOW) #self.yellow_but.set_use_current_background(True) self.snd_butts.append(self.yellow_but) red_on = utils.load_image(os.path.join(self.my_datadir, 'red.png')) red_off = utils.load_image(os.path.join(self.my_datadir, 'red_off.png')) self.red_but = SndButton(red_off, red_on, red_sound,(400,16+self.yTop), \ self.snd_but_observer, CRED) #self.red_but.set_use_current_background(True) self.snd_butts.append(self.red_but) blue_on = utils.load_image(os.path.join(self.my_datadir, 'blue.png')) blue_off = utils.load_image( os.path.join(self.my_datadir, 'blue_off.png')) self.blue_but = SndButton(blue_off, blue_on, blue_sound,(14,16+self.yTop),\ self.snd_but_observer, CBLUE) #self.blue_but.set_use_current_background(True) self.snd_butts.append(self.blue_but) green_on = utils.load_image(os.path.join(self.my_datadir, 'green.png')) green_off = utils.load_image( os.path.join(self.my_datadir, 'green_off.png')) self.green_but = SndButton(green_off, green_on, green_sound, (400,245+self.yTop),\ self.snd_but_observer, CGREEN) #self.green_but.set_use_current_background(True) self.snd_butts.append(self.green_but) langdatadir = os.path.join(self.my_datadir, self.lang) if not os.path.exists(langdatadir): langdatadir = os.path.join(self.my_datadir, 'en') img = utils.load_image(os.path.join(langdatadir, 'start.png')) self.start_but = CenterButton(img, (232, 148 + self.yTop)) self.start_but.connect_callback(self._cbf_start_button, MOUSEBUTTONDOWN) img = utils.load_image(os.path.join(langdatadir, 'simon.png')) self.simon_but = CenterButton(img, (232, 148 + self.yTop)) img = utils.load_image(os.path.join(langdatadir, 'good.png')) self.good_but = CenterButton(img, (232, 148 + self.yTop)) img = utils.load_image(os.path.join(langdatadir, 'wrong.png')) self.wrong_but = CenterButton(img, (232, 148 + self.yTop)) # lookup hash for the sounds dbase field, see generate_sequence for the # number of sounds in each level self.level_sounds_hash = {1: 2, 2: 3, 3: 3, 4: 4, 5: 5, 6: 6} self.scoredisplay.clear_score() self.AreWeDT = False self.score = 0
def next_level(self, level, dbmapper): """Mandatory method. Return True if there levels left. False when no more levels left.""" if level > 6: return False if level == self.level: self.levelrestartcounter += 1 self.level = level if self.blit_pos[1] == 0: ty = 10 else: ty = 110 # Lower framerate as we only check for mouse events and don't have animated # sprites self.SPG.tellcore_set_framerate(10) SndBut.Selected = None # make sure we don't have old sprites in the group self.actives.empty() # restore screen self.clear_screen() #pygame.display.update() r, c, xoffset, yoffset = self.gamelevels[level - 1] x_offset = self.snd_img.get_width() + 16 y_offset = self.snd_img.get_height() + 16 # shuffle sounds random.shuffle(self.all_sounds_files) num = (r * c) / 2 files = self.all_sounds_files[:num] * 2 self.num_of_buttons = len(files) self.levelupcount = 1 # db_mapper is a Python class object that provides easy access to the # dbase. self.db_mapper = dbmapper # store number of cards into the db table 'cards' col self.db_mapper.insert('sounds', self.num_of_buttons) random.shuffle(files) # used to record how many times the same card is shown. # It's setup in the next_level method and used by the Card objects. # we store it into a class namespace to make it globally available. Global.selected_cards = {} i = 1 for y in range(r): for x in range(c): sfile = files.pop() snd = utils.load_sound(sfile) if self.beamer_set == 'on': obj = SndBut(snd,\ (xoffset + x*x_offset,yoffset + y*y_offset+ty),\ self.snd_img_b.copy(),self.snd_img_high_b.copy(), sfile, self.scoreobs) f = os.path.join(self.my_datadir, "%s.png" % i) s = utils.load_image(f) obj.set_number(s) i += 1 else: obj = SndBut(snd,\ (xoffset + x*x_offset,yoffset + y*y_offset+ty),\ self.snd_img.copy(),self.snd_img_high.copy(), sfile, self.scoreobs) self.actives.add(obj) obj.display_sprite() Global.selected_cards[obj] = 0 return True