class SoundDecorator(FrameDecorator):
    def __init__(self, parent_component=NullComponent(), sound_file_path=''):
        self.sound_file_path = sound_file_path
        self.parent = parent_component
        self.sound = Sound(sound_file_path)
        self.start_time = 0

    def get_parent(self):
        return self.parent

    def set_parent(self, new_parent):
        self.parent = new_parent

    def get_landmarks(self):
        self.parent.get_landmarks()

    def get_image(self):
        self.play()
        return self.parent.get_image()

    def play(self):
        if not self.is_playing():
            self.start_time = time()
            self.sound.play()

    def is_playing(self):
        now = time()
        return self.sound.get_length() > now - self.start_time

    def stop(self):
        self.sound.stop()
        self.start_time = 0

    def copy(self):
        return SoundDecorator(parent_component=self.parent.copy(), sound_file_path=self.sound_file_path)
Example #2
0
    def setup(self, all_sprites):
        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"),
                        layer=0)

        all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5),
                        layer=1)

        all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), layer=1)        

        # sounds
        Sound("assets/audio/panel/215.wav").play()
        Sound("assets/audio/enter_authorization_code.wav").play()
        self.sound_granted = Sound("assets/audio/accessing.wav")
        self.sound_beep1 = Sound("assets/audio/panel/206.wav")
        self.sound_denied = Sound("assets/audio/access_denied.wav")
        self.sound_deny1 = Sound("assets/audio/deny_1.wav")
        self.sound_deny2 = Sound("assets/audio/deny_2.wav")

        self.attempts = 0
        self.granted = False
Example #3
0
class LcarsButton(LcarsWidget):
    def __init__(self, colour, pos, text, handler=None):
        self.handler = handler
        image = pygame.image.load("assets/button.png").convert()
        size = (image.get_rect().width, image.get_rect().height)
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                   (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))

        self.image = image
        self.colour = colour
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")

    def handleEvent(self, event, clock):
        handled = False
        
        if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)):
            self.applyColour(colours.WHITE)
            self.highlighted = True
            self.beep.play()
            handled = True

        if (event.type == MOUSEBUTTONUP and self.highlighted):
            self.applyColour(self.colour)
            if self.handler:
                self.handler(self, event, clock)
                handled = True
            
        LcarsWidget.handleEvent(self, event, clock)
        return handled
Example #4
0
class LcarsButton(LcarsWidget):
    """Button - either rounded or rectangular if rectSize is spcified"""

    def __init__(self, colour, pos, text, handler=None, rectSize=None):
        if rectSize == None:
            image = pygame.image.load("assets/button.png").convert()
            size = (image.get_rect().width, image.get_rect().height)
        else:
            size = rectSize
            image = pygame.Surface(rectSize).convert()
            image.fill(colour)

        self.colour = colour
        self.image = image
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))
    
        LcarsWidget.__init__(self, colour, pos, size, handler)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")

    def handleEvent(self, event, clock):
        if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)):
            self.applyColour(colours.WHITE)
            self.highlighted = True
            self.beep.play()

        if (event.type == MOUSEBUTTONUP and self.highlighted):
            self.applyColour(self.colour)
           
        return LcarsWidget.handleEvent(self, event, clock)
Example #5
0
def _make_sample(slot):
    """
        Makes Sound instances tuple and sets Sound volumes
    """
    global SAMPLES_DIR
    sample_file = os.path.join(SAMPLES_DIR, slot['sample'])
    sample = Sound(sample_file)
    sample.set_volume(slot.get('volume', 100) / 100.0)
    return sample
Example #6
0
class Audio:

    PLAY = 0
    PAUSE = 1
    STOP = 2
    GRAVITY = 0
    DEATH = 1

    def __init__(self):
        mixer.init(frequency=44100, size=-16, channels=4, buffer=128)
        self._background_s = Sound(os.path.join("res", "background.ogg"))
        self._background_s.set_volume(0.8)
        self._grav_fxs_s = [
            Sound(os.path.join("res", "grav1.wav")),
            Sound(os.path.join("res", "grav2.wav")),
            Sound(os.path.join("res", "grav3.wav")),
        ]
        for s in self._grav_fxs_s:
            s.set_volume(0.1)
        self._death_s = Sound(os.path.join("res", "death.wav"))

        self._background_channel = mixer.Channel(0)
        self._fx_channel = mixer.Channel(1)
        self.effect_playing = False
        self.bg_playing = False

    def bg(self, state=0):
        if state == self.PLAY:
            if self._background_channel.get_sound() == None:
                self._background_channel.play(self._background_s, loops=-1, fade_ms=250)
            else:
                self._background_channel.unpause()
            self.bg_playing = True
        elif state == self.PAUSE:
            self._background_channel.pause()
            self.bg_playing = False
        else:
            self._background_channel.stop()
            self.bg_playing = False

    def fx(self, state=0, fx=0):
        if state == self.PLAY:
            if fx == self.GRAVITY:
                if self._fx_channel.get_sound() not in self._grav_fxs_s:
                    self._fx_channel.stop()
                    self._fx_channel.play(choice(self._grav_fxs_s), loops=0, fade_ms=0)
            else:
                if self._fx_channel.get_sound() != self._death_s:
                    self._fx_channel.stop()
                    self._fx_channel.play(self._death_s, loops=0, fade_ms=0)

        elif state == self.PAUSE:
            self._fx_channel.pause()
        else:
            self._fx_channel.stop()
Example #7
0
class ScreenAuthorize(LcarsScreen):

    def setup(self, all_sprites):
        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"),
                        layer=0)

        all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5),
                        layer=1)

        all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), layer=1)        

        # sounds
        Sound("assets/audio/panel/215.wav").play()
        Sound("assets/audio/enter_authorization_code.wav").play()
        self.sound_granted = Sound("assets/audio/accessing.wav")
        self.sound_beep1 = Sound("assets/audio/panel/206.wav")
        self.sound_denied = Sound("assets/audio/access_denied.wav")
        self.sound_deny1 = Sound("assets/audio/deny_1.wav")
        self.sound_deny2 = Sound("assets/audio/deny_2.wav")

        self.attempts = 0
        self.granted = False

    def handleEvents(self, event, fpsClock):
        LcarsScreen.handleEvents(self, event, fpsClock)

        if event.type == pygame.MOUSEBUTTONDOWN:
            if (self.attempts > 1):
                self.granted = True
                self.sound_beep1.play()
            else:
                if self.attempts == 0: self.sound_deny1.play()
                else: self.sound_deny2.play()
                self.granted = False
                self.attempts += 1

        if event.type == pygame.MOUSEBUTTONUP:
            if (self.granted):
                self.sound_granted.play()
                from screens.main import ScreenMain
                self.loadScreen(ScreenMain())
            else:
                self.sound_denied.play()
        

        return False
Example #8
0
def play_wav(name, *args):
    """This is a convenience method to play a wav.

    *args
      These are passed to play.

    Return the sound object.

    """
    s = Sound(filepath(name))
    s.play(*args)
    return s
Example #9
0
    def show(self):
        # Initialize options
        font = resources.get_font('prstartcustom.otf')
        self.options.init(font, 15, True, MORE_WHITE)

        # Initialize sounds
        self.select_sound = Sound(resources.get_sound('menu_select.wav'))
 def __init__(self):
     """Declare and initialize instance variables."""
     self.is_running = False
     self.voice = Sound(VOICE_PATH)
     self.voice_duration = (self.voice.get_length() * FRAME_RATE)
     self.voice_timer = 0
     self.voice_has_played = False
Example #11
0
class Bass:
    __author__ = 'James Dewes'

    def __init__(self):
        try:
            import pygame.mixer
            from pygame.mixer import Sound
        except RuntimeError:
            print("Unable to import pygame mixer sound")
            raise Exception("Unable to import pygame mixer sound")

        self.soundfile = "launch_bass_boost_long.wav"
        self.mixer = pygame.mixer.init() #instance of pygame
        self.bass = Sound(self.soundfile)

    def start(self):
        state = self.bass.play()
        while state.get_busy() == True:
            continue

    def stop(self):
        try:
            Pass
        except Exception:
            raise Exception("unable to stop")
Example #12
0
	def __init__(self, pos, color_interval, input):
		PhysicsObject.__init__(self, pos, (0, 0), (28, 48), BODY_DYNAMIC)
		self.change_color_mode = False
		self.color_interval = 0
		self.color_timer_text = None
		if color_interval > 0:
			self.change_color_mode = True
			self.color_interval = color_interval
			font = Font('./assets/font/vcr.ttf', 18)
			self.color_timer_text = Text(font, str(color_interval), (740, 5))
			self.color_timer_text.update = True
		self.color_timer = 0.0
		self.input = input
		self.sprite = Sprite("./assets/img/new_guy.png", (64, 64), (1.0 / 12.0))
		self.set_foot(True)
		self.active_color = 'red'
		self.acceleration = 400
		self.dead = False
		self.sound_jump = Sound('./assets/audio/jump.wav')
		self.sound_land = Sound('./assets/audio/land.wav')
		self.sound_push = Sound('./assets/audio/push.wav')
		self.sound_timer = 0.0
		self.sound_min_interval = 0.5
		self.id = ID_PLAYER
		self.bounce_timer = 0.0

		# view rectangle for HUD stuff
		self.view_rect = Rect(0, 0, 0, 0)
Example #13
0
    def show(self):
        font = resources.get_font('prstartcustom.otf')

        # Make title
        font_renderer = pygame.font.Font(font, 15)
        self.title_surface = font_renderer.render('Hi-scores', True, NOT_SO_BLACK)

        # Make all scores
        # Get the score with highest width
        max_width_score = max(self.scores, key=self.score_width)
        # Calculate its width, and add 4 dots
        max_width = self.score_width(max_width_score) + 4
        font_renderer = pygame.font.Font(font, 12)
        for score in self.scores:
            self.scores_surfaces.append(
                font_renderer.render(
                    score.name + '.' * (max_width - self.score_width(score)) + str(score.score),
                    True,
                    NOT_SO_BLACK
                )
            )

        # Make the back option
        self.back_options.init(font, 15, True, NOT_SO_BLACK)

        # Load all sounds
        self.select_sound = Sound(resources.get_sound('menu_select.wav'))
Example #14
0
    def show(self):
        # Start the music
        pygame.mixer.music.load(resources.get_music('whatislove.ogg'))
        pygame.mixer.music.play(-1)

        # Get font name
        font = resources.get_font('prstartcustom.otf')

        # Make Hi-score and rights
        font_renderer = pygame.font.Font(font, 12)
        self.hiscore_label_surface = font_renderer.render('Hi-score', True, NOT_SO_BLACK)
        self.hiscore_surface = font_renderer.render(self.hiscore, True, NOT_SO_BLACK)
        self.rights_surface = font_renderer.render(self.rights, True, NOT_SO_BLACK)

        # Make title
        font_renderer = pygame.font.Font(font, 36)
        self.title_surface = font_renderer.render(GAME_TITLE, False, NOT_SO_BLACK)

        # Make all options and change to the main menu
        self.play_menu_options.init(font, 15, True, NOT_SO_BLACK)
        self.main_menu_options.init(font, 15, True, NOT_SO_BLACK)
        self.change_menu_options(self.main_menu_options)

        # Load all sounds
        self.select_sound = Sound(resources.get_sound('menu_select.wav'))
Example #15
0
class PauseState(GameState):
    CONTINUE_OPTION = 0
    RESTART_OPTION = 1
    EXIT_OPTION = 2

    def __init__(self, game, restart_state):
        super(PauseState, self).__init__(game)
        self.listen_keys = (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN, pygame.K_RETURN)

        self.restart_state = restart_state
        self.options = VerticalMenuOptions(
            ['Continue', 'Restart', 'Exit'],
            self.on_click,
            self.on_change,
        )

        self.select_sound = None

    def show(self):
        # Initialize options
        font = resources.get_font('prstartcustom.otf')
        self.options.init(font, 15, True, MORE_WHITE)

        # Initialize sounds
        self.select_sound = Sound(resources.get_sound('menu_select.wav'))

    def update(self, delta):
        self.options.update(self.input)

    def render(self, canvas):
        canvas.fill(NOT_SO_BLACK)
        self.options.render(canvas, GAME_WIDTH / 2, GAME_HEIGHT / 2 - self.options.get_height() / 2)

    def on_click(self, option):
        self.select_sound.play()
        if option == PauseState.CONTINUE_OPTION:
            self.state_manager.pop_overlay()
        elif option == PauseState.RESTART_OPTION:
            self.state_manager.set_state(self.restart_state)
        elif option == PauseState.EXIT_OPTION:
            self.state_manager.set_state(MenuState(self.game))

    def on_change(self, old_option, new_option):
        self.select_sound.play()

    def dispose(self):
        pass
 def __init__(self, serial_port, data_folder):
     self.lightning = SocketControl(serial_port)
     self._data_folder = data_folder
     self._rain = Sound("%s/rain.wav" % data_folder)
     self._thunder = 0
     self._last = 0
     self.lightning.set_B(ON)
     self.lightning.send()
Example #17
0
 def play_bgm(self, path, stream=False):
     self.stop_current_channel()
     if stream:
         music.load(path)
         music.play(-1)
     else:
         self.current_channel = Sound(path).play(-1)
     self.set_volume()
Example #18
0
    def setup(self, all_sprites):
        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"),
                        layer=0)

        all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), 
                        layer=0)        

        all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2),
                        layer=0)

        all_sprites.add(LcarsText(colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5),
                        layer=1)

        all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5),
                        layer=1)
        
        #all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5),layer=1)


        all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 130), "1", self.num_1), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 130), "2", self.num_2), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 270), "3", self.num_3), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 270), "4", self.num_4), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 410), "5", self.num_5), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 410), "6", self.num_6), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 550), "7", self.num_7), layer=2)
        all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 550), "8", self.num_8), layer=2)

        self.layer1 = all_sprites.get_sprites_from_layer(1)
        self.layer2 = all_sprites.get_sprites_from_layer(2)

        # sounds
        Sound("assets/audio/panel/215.wav").play()
        self.sound_granted = Sound("assets/audio/accessing.wav")
        self.sound_beep1 = Sound("assets/audio/panel/201.wav")
        self.sound_denied = Sound("assets/audio/access_denied.wav")
        self.sound_deny1 = Sound("assets/audio/deny_1.wav")
        self.sound_deny2 = Sound("assets/audio/deny_2.wav")

        ############
        # SET PIN CODE WITH THIS VARIABLE
        ############
        self.pin = 1234
        ############
        self.reset()
Example #19
0
    def __init__(self,
                 obj_file,
                 gravity,
                 maximum_speed,
                 maximum_acceleration,
                 maximum_roll_rate,
                 controls,
                 blaster_list,
                 blaster_color):

        self.gravity=gravity
        
        self.maximum_speed=maximum_speed
        self.maximum_acceleration=maximum_acceleration
        self.maximum_roll_rate=maximum_roll_rate
        
        self.controls=controls

        self.blaster_list=blaster_list
        
        self.blaster_color=blaster_color
        
        self.angle=0.0

        self.model=OBJ(config.basedir+"/assets", obj_file)

        self.position=Vector2D(0.0,0.0)
        self.velocity=Vector2D(0.0,0.0)

        self.bounding_box=BoundingPolygon( (Vector2D(-1.0, 1.0),
                                            Vector2D(1.0, 1.0),
                                            Vector2D(1.0, -1.0),
                                            Vector2D(0.0, -2.0),
                                            Vector2D(-1.0, -1.0)) )

        self.weight=1.0

        self.beam=Beam()
        self.plume=Plume()

        self.blaster_sound=Sound(config.basedir+"/assets/Laser_Shoot_2.wav")
        self.engine_sound=Sound(config.basedir+"/assets/engine.wav")
        self.engine_sound.set_volume(0.075)

        self.fire_counter=3
    def __init__(self, note=None, frequency=440, volume=0.1):
        # Notes must be in the format A[♯,♭,♮][octave number], if the octave is
        # left out then it will be centered around C5.

        # If note is a tuple then map the calls to parse_note, etc.
        if note is not None:
            if type(note) in [list, tuple]:
                note = map(Note.parse_note, note)
                frequency = [Note.notes[n] for n in note]
                sound_buffer = Note.build_chord(frequency)
            else:
                note = Note.parse_note(note)
                frequency = Note.notes[note]
                sound_buffer = Note.build_samples(frequency)

        self.note = note
        self.frequency = frequency
        Sound.__init__(self, buffer=sound_buffer)
        self.set_volume(volume)
Example #21
0
class LcarsElbow(LcarsWidget):
    """The LCARS corner elbow - not currently used"""
    
    #STYLE_BOTTOM_LEFT = 0
    #STYLE_TOP_LEFT = 1
    #STYLE_BOTTOM_RIGHT = 2
    #STYLE_TOP_RIGHT = 3
    
    def __init__(self, colour, pos, text, handler=None):
        self.handler = handler
        image = pygame.image.load("assets/elbow.png").convert()
        size = (image.get_rect().width, image.get_rect().height)
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                   (image.get_rect().width - 219,
                    image.get_rect().height - textImage.get_rect().height - 35))

        self.image = image
        self.colour = colour
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")

    def handleEvent(self, event, clock):
        handled = False
        
        if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)):
            self.applyColour(colours.WHITE)
            self.highlighted = True
            self.beep.play()
            handled = True

        if (event.type == MOUSEBUTTONUP and self.highlighted):
            self.applyColour(self.colour)
            if self.handler:
                self.handler(self, event, clock)
                handled = True
            
        LcarsWidget.handleEvent(self, event, clock)
        return handled
Example #22
0
    def __init__(self):
        try:
            import pygame.mixer
            from pygame.mixer import Sound
        except RuntimeError:
            print("Unable to import pygame mixer sound")
            raise Exception("Unable to import pygame mixer sound")

        self.soundfile = "launch_bass_boost_long.wav"
        self.mixer = pygame.mixer.init() #instance of pygame
        self.bass = Sound(self.soundfile)
 def devil(self):
     self.lightning.set_A(ON)
     self.lightning.set_C(ON)
     self.lightning.send()
     poodle = Sound("%s/poodle.wav" % (self._data_folder))
     poodle.play()
     time.sleep(0.3)
     self.lightning.set_A(OFF)
     self.lightning.send()
     time.sleep(0.7)
     for i in range(10):
         wait = random.randint(0, 3)
         while self._last == wait:
             wait = random.randint(0, 3)
         print "devil intensity:", wait
         self._last = wait
         thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait))
         thunder.play()
         if wait < 2:
             off_for = 0.05 + random.random() * 0.3
             print "flicker for", off_for
             self.lightning.set_B(OFF)
             self.lightning.send()
             time.sleep(off_for)
             self.lightning.set_B(ON)
             self.lightning.send()
         time.sleep(2)
     self.lightning.set_C(OFF)
     self.lightning.send()
     time.sleep(1)
     self.lightning.set_B(ON)
     self.lightning.send()
    def thunder(self, inc):
        wait = random.randint(0, 2+inc)

        while (self._last == wait):
            wait = random.randint(0, 2+inc)

        self._last = wait
        print "intensity:", wait
        thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait))
        if wait < 6:
            self.lightning.set_C(ON)
            self.lightning.send()
            time.sleep(random.uniform(0.5, 1.5))
            self.lightning.set_C(OFF)
            self.lightning.send()
            time.sleep(wait)

        if wait < 6:
            self.lightning.set_B(OFF)
            self.lightning.send()
        thunder.play()
        if wait < 6:
            time.sleep(0.3)
            self.lightning.set_B(ON)
            self.lightning.send()
        time.sleep(thunder.get_length()-0.3)
        thunder.fadeout(200)
        time.sleep(wait)
Example #25
0
    def show(self):
        # Start the music
        pygame.mixer.music.load(resources.get_music('mortalkombat.ogg'))
        pygame.mixer.music.play(-1)

        self.font = resources.get_font('prstartcustom.otf')
        self.font_renderer = pygame.font.Font(self.font, 12)

        # Player 1 Text
        self.player1_lives_label_surface = self.font_renderer.render('Lives: ', True, NOT_SO_BLACK)
        self.player1_lives_surface = self.font_renderer.render(str(self.player1.lives), True, NOT_SO_BLACK)
        self.player1_charge_label_surface = self.font_renderer.render('Charge: ', True, NOT_SO_BLACK)
        self.player1_charge_surface = self.font_renderer.render(str(self.player1.pad.charge), True, NOT_SO_BLACK)

        # Player 2 Text
        self.player2_lives_label_surface = self.font_renderer.render('Lives: ', True, NOT_SO_BLACK)
        self.player2_lives_surface = self.font_renderer.render(str(self.player2.lives), True, NOT_SO_BLACK)
        self.player2_charge_label_surface = self.font_renderer.render('Charge: ', True, NOT_SO_BLACK)
        self.player2_charge_surface = self.font_renderer.render(str(self.player2.pad.charge), True, NOT_SO_BLACK)

        # Initialize the sounds
        self.wall_hit_sound = Sound(resources.get_sound('on_wall_hit.wav'))
        self.pad_hit_sound = Sound(resources.get_sound('on_pad_hit.wav'))
        self.powerup_sound = Sound(resources.get_sound('powerup.wav'))
Example #26
0
    def __init__(self, colour, pos, text, handler=None):
        self.handler = handler
        image = pygame.image.load("assets/button.png").convert()
        size = (image.get_rect().width, image.get_rect().height)
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                   (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))

        self.image = image
        self.colour = colour
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")
Example #27
0
    def setup(self, all_sprites):

        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1.png"),
                        layer=0)
        
        # panel text
        all_sprites.add(LcarsText(colours.BLACK, (11, 75), "MOSF"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "LONG RANGE PROBE", 2.5),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (54, 667), "192 168 0 3"),
                        layer=1)

        # date display
        self.stardate = LcarsText(colours.BLACK, (444, 506), "", 1)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # permanent buttons        
        all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler),
                        layer=1)
        all_sprites.add(LcarsBlockSmall(colours.ORANGE, (211, 16), "ABOUT", self.aboutHandler),
                        layer=1)
        all_sprites.add(LcarsBlockLarge(colours.BLUE, (145, 16), "DEMO", self.demoHandler),
                        layer=1)
        all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler),
                        layer=1)
        all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN"),
                        layer=1)
        
        # Sounds
        self.beep1 = Sound("assets/audio/panel/201.wav")
        #Sound("assets/audio/panel/220.wav").play()

        #-----Screens-----#

        
        # Main Screen
        all_sprites.add(LcarsText(colours.WHITE, (265, 458), "WELCOME", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1.5),
                        layer=3)
        self.info_text = all_sprites.get_sprites_from_layer(3)
Example #28
0
    def __init__(self):
        mixer.init(frequency=44100, size=-16, channels=4, buffer=128)
        self._background_s = Sound(os.path.join("res", "background.ogg"))
        self._background_s.set_volume(0.8)
        self._grav_fxs_s = [
            Sound(os.path.join("res", "grav1.wav")),
            Sound(os.path.join("res", "grav2.wav")),
            Sound(os.path.join("res", "grav3.wav")),
        ]
        for s in self._grav_fxs_s:
            s.set_volume(0.1)
        self._death_s = Sound(os.path.join("res", "death.wav"))

        self._background_channel = mixer.Channel(0)
        self._fx_channel = mixer.Channel(1)
        self.effect_playing = False
        self.bg_playing = False
Example #29
0
    logger.LogError(
        "motorFunctions.py: Cannot import the RPi module, install it with pip or this may not be a Raspberry Pi"
    )

DEBUG = False

frequencyHertz = 50  # PWm Frequency
msPerCycle = 1000 / frequencyHertz  # MilliSeconds per Frequency Cycle

###### Create default joint positions
leftPosition_RS = 0.85
rightPosition_RS = 2.25
middlePosition_RS = (rightPosition_RS - leftPosition_RS) / 2 + leftPosition_RS

pygame.mixer.init()
ack = Sound("audio/ack.wav")
limit = Sound("audio/limit.wav")


def executeMovement(pin, pos):
    try:
        # CREATE and Clean up a GPIO object with each call - until further notice
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(pin, GPIO.OUT)
        pwm = GPIO.PWM(pin, 50)
        pwm.start(0)
        pwm.ChangeDutyCycle(pos)
        time.sleep(.85)
        pwm.stop()
        GPIO.cleanup()
    except Exception as e:
Example #30
0
 def __init__(self, source, ui_config):
     self._ui_config = ui_config
     if ui_config.sound_on:
         self.sound = Sound(source)
Example #31
0
 def __init__(self, source):
     if config.SOUND:
         self.sound = OldSound(source)
Example #32
0
#=======================================================================
pygame.init()

tela = pygame.display.set_mode((900, 706), 0, 0)
pygame.display.set_caption('Alunimon')
relogio = pygame.time.Clock()

mapa = pygame.image.load("map.jpg").convert()
sala = pygame.image.load("sala.jpg").convert()
batalha = pygame.image.load("Waterloo.jpg").convert()
player = Player("character.png", 415, 419)
all_sprite_list = pygame.sprite.Group()
frame2 = pygame.image.load("frame 3.jpg")
frame3 = pygame.image.load('frame 2.jpg')
musica_inicial = Sound("Ameno.ogg")
musica_história = Sound('O_fortuna.ogg')
menu_inicial = pygame.image.load('menu_inicial.jpeg')
historia = pygame.image.load('historia_inicial.jpg')
frame5 = pygame.image.load('Frame 5.jpg')
selecao = pygame.image.load('Slide1.jpg')
fernando = pygame.image.load('Slide2.jpg')
ayres = pygame.image.load('Slide3.jpg')
bobrow = pygame.image.load('Slide4.jpg')
victor = pygame.image.load('Slide5.jpg')
pelican = pygame.image.load('Slide6.jpg')
daniel = pygame.image.load('Slide7.jpg')
musica_selecao = Sound('Vingadores.ogg')
frame6 = pygame.image.load('Slide8.jpg')
comandos = pygame.image.load('Comandos.jpg')
hospital = pygame.image.load('Mercado.jpg')
Example #33
0
class ScreenTemplate(LcarsScreen):
    def setup(self, all_sprites):
        # Load BG image
        all_sprites.add(LcarsBackgroundImage("assets/lcars_bg.png"), layer=0)

        # Time/Date display
        self.stardate = LcarsText(colours.BLUE, (12, 380), "", 1.5)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # Static text
        all_sprites.add(LcarsText(colours.BLACK, (8, 40), "LCARS 1123"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "SECTION NAME", 2),
                        layer=1)

        # Interfaces
        all_sprites.add(LcarsButton(colours.RED_BROWN, "btn", (6, 660), "MAIN",
                                    self.logoutHandler),
                        layer=2)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (145, 15),
                                    "BUTTON 1", self.nullfunction),
                        layer=2)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (200, 15),
                                    "BUTTON 2", self.nullfunction),
                        layer=2)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (255, 15),
                                    "BUTTON 3", self.nullfunction),
                        layer=2)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (310, 15),
                                    "BUTTON 4", self.nullfunction),
                        layer=2)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (365, 15), "",
                                    self.nullfunction),
                        layer=2)

        # Info text
        all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TEXT GOES HERE",
                                  1.5),
                        layer=3)
        self.info_text = all_sprites.get_sprites_from_layer(3)

        # SFX
        self.beep1 = Sound("assets/audio/panel/201.wav")
        Sound("assets/audio/hail_2.wav").play()

    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 1000:
            self.stardate.setText("{}".format(
                datetime.now().strftime("%a %b %d, %Y - %X")))
            self.lastClockUpdate = pygame.time.get_ticks()
        LcarsScreen.update(self, screenSurface, fpsClock)

    def handleEvents(self, event, fpsClock):
        LcarsScreen.handleEvents(self, event, fpsClock)

        if event.type == pygame.MOUSEBUTTONDOWN:
            self.beep1.play()

        if event.type == pygame.MOUSEBUTTONUP:
            return False

    def hideInfoText(self):
        if self.info_text[0].visible:
            for sprite in self.info_text:
                sprite.visible = False

    def nullfunction(self, item, event, clock):
        print("I am a fish.")

    def logoutHandler(self, item, event, clock):
        from screens.main import ScreenMain
        self.loadScreen(ScreenMain())
Example #34
0
def play_sound(filename, volume=0.75):
    global SOUND_PATH
    sound = Sound(SOUND_PATH + filename)
    sound.set_volume(volume)
    sound.play()
Example #35
0
from gpiozero import Button
import pygame.mixer
from pygame.mixer import Sound
from signal import pause

pygame.mixer.init()

button_sounds = {
    Button(2): Sound("samples/drum_tom_mid_hard.wav"),
    Button(3): Sound("samples/drum_cymbal_open.wav"),
}

for button, sound in button_sounds.items():
    button.when_pressed = sound.play

pause()
Example #36
0
    def setup(self, all_sprites):
        # Load standard LCARS BG image
        all_sprites.add(LcarsBackgroundImage("assets/lcars_bg.png"), layer=0)

        # Setup time/date display
        self.stardate = LcarsText(colours.BLUE, (12, 380), "", 1.5)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # Static text
        all_sprites.add(LcarsText(colours.BLACK, (8, 40), "LCARS 1123"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "MAIN MENU", 2),
                        layer=1)

        # Buttons
        all_sprites.add(LcarsButton(colours.RED_BROWN, "btn", (6, 660),
                                    "LOGOUT", self.load_idle),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (145, 15), "ENVIRO",
                                    self.load_enviro),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (200, 15), "NETWORK",
                                    self.load_network),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (255, 15), "POWER",
                                    self.load_power),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (310, 15),
                                    "OPERATIONS", self.load_auth),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (365, 15), "",
                                    self.load_template),
                        layer=4)

        # Load data from file
        returnpayload = read_txt("/var/lib/lcars/alert")

        # First line in file is always going to be heading
        all_sprites.add(LcarsText(colours.ORANGE, (137, 133), returnpayload[0],
                                  1.8),
                        layer=3)

        # Loop through results starting at second element
        index = 1
        ypos = 190
        while index < len(returnpayload):
            all_sprites.add(LcarsText(colours.BLUE, (ypos, 150),
                                      returnpayload[index], 1.5),
                            layer=3)
            # Bump index and vertical pos
            index += 1
            ypos += 50

        # Rotating Deep Space 9
        all_sprites.add(LcarsGifImage("assets/animated/ds9_3d.gif", (148, 475),
                                      100),
                        layer=1)

        self.beep1 = Sound("assets/audio/panel/201.wav")
        Sound("assets/audio/panel/220.wav").play()
Example #37
0
import pygame
from pygame.mixer import Sound
from signal import pause
import os

pygame.init()

btn1 = Button("GPIO18")
btn2 = Button("GPIO23")
btn3 = Button("GPIO25")
btn4 = Button("GPIO16")

led4 = LED("GPIO4")

blip = Sound(
    "/home/pi/Raspberry-Pi-with-Python3/music_files_from_sonic_pi/samples/elec_blip.wav"
)
bass = Sound(
    "/home/pi/Raspberry-Pi-with-Python3/music_files_from_sonic_pi/samples/glitch_bass_g.wav"
)
snare = Sound(
    "/home/pi/Raspberry-Pi-with-Python3/music_files_from_sonic_pi/samples/elec_snare.wav"
)
glitch = Sound(
    "/home/pi/Raspberry-Pi-with-Python3/music_files_from_sonic_pi/samples/glitch_perc5.wav"
)


def activate_blip():
    print("Blip and light!")
    led4.on()
Example #38
0
    def preload():
        # Preload images
        Resources.mouse_pointer = pyglet.resource.image(
            "images/ui/mouse-pointer-0.png")

        buildings_img = pyglet.resource.image(
            "images/board/colony-buildings-32.png")
        buildings_grid = pyglet.image.ImageGrid(
            buildings_img,
            columns=(buildings_img.width // board.Board.TILE_SIZE),
            rows=(buildings_img.height // board.Board.TILE_SIZE))

        Resources.buildings_tex = pyglet.image.TextureGrid(buildings_grid)
        Resources.ground_img = pyglet.resource.image(
            "images/board/ground-dark.png")

        Resources.action_indicator_img = pyglet.resource.animation(
            "images/ui/action-indicator.gif")

        Resources.player_indicator_img = pyglet.resource.image(
            "images/ui/player-indicator.png")
        Resources.friendly_indicator_img = pyglet.resource.image(
            "images/ui/friendly-indicator.png")
        Resources.enemy_indicator_img = pyglet.resource.image(
            "images/ui/enemy-indicator.png")
        Resources.move_indicator_img = pyglet.resource.image(
            "images/ui/move-indicator.png")

        Resources.armor_pip_img = pyglet.resource.image(
            "images/ui/armor-pip.png")
        Resources.structure_pip_img = pyglet.resource.image(
            "images/ui/structure-pip.png")
        Resources.empty_pip_img = pyglet.resource.image(
            "images/ui/empty-pip.png")
        Resources.heat_pip_img = pyglet.resource.image(
            "images/ui/heat-pip.png")

        Resources.armor_icon_img = pyglet.resource.image(
            "images/ui/armor-icon.png")
        Resources.structure_icon_img = pyglet.resource.image(
            "images/ui/structure-icon.png")
        Resources.heat_icon_img = pyglet.resource.image(
            "images/ui/heat-icon.png")

        Resources.ballistic_img = pyglet.resource.image(
            "images/weapons/ballistic.png")
        Resources.buckshot_img = pyglet.resource.image(
            "images/weapons/buckshot.png")
        Resources.gauss_img = pyglet.resource.image("images/weapons/gauss.png")
        Resources.missile_img = pyglet.resource.image(
            "images/weapons/missile.png")
        Resources.explosion01 = pyglet.resource.image(
            'images/weapons/explosion_01.png')
        Resources.explosion07 = pyglet.resource.image(
            'images/weapons/explosion_07.png')
        Resources.flash03 = pyglet.resource.image(
            'images/weapons/flash_03.png')

        # Preload sound effects
        Resources.cannon_sound = Sound(
            pyglet.resource.file("sounds/autocannon-shot.ogg"))
        Resources.explosion_sound = Sound(
            pyglet.resource.file("sounds/explosion-single.ogg"))
        Resources.explosion_multiple_sound = Sound(
            pyglet.resource.file("sounds/explosion-multiple.ogg"))

        Resources.flamer_sound = Sound(
            pyglet.resource.file("sounds/flamer-shot.ogg"))
        Resources.gauss_sound = Sound(
            pyglet.resource.file("sounds/gauss-shot.ogg"))
        Resources.las_sound = Sound(
            pyglet.resource.file("sounds/laser-blast-long.ogg"))
        Resources.machinegun_sound = Sound(
            pyglet.resource.file("sounds/machine-gun.ogg"))
        Resources.ppc_sound = Sound(
            pyglet.resource.file("sounds/ppc-shot.ogg"))

        Resources.missile_sounds = []
        for i in range(8):
            Resources.missile_sounds.append(
                Sound(pyglet.resource.file("sounds/missile-shot-%s.ogg" % i)))

        Resources.stomp_sounds = []
        for i in range(4):
            Resources.stomp_sounds.append(
                Sound(pyglet.resource.file("sounds/mech-stomp-%s.ogg" % i)))

        # preload font
        pyglet.font.add_file(pyglet.resource.file('images/ui/Convoy.ttf'))
        pyglet.font.add_file(
            pyglet.resource.file('images/ui/TranscendsGames.otf'))
Example #39
0
class ScreenMain(LcarsScreen):
    def setup(self, all_sprites):
        # Load standard LCARS BG image
        all_sprites.add(LcarsBackgroundImage("assets/lcars_bg.png"), layer=0)

        # Setup time/date display
        self.stardate = LcarsText(colours.BLUE, (12, 380), "", 1.5)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # Static text
        all_sprites.add(LcarsText(colours.BLACK, (8, 40), "LCARS 1123"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "MAIN MENU", 2),
                        layer=1)

        # Buttons
        all_sprites.add(LcarsButton(colours.RED_BROWN, "btn", (6, 660),
                                    "LOGOUT", self.load_idle),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (145, 15), "ENVIRO",
                                    self.load_enviro),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (200, 15), "NETWORK",
                                    self.load_network),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (255, 15), "POWER",
                                    self.load_power),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (310, 15),
                                    "OPERATIONS", self.load_auth),
                        layer=4)
        all_sprites.add(LcarsButton(randomcolor(), "nav", (365, 15), "",
                                    self.load_template),
                        layer=4)

        # Load data from file
        returnpayload = read_txt("/var/lib/lcars/alert")

        # First line in file is always going to be heading
        all_sprites.add(LcarsText(colours.ORANGE, (137, 133), returnpayload[0],
                                  1.8),
                        layer=3)

        # Loop through results starting at second element
        index = 1
        ypos = 190
        while index < len(returnpayload):
            all_sprites.add(LcarsText(colours.BLUE, (ypos, 150),
                                      returnpayload[index], 1.5),
                            layer=3)
            # Bump index and vertical pos
            index += 1
            ypos += 50

        # Rotating Deep Space 9
        all_sprites.add(LcarsGifImage("assets/animated/ds9_3d.gif", (148, 475),
                                      100),
                        layer=1)

        self.beep1 = Sound("assets/audio/panel/201.wav")
        Sound("assets/audio/panel/220.wav").play()

    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 1000:
            self.stardate.setText("{}".format(
                datetime.now().strftime("%a %b %d, %Y - %X")))
            self.lastClockUpdate = pygame.time.get_ticks()
        LcarsScreen.update(self, screenSurface, fpsClock)

    def handleEvents(self, event, fpsClock):
        LcarsScreen.handleEvents(self, event, fpsClock)

        if event.type == pygame.MOUSEBUTTONDOWN:
            self.beep1.play()

        if event.type == pygame.MOUSEBUTTONUP:
            return False

    def nullfunction(self, item, event, clock):
        print("I am a fish.")

    def load_template(self, item, event, clock):
        from screens.template import ScreenTemplate
        self.loadScreen(ScreenTemplate())

#    def load_auth(self, item, event, clock):
#        from screens.authorize import ScreenAuthorize
#        self.loadScreen(ScreenAuthorize())

    def load_auth(self, item, event, clock):
        from screens.ops import ScreenOps
        self.loadScreen(ScreenOps())

    def load_power(self, item, event, clock):
        from screens.power import ScreenPower
        self.loadScreen(ScreenPower())

    def load_idle(self, item, event, clock):
        from screens.idle import ScreenIdle
        self.loadScreen(ScreenIdle())

    def load_network(self, item, event, clock):
        from screens.network import ScreenNetwork
        self.loadScreen(ScreenNetwork())

    def load_enviro(self, item, event, clock):
        from screens.enviro import ScreenEnviro
        self.loadScreen(ScreenEnviro())
Example #40
0
__doc__ = 'Brutal Maze module for shared constants'

from string import ascii_lowercase

from pkg_resources import resource_filename as pkg_file
import pygame
from pygame.mixer import Sound

SETTINGS = pkg_file('brutalmaze', 'settings.ini')
ICON = pygame.image.load(pkg_file('brutalmaze', 'icon.png'))
MUSIC = pkg_file('brutalmaze', 'soundfx/music.ogg')
NOISE = pkg_file('brutalmaze', 'soundfx/noise.ogg')

mixer = pygame.mixer.get_init()
if mixer is None: pygame.mixer.init(frequency=44100)
SFX_SPAWN = Sound(pkg_file('brutalmaze', 'soundfx/spawn.ogg'))
SFX_SLASH_ENEMY = Sound(pkg_file('brutalmaze', 'soundfx/slash-enemy.ogg'))
SFX_SLASH_HERO = Sound(pkg_file('brutalmaze', 'soundfx/slash-hero.ogg'))
SFX_SHOT_ENEMY = Sound(pkg_file('brutalmaze', 'soundfx/shot-enemy.ogg'))
SFX_SHOT_HERO = Sound(pkg_file('brutalmaze', 'soundfx/shot-hero.ogg'))
SFX_MISSED = Sound(pkg_file('brutalmaze', 'soundfx/missed.ogg'))
SFX_HEART = Sound(pkg_file('brutalmaze', 'soundfx/heart.ogg'))
SFX_LOSE = Sound(pkg_file('brutalmaze', 'soundfx/lose.ogg'))
if mixer is None: pygame.mixer.quit()

SQRT2 = 2**0.5
INIT_SCORE = 2
ROAD_WIDTH = 3  # grids
WALL_WIDTH = 4  # grids
CELL_WIDTH = WALL_WIDTH + ROAD_WIDTH * 2  # grids
CELL_NODES = ROAD_WIDTH, ROAD_WIDTH + WALL_WIDTH, 0
 def __init__(self, frequency, volume=.1):
     self.frequency = frequency
     Sound.__init__(self, self.build_samples())
     self.set_volume(volume)
Example #42
0
from pygame.draw import rect as draw_rect
from pygame import Surface
from pygame.transform import scale as scale_image
from pygame import MOUSEBUTTONDOWN
from pygame.font import Font
from pygame.mixer import Sound
button_press_sound = Sound("button_pressed.wav")
class Cell():
  def __init__(self, x, y, width, height, block_image):
    self.x = x
    self.y = y
    self.activated = False
    self.small_block_image = scale_image(block_image, (20, 20))
    self.image = Surface((width, height))
    self.image.fill((139,69,19))
    self.image.set_alpha(60)
  def update(self, event, cells):
    if event.type == MOUSEBUTTONDOWN:
      if event.button == 1:
        if event.pos[0] in range(self.x, self.x + self.image.get_width()) and event.pos[1] in range(self.y, self.y + self.image.get_height()):
          button_press_sound.play()
          self.activated = True
          for cell in cells:
            if cell != self:
              cell.activated = False
  def draw(self, window):
    window.blit(self.image, (self.x, self.y))
    if self.activated:
      draw_rect(window, (0, 0, 0), (self.x, self.y, self.image.get_width(), self.image.get_height()), 2)
    else:
      draw_rect(window, (150, 150, 150), (self.x, self.y, self.image.get_width(), self.image.get_height()), 2)
Example #43
0
def load_sound(name):
    path = f"assets/sounds/{name}.wav"
    return Sound(path)
Example #44
0
class Game(Scene):
    '''
    This class represents the main game scene where the player will
    face multiples asteroids and will attempt to stay alive
    '''
    #
    # Base Sprites
    #
    tiny_meteors = (
        'meteorBrown_tiny1.png',
        'meteorBrown_tiny2.png',
        'meteorGrey_tiny1.png',
        'meteorGrey_tiny2.png',
    )
    small_meteors = (
        'meteorBrown_small1.png',
        'meteorBrown_small2.png',
        'meteorGrey_small1.png',
        'meteorGrey_small2.png',
    )
    med_meteors = (
        'meteorBrown_med1.png',
        'meteorBrown_med2.png',
        'meteorGrey_med1.png',
        'meteorGrey_med2.png',
    )
    big_meteors = (
        'meteorBrown_big1.png',
        'meteorBrown_big2.png',
        'meteorBrown_big3.png',
        'meteorBrown_big4.png',
        'meteorGrey_big1.png',
        'meteorGrey_big2.png',
        'meteorGrey_big3.png',
        'meteorGrey_big4.png',
    )

    #
    # Difficulty System
    #
    phase = 0

    def update_phase(self):
        '''
        This method update the phase of the game base on the score of
        the player
        '''
        score = self.ui.get_score()
        if score < 40:
            if self.phase < 1:
                self.phase = 1
                set_timer(events.ADD_ENEMY, 300)
        elif score < 60:
            if self.phase < 2:
                self.phase = 2
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 200)
        elif score < 100:
            if self.phase < 3:
                self.phase = 3
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 250)
        elif score < 120:
            if self.phase < 4:
                self.phase = 4
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 150)
        elif score < 160:
            if self.phase < 5:
                self.phase = 5
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 200)
        elif score < 180:
            if self.phase < 6:
                self.phase = 6
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 100)
        elif score < 220:
            if self.phase < 7:
                self.phase = 7
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 150)
        elif score < 240:
            if self.phase < 8:
                self.phase = 8
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 50)
        else:
            if self.phase < 9:
                self.phase = 9
                self.bg.increase_frame_move()
                set_timer(events.ADD_ENEMY, 100)

    def select_enemy(self):
        '''
        This method set the probabilities of a certain sprite to be choosen
        as enemy based on the phase of the game, at higher phases unlock
        more sprites and more velocity
        '''
        if self.phase < 3:
            # p_tiny = 100% - 50%
            p_tiny = 1 - self.ui.get_score() * .0083
            v_tiny = random.randint(5, 5 + int(self.ui.get_score() * 0.09))
            # p_small = 0% - 50%
            p_small = 1
            v_small = random.randint(5, 5 + int(self.ui.get_score() * 0.09))
        elif self.phase < 4:
            n_score = self.ui.get_score() - 60
            # p_tiny = 50% - 30%
            p_tiny = .5 - n_score * .0033
            v_tiny = random.randint(5, 10 + int(n_score * .09))
            # p_small = 50% - 60%
            p_small = 1 - n_score * .0016
            v_small = random.randint(5, 10 + int(n_score * .09))
            # p_med = 0% - 10%
            p_med = 1
            v_med = random.randint(3, 5 + int(n_score * .09))
        elif self.phase < 6:
            n_score = self.ui.get_score() - 120
            # p_tiny = 30% - 20%
            p_tiny = .3 - n_score * .0016
            v_tiny = random.randint(5, 15)
            # p_small = 60% - 50%
            p_small = .9 - n_score * .0033
            v_small = random.randint(5, 15)
            # p_med = 10% - 20%
            p_med = 1 - n_score * .0016
            v_med = random.randint(3, 10)
            # p_big = 0% - 10%
            p_big = 1
            v_big = random.randint(1, 2 + int(n_score * .09))
        else:
            # p_tiny = 20%
            p_tiny = .2
            v_tiny = random.randint(5, 15)
            # p_small = 50% - 40%
            p_small = .6
            v_small = random.randint(5, 15)
            # p_med = 20% - 25%
            p_med = .85
            v_med = random.randint(3, 10)
            # p_big = 10% - 15%
            p_big = 1
            v_big = random.randint(1, 7)

        p = random.random()
        if p < p_tiny:
            sprite = random.choice(self.tiny_meteors)
            speed = v_tiny
        elif p < p_small:
            sprite = random.choice(self.small_meteors)
            speed = v_small
        elif p < p_med:
            sprite = random.choice(self.med_meteors)
            speed = v_med
        elif p < p_big:
            sprite = random.choice(self.big_meteors)
            speed = v_big

        return f'meteors/{sprite}', speed

    #
    # Enemy System
    #
    def add_enemy(self):
        '''
        This method generates an enemy based on select enemy method of
        the difficulty system
        '''
        sprite, speed = self.select_enemy()
        enemy = Enemy(sprite)
        enemy.start(speed)
        enemy.set_pos(
            random.randint(
                self.screen_w + 20,
                self.screen_w + 100
            ),
            random.randint(0, self.screen_h)
        )
        enemy.update_box_collider()
        self.render_group.add(enemy, layer=ENEMY_LAYER)
        self.update_group.add(enemy)
        self.enemies.add(enemy)

    #
    # Player System
    #
    def player_collide(self, enemy: Enemy):
        '''
        This method handles the case when the player hits an enemy
        Will trigger the game over ui
        '''
        if self.player.lifes > 1:
            # Remove the ui so lifes can be redraw
            self.render_group.remove(*self.ui.get_objects())
            self.player.damage()
            enemy.kill()
            self.ui.decrease_player_lifes()
            self.render_group.add(
                *self.ui.get_objects(),
                layer=UI_LAYER,
            )

        else:
            self.player.kill()
            self.sound.fadeout(100)
            self.render_group.remove(*self.ui.get_objects())
            self.lose_sound.play()

            self.ui.start_game_over(self.cursor)
            self.cursor.add(
                self.event_group,
                self.update_group,
            )
            self.render_group.add(
                *self.ui.get_objects(),
                self.cursor,
                layer=UI_LAYER
            )

    #
    # Restart System
    #
    def restart(self):
        '''
        This method handles the restart option of the game over menu
        will restart all the environment variables and restart the
        journey
        '''
        # Delete old stuff
        self.cursor.clear()
        self.cursor.kill()
        for e in self.enemies.sprites():
            e.kill()
        self.render_group.remove(*self.ui.get_objects())

        # Set new stuff
        self.ui.start_score()
        self.phase = 0
        self.bg.start()
        self.ui.create_player_lifes()
        self.render_group.add(self.player, layer=PLAYER_LAYER)
        self.render_group.add(*self.ui.get_objects(), layer=UI_LAYER)
        self.update_group.add(self.player)

        # Start the music
        if SOUND:
            self.sound.play(loops=-1)

        # Set the player starting position
        self.player.set_start_position()

        # Refund player lifes
        self.player.reset_life()

    #
    # CORE
    #
    def clear(self):
        self.enemies.empty()
        self.phase = 0
        set_timer(events.ADD_ENEMY, 0)

    def start(self):
        # Sound Config
        self.sound = Sound(
            get_asset_path('sounds', 'bensound-game.ogg')
        )
        self.sound.set_volume(.2)
        if SOUND:
            self.sound.play(loops=-1)

        self.lose_sound = Sound(
            get_asset_path('sounds', 'sfx_lose.ogg')
        )

        # Game object creation
        self.bg = BackgroundParalax('blue.png')
        self.player = Player(
            'playerShip1_blue.png',
            rotation=-90,
            scale_factor=.5,
        )
        self.ui = GameUI()
        self.cursor = Cursor('playerLife1_blue.png', 'sfx_zap.ogg')

        # Start objects
        self.player.start()
        self.ui.start()
        self.bg.start()

        # Custom group creation
        self.enemies = Group()

        # Add objects to groups
        self.render_group.add(self.bg, layer=BACKGROUND_LAYER)
        self.render_group.add(self.player, layer=PLAYER_LAYER)
        self.render_group.add(*self.ui.get_objects(), layer=UI_LAYER)

        self.update_group.add(
            self.player,
            self.ui,
            self.bg,
        )

        # Set the player starting position
        self.player.set_start_position()

    def update(self):
        # Event handling
        for e in self.events:
            if e.type == events.ADD_ENEMY:
                self.add_enemy()

        if self.player.alive():
            # Phase handling
            self.update_phase()

            # Collision handling
            enemy: Enemy = spritecollideany(self.player, self.enemies, box_collide)
            if enemy:
                self.player_collide(enemy)
        else:
            if self.cursor.selected is not None:
                if self.cursor.selected == 0:
                    self.restart()
                elif self.cursor.selected == 1:
                    self.exit(1)
Example #45
0
class Sound(object):
    """
		todo is to wrap all the channel methods so they only work on the sound. This could happen either by checking if the sound is playing on the channel or possibly by calling methods on the sound itself.
		mixer documentation:
		https://www.pygame.org/docs/ref/mixer.html

		This class ads support for 3D positioning. Just pass the position of the sound in a tuple of (x,y) coordinates after the path of the file.
	"""
    def __init__(self, filename, position=None, single_channel=True):
        self.name = filename
        self.pos = position  # should be a tuple (x, y)
        self.channel = None
        self.paused = False
        self.playing = False
        self.stopped = False  # this is to tell a callback if the sound was stopped by a stop function or not.
        self.single_channel = single_channel
        self.callback = lambda e: None  # the callback is passed this object as an argument and is triggered at the end of the sound
        self._id = "sound-%s-%s" % (self.name, id(self))

        try:
            self.sound = Mixer_sound(filename)
        except:
            raise Exception("Unable to open file %r" % filename)

    def play(self, loops=0, maxtime=0, fade_ms=0):
        self.playing = True
        self.stopped = False
        if not self.channel or (
            (not self.single_channel or self.channel.get_sound() != self.sound)
                and self.channel.get_busy()):
            self.channel = find_channel() or self.channel
        self.channel.play(self.sound, loops, maxtime, fade_ms)
        if self.pos:
            playing_sounds.append(self)
            self.set_volume()
        event_queue.schedule(
            function=self.check_if_finished,
            repeats=-1,
            delay=0,
            name=self._id
        )  # this uses the channel.get_busy to figure out if the sound has finished playing.


#		event_queue.schedule(function=self.finish, repeats=1, delay=self.get_length()-0.09, name=self._id) # This does the same as above, but uses the length of the sound to schedule an end event. The problem with this is that if one pauses the sound, the event still runs. The pro is that the end event can be faster than the actual sound.

    def get_volume(self):
        return self.channel.get_volume()

    def move_pos(self, x=0, y=0):
        cx, cy = self.pos
        self.set_pos(cx + x, cy + y)
        return self.pos

    def set_pos(self, x, y):
        self.pos = (float(x), float(y))
        if (self.channel):
            self.channel.set_volume(*position.stereo(*self.pos))

    def get_pos(self):
        return self.pos

    def get_length(self):
        return self.sound.get_length()

    def toggle_pause(self):
        """This function can be called to pause and unpause a sound without the script needing to handle the check for paused and unpaused. If the sound is paused when this function is called, then the sound is unpaused and if the sound is playing when this function is called, then the sound is paused. It's very good for buttons to play and pause sounds."""
        if not self.channel or not self.playing:
            self.play()
        elif self.paused:
            self.unpause()
        else:
            self.pause()

    def unpause(self):
        if not self.channel: return False
        self.channel.unpause()
        self.paused = False

    def is_paused(self):
        return self.paused

    def pause(self):
        if not self.channel: return False
        self.channel.pause()
        self.paused = True

    def stop(self):
        """This stops the channel from playing."""
        event_queue.unschedule(self._id)
        if self in playing_sounds:
            playing_sounds.remove(self)
        self.playing = False
        self.paused = False
        self.stopped = True
        self.unpause()
        if self.channel:
            self.channel.stop()
        self.finish()

    def stop_sound(self):
        """This stops the sound object from playing rather than the channel"""
        self.sound.stop()
        self.unpaws()
        self.playing = False
        mixer_queue.remove(self.channel)
        if self in playing_sounds:
            playing_sounds.remove(self)

    def get_busy(self):
        """Returns if the channel is active. This is used for triggering the callback"""
        if self.channel:
            return self.channel.get_busy()
        return False

    def check_if_finished(self):
        """This runs every tick to see if the channel is done. if it is done, then it runs the finish method and removes itself from the event_queue."""
        if not self.get_busy():
            self.finish()
            event_queue.unschedule(self._id)

    def toggle_playing(self):
        if self.playing:
            self.stop()
        else:
            self.play()

    def set_volume(self, volume=1, right=None):
        """Sets the volume if there is a channel. If there is a position, then volume is adjusted to be that position. If no arguments are passed, then it will update the volume to be the current pos, or set volume back to 1."""
        if not self.channel:
            return 0
        if volume > 1:
            volume = 1
        elif volume <= 0:
            self.channel.set_volume(0)
            return 0
        if not self.pos and not right:
            self.channel.set_volume(volume)
        elif right:
            self.channel.set_volume(volume, right)
        else:
            x, y = self.pos
            if x == 0 and y == 0:
                self.channel.set_volume(volume)
                return 0
            self.channel.set_volume(*position.stereo(x / volume, y / volume))

    def finish(self):
        self.playing = False
        self.paused = False
        self.callback(self)
Example #46
0
    def setup(self, all_sprites):
        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1b.png"),
                        layer=0)
        
        # panel text
        all_sprites.add(LcarsText(colours.BLACK, (11, 52), "LCARS 105"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "HOME AUTOMATION", 2),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (183, 74), "LIGHTS"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (222, 57), "CAMERAS"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (372, 70), "ENERGY"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (444, 612), "192 168 0 3"),
                        layer=1)

        # info text
        all_sprites.add(LcarsText(colours.WHITE, (192, 174), "EVENT LOG:", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (244, 174), "2 ALARM ZONES TRIGGERED", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (286, 174), "14.3 kWh USED YESTERDAY", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (330, 174), "1.3 Tb DATA USED THIS MONTH", 1.5),
                        layer=3)
        self.info_text = all_sprites.get_sprites_from_layer(3)

        # date display
        self.stardate = LcarsText(colours.BLUE, (12, 380), "STAR DATE 2711.05 17:54:32", 1.5)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # buttons        
        all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.BEIGE, (107, 127), "SENSORS", self.sensorsHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.PURPLE, (107, 262), "GAUGES", self.gaugesHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.PEACH, (107, 398), "WEATHER", self.weatherHandler),
                        layer=4)

        # gadgets        
        all_sprites.add(LcarsGifImage("assets/gadgets/fwscan.gif", (277, 556), 100), layer=1)
        
        self.sensor_gadget = LcarsGifImage("assets/gadgets/lcars_anim2.gif", (235, 150), 100) 
        self.sensor_gadget.visible = False
        all_sprites.add(self.sensor_gadget, layer=2)

        self.dashboard = LcarsImage("assets/gadgets/dashboard.png", (187, 232))
        self.dashboard.visible = False
        all_sprites.add(self.dashboard, layer=2) 

        self.weather = LcarsImage("assets/weather.jpg", (188, 122))
        self.weather.visible = False
        all_sprites.add(self.weather, layer=2) 

        #all_sprites.add(LcarsMoveToMouse(colours.WHITE), layer=1)
        self.beep1 = Sound("assets/audio/panel/201.wav")
        Sound("assets/audio/panel/220.wav").play()
Example #47
0
def load_sound(name):
    path = f"C:/Users/ActionICT/PycharmProjects/Asteroids/assets/sounds/zapsplat_laser.mp3 "
    return Sound(path)
Example #48
0
 def __init__(self, frequency, volume=.1, sample_rate=44100):
     self.frequency = frequency
     self.sr = sample_rate
     Sound.__init__(self, self.build_samples())
     self.set_volume(volume)
Example #49
0
 def add_audio_source(self, name, path, preload=True):
     if preload:  # default is to preload
         sound_obj = Sound(path)
     else:
         sound_obj = None
     self.audio_sources[name] = [preload, path, sound_obj]
Example #50
0
import pygame.mixer
from pygame.mixer import Sound
from gpiozero import Button
from signal import pause

pygame.mixer.pre_init(48000, -16, 1, 4096)
pygame.mixer.init()

def pauseSound():
  pygame.mixer.pause()

button_sounds = {
    Button(14): Sound("/home/pi/sounds/1.wav").play,
    Button(15): Sound("/home/pi/sounds/2.wav").play,
    Button(18): Sound("/home/pi/sounds/3.wav").play,
    Button(23): Sound("/home/pi/sounds/4.wav").play,
    Button(24): Sound("/home/pi/sounds/5.wav").play,
    Button(3): pauseSound,
}

for button, sound in button_sounds.items():
    button.when_pressed = sound

pause()
Example #51
0
class ScreenMain(LcarsScreen):
    def setup(self, all_sprites):
        all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1b.png"),
                        layer=0)
        
        # panel text
        all_sprites.add(LcarsText(colours.BLACK, (11, 52), "LCARS 105"),
                        layer=1)
        all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "HOME AUTOMATION", 2),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (183, 74), "LIGHTS"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (222, 57), "CAMERAS"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (372, 70), "ENERGY"),
                        layer=1)
        all_sprites.add(LcarsText(colours.BLACK, (444, 612), "192 168 0 3"),
                        layer=1)

        # info text
        all_sprites.add(LcarsText(colours.WHITE, (192, 174), "EVENT LOG:", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (244, 174), "2 ALARM ZONES TRIGGERED", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (286, 174), "14.3 kWh USED YESTERDAY", 1.5),
                        layer=3)
        all_sprites.add(LcarsText(colours.BLUE, (330, 174), "1.3 Tb DATA USED THIS MONTH", 1.5),
                        layer=3)
        self.info_text = all_sprites.get_sprites_from_layer(3)

        # date display
        self.stardate = LcarsText(colours.BLUE, (12, 380), "STAR DATE 2711.05 17:54:32", 1.5)
        self.lastClockUpdate = 0
        all_sprites.add(self.stardate, layer=1)

        # buttons        
        all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.BEIGE, (107, 127), "SENSORS", self.sensorsHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.PURPLE, (107, 262), "GAUGES", self.gaugesHandler),
                        layer=4)
        all_sprites.add(LcarsButton(colours.PEACH, (107, 398), "WEATHER", self.weatherHandler),
                        layer=4)

        # gadgets        
        all_sprites.add(LcarsGifImage("assets/gadgets/fwscan.gif", (277, 556), 100), layer=1)
        
        self.sensor_gadget = LcarsGifImage("assets/gadgets/lcars_anim2.gif", (235, 150), 100) 
        self.sensor_gadget.visible = False
        all_sprites.add(self.sensor_gadget, layer=2)

        self.dashboard = LcarsImage("assets/gadgets/dashboard.png", (187, 232))
        self.dashboard.visible = False
        all_sprites.add(self.dashboard, layer=2) 

        self.weather = LcarsImage("assets/weather.jpg", (188, 122))
        self.weather.visible = False
        all_sprites.add(self.weather, layer=2) 

        #all_sprites.add(LcarsMoveToMouse(colours.WHITE), layer=1)
        self.beep1 = Sound("assets/audio/panel/201.wav")
        Sound("assets/audio/panel/220.wav").play()

    def update(self, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 1000:
            self.stardate.setText("STAR DATE {}".format(datetime.now().strftime("%d%m.%y %H:%M:%S")))
            self.lastClockUpdate = pygame.time.get_ticks()
        LcarsScreen.update(self, fpsClock)
        
    def handleEvents(self, event, fpsClock):
        LcarsScreen.handleEvents(self, event, fpsClock)
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.beep1.play()

        if event.type == pygame.MOUSEBUTTONUP:
            return False

    def hideInfoText(self):
        if self.info_text[0].visible:
            for sprite in self.info_text:
                sprite.visible = False

    def gaugesHandler(self, item, event, clock):
        self.hideInfoText()
        self.sensor_gadget.visible = False
        self.dashboard.visible = True
        self.weather.visible = False

    def sensorsHandler(self, item, event, clock):
        self.hideInfoText()
        self.sensor_gadget.visible = True
        self.dashboard.visible = False
        self.weather.visible = False
    
    def weatherHandler(self, item, event, clock):
        self.hideInfoText()
        self.sensor_gadget.visible = False
        self.dashboard.visible = False
        self.weather.visible = True
    
    def logoutHandler(self, item, event, clock):
        from screens.authorize import ScreenAuthorize
        self.loadScreen(ScreenAuthorize())
Example #52
0
from gpiozero import Button
import pygame.mixer
from pygame.mixer import Sound
from signal import pause

pygame.mixer.init()

button_sounds = {
    Button(2): Sound("applause-1.wav"),
    Button(3): Sound("applause-2.wav"),

}

for button, sound in button_sounds.items():
    button.when_pressed = sound.play
    
pause()

Example #53
0
class SoundEffect:
    """Class wrapping ``pygame.mixer.Sound`` with the ability to enable/disable sound globally

    Use this instead of ``pygame.mixer.Sound``. The interface is fully transparent.
    """
    def __init__(self, source, ui_config):
        self._ui_config = ui_config
        if ui_config.sound_on:
            self.sound = Sound(source)

    def play(self, loops=0, maxtime=0, fade_ms=0):
        if self._ui_config:
            self.sound.play(loops, maxtime, fade_ms)

    def stop(self):
        if self._ui_config:
            self.sound.stop()

    def fadeout(self, time):
        if self._ui_config:
            self.sound.fadeout(time)

    def set_volume(self, value):
        if self._ui_config:
            self.sound.set_volume(value)

    def get_volume(self):
        if self._ui_config:
            return self.sound.get_volume()

    def get_num_channels(self):
        if self._ui_config:
            return self.sound.get_num_channels()

    def get_length(self):
        if self._ui_config:
            return self.get_length()

    def get_raw(self):
        if self._ui_config:
            return self.sound.get_raw()
Example #54
0
    try:
        if GPIO.event_detected(24):
            current = GPIO.input(24)
            if (last != current):
                if (current == 0):
                    GPIO.add_event_detect(11,
                                          GPIO.BOTH,
                                          callback=count,
                                          bouncetime=5)
                else:
                    GPIO.remove_event_detect(11)
                    number = int(c / 2)

                    print("You dialled", number)
                    if number == 1:
                        choon = Sound('/home/pi/phones/hanging.wav')
                        choon.play()
                    elif number == 2:
                        choon = Sound('/home/pi/phones/callme.wav')
                        choon.play()
                    elif number == 3:
                        choon = Sound('/home/pi/phones/clarksville.wav')
                        choon.play()
                    elif number == 4:
                        choon = Sound('/home/pi/phones/hesonthephone.wav')
                        choon.play()
                    elif number == 5:
                        choon = Sound('/home/pi/phones/payphone.wav')
                        choon.play()
                    elif number == 6:
                        choon = Sound('/home/pi/phones/ring.wav')
import pygame.mixer
from pygame.mixer import Sound
from gpiozero import Button
from signal import pause

#create an object for the mixer module that loads and plays sounds
pygame.mixer.init()

#assign each button to a drum sound
button_sounds = {
    Button(2): Sound("samples/00 - samples - drum cymbal open.wav"),
    Button(3): Sound("samples/00 - samples - drum heavy kick.wav"),
    Button(14): Sound("samples/00 - samples - drum snare hard.wav"),
    Button(15): Sound("samples/00 - samples - drum cymbal closed.wav"),
}

#the sound plays when the button is pressed
for button, sound in button_sounds.items():
    button.when_pressed = sound.play

#keep the program running to detect events
pause()
Example #56
0
import pygame
from pygame.mixer import Sound

pygame.mixer.init()

mutecity = Sound("mutecity.wav") 
Example #57
0
class Mob(Sprite):
    """
       Class for creating game mobs
       Args:
           path_to_image (str) - path to image mob;
           animations (list) - list with paths to animations mobs;
           coords (tuple) - start coordinates of mob
           play_sounds (bool) - if True there will be certain sounds
    """
    def __init__(self, path_to_image, animations, coords, play_sounds):
        super().__init__()

        self.health = 100
        self.path_to_image = path_to_image
        self.stay_animation = PygAnimation([animations[0]])
        self.move_animation = PygAnimation(animations[:2])
        self.dead_animation = PygAnimation([animations[2]])
        self.rect = self.image.get_rect()
        self.rect.x = coords[0]
        self.rect.y = coords[1]
        self.play_sounds = play_sounds
        self.direction = 1
        self.dead_time = 0
        self.distance = 0
        self.speed = 10
        self.damage = 10
        self.push = 30
        self.push_sound = Sound(PUSH_SOUND)
        self.on_ground = True

        self._play_animations()

    @property
    def image(self):
        return pygame.image.load(self.path_to_image)

    @property
    def coordinates(self):
        return self.rect.x, self.rect.y

    def _play_animations(self):
        """
        Method for loading and playing animations It is enough to call method once
        :return: None
        """

        self.stay_animation.play()
        self.move_animation.play()
        self.dead_animation.play()

    def push_object(self, object_):
        """
        If has collision between mob and object_ (for example, player), mob will pushes object by self.push
        :param object_: pygame.sprite object
        :return: None
        """
        object_.health -= self.damage
        check = False
        if self.direction == 1 and object_.rect.x > self.rect.x:
            object_.rect.x += self.push
            check = True
        elif self.direction == -1 and object_.rect.x < self.rect.x:
            object_.rect.x -= self.push
            check = True

        if check and self.play_sounds:
            self.push_sound.play()

    def live(self, screen, camera, level_objects):
        """
        Life cycle of mob. If mod is dead it will returns True
        :param screen: (pygame.Surface) - screen where image will be drew
        :param camera: (Camera) - big rect that follows for player
        :param level_objects: (pygame.sprite.Group) - Group with level blocks sprites or mobs
        :return: (bool)
        """
        permissions = self._check_collision(level_objects)

        if permissions['is_dead']:
            self.dead_time = time()
            return True

        curr_distance = self.direction * self.speed

        if self.direction == 1 and permissions['right']:
            self.rect.x += curr_distance
        elif self.direction == -1 and permissions['left']:
            self.rect.x += curr_distance
        else:
            curr_distance = 0

        self.distance += abs(curr_distance)
        if self.distance >= STOP_MOVEMENT:
            self.direction *= -1
            self.distance = 0

        if curr_distance != 0:
            self.move_animation.blit(screen, camera.apply(self))
        else:
            self.stay_animation.blit(screen, camera.apply(self))

        self._gravity()

        if self.coordinates[1] >= STOP_FALLING:
            self.dead_time = time()
            return True
        return False

    def _gravity(self):
        """
        If there is no surface it means that mob is falling
        :return: None
        """
        if not self.on_ground:
            self.rect.y += GRAVITY_POWER

    def _check_collision(self, level_objects):
        """
           Checks collision with mob and finds side of collision
        :param level_objects: (pygame.sprite.Group) - Group with level blocks sprites
        :return: (dict) - dict with permissions to moves.
        """
        moves = {'right': True,
                 'left': True,
                 'up': False,
                 'is_dead': False}
        self.on_ground = False
        for object_ in level_objects:
            if self != object_ and object_.rect.colliderect(self.rect):
                # 100
                if object_.rect.centerx > self.rect.centerx and object_.rect.centery - self.rect.centery < 30:
                    moves['right'] = False
                    if str(object_) == 'Mob':
                        self.push_object(object_)
                elif object_.rect.centerx < self.rect.centerx and object_.rect.centery - self.rect.centery < 30:
                    moves['left'] = False
                    if str(object_) == 'Mob':
                        self.push_object(object_)

                if object_.rect.centery > self.rect.centery:
                    moves['up'] = True
                    self.on_ground = True
                else:
                    if str(object_) == 'Mob':
                        moves['is_dead'] = True
        return moves

    def __str__(self):
        return 'Mob'

    def die(self, screen, camera):
        """
        If mob is dead this method will be called. 10 seconds for showing death animations
        :param screen: (pygame.Surface) - screen where image will be drew
        :param camera: (Camera) - big rect that follows for player
        :return: (bool)
        """
        self.damage = 0
        self.push = 0
        self.health = 0

        self.dead_animation.blit(screen, camera.apply(self))

        curr_time = time()
        if curr_time - self.dead_time >= TIME_TO_SHOW_DEATH_ANIMATION:
            return True
        return False
Example #58
0
import lightshow as show
import fsr
import pot
import time

import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init()
drums = Sound("drums.wav")
lose = Sound("cry.wav")
win1 = Sound("win1.wav")
win2 = Sound("win2.wav")


def to_pattern(val):
    patterns = []
    pattern = list('0000000000000000')

    for x in range(val):
        pattern[x] = '1'
        patterns.append(''.join(pattern))

    return patterns


while True:
    val = fsr.norm(fsr.get(), 0, 16)
    pot_val = pot.norm(pot.get(), 0.01, 1)
    val = int(val / pot_val)
    if val > 16:
        val = 16
Example #59
0
class Sound:
    """Class wrapping ``pygame.mixer.Sound`` with the ability to enable/disable sound globally

    Use this instead of ``pygame.mixer.Sound``. The interface is fully transparent.
    """
    def __init__(self, source):
        if config.SOUND:
            self.sound = OldSound(source)

    def play(self, loops=0, maxtime=0, fade_ms=0):
        if config.SOUND:
            self.sound.play(loops, maxtime, fade_ms)

    def stop(self):
        if config.SOUND:
            self.sound.stop()

    def fadeout(self, time):
        if config.SOUND:
            self.sound.fadeout(time)

    def set_volume(self, value):
        if config.SOUND:
            self.sound.set_volume(value)

    def get_volume(self):
        if config.SOUND:
            return self.sound.get_volume()

    def get_num_channels(self):
        if config.SOUND:
            return self.sound.get_num_channels()

    def get_length(self):
        if config.SOUND:
            return self.get_length()

    def get_raw(self):
        if config.SOUND:
            return self.sound.get_raw()
Example #60
0
class WildWestStage(Stage):
    BANDIT_TYPES = (Bandit, BulletproofBandit)
    SPAWN_RATE_INCREASE = 0.05
    SPAWNABLE_POSITIONS = (Point(68, 148), Point(182, 148), Point(301, 148),
                           Point(68, 254), Point(182, 254), Point(301, 254))

    _aim = Image('data/graphics/aim.png', pivot=Point(4, 4))
    _preview = Image('data/graphics/wild_west_preview.png', pivot=Point(0, 0))
    _shoot_sound = Sound('data/sounds/gun.wav')
    _background = Image('data/graphics/wild_west_background.png',
                        pivot=Point(0, 0))

    def __init__(self):
        self._bandits = [None] * len(self.SPAWNABLE_POSITIONS)
        self._spawn_timer = Timer(2, self.spawn_bandit_randomly, repeat=True)
        self._hud = HealthScoreHUD(text_color=(255, 255, 255))
        self._lives = 5
        self._score = 0

        System().set_mouse_visibility(False)

    def decrease_life(self):
        self._lives -= 1

    def despawn_bandit(self, bandit):
        if bandit in self._bandits:
            self._bandits[self._bandits.index(bandit)] = None
            self._score += 1

    @classmethod
    def get_preview(cls):
        return cls._preview

    def on_draw(self, dt):
        self._background.draw(Point(0, 0))

        for i, bandit in enumerate(self._bandits):
            if bandit is not None:
                bandit.draw(self.SPAWNABLE_POSITIONS[i])

        self._aim.draw(System().get_mouse_position())
        self._hud.draw(lives=self._lives, score=self._score)

    def on_mouse_event(self, position, button, pressed):
        if pressed and button == BUTTON_LEFT:
            self._shoot_sound.play()

            for i, bandit in enumerate(self._bandits):
                if bandit is not None:
                    if bandit.is_inside_hitbox(self.SPAWNABLE_POSITIONS[i],
                                               position):
                        bandit.on_being_shot()
                        break

    def on_update(self, dt):
        self._spawn_timer.advance(dt)
        self._spawn_timer.fuse *= 1 - self.SPAWN_RATE_INCREASE * dt

        for i, bandit in enumerate(self._bandits):
            if bandit is not None:
                bandit.on_update(dt)

        if self._lives <= 0:
            HighscoresFile.write('Wild West', self._score)
            System().set_mouse_visibility(True)
            System().current_stage = GameOverStage(self._score)

    def on_key_event(self, key, pressed):
        if pressed and key == K_ESCAPE:
            System().set_mouse_visibility(True)
            System().current_stage = PausedStage(self)

    def spawn_bandit_randomly(self):
        free = [
            i for i in range(len(self._bandits)) if self._bandits[i] is None
        ]

        if len(free) > 0:
            position = random.choice(free)

            self._bandits[position] = random.choice(self.BANDIT_TYPES)()