Exemplo n.º 1
0
    def __init__(self, image: str, xy: Tuple[int, int], game: Game):
        scale = 0.9
        width = int(s.CELL_W * scale)
        size = (width, width)
        super().__init__(image, size, game)
        self.xy = xy
        self.rect: Rect = self.get_rect()  # Sprite.rect

        sound = Sound(s.S_FOOTSTEPS_HERO)
        sound.set_volume(0.2)
        self.sound_footsteps = Channel(1)
        self.sound_footsteps.play(sound, loops=-1)
        self.sound_footsteps.pause()
        self.sound_damage: Sound = Sound(s.S_DAMAGE["kick"])

        self.type: str = ""  # тип персонажа: "hero", "monster"
        self.name: str = ""  # имя персонажа: "hero1", ...
        self.active: bool = False  # True= персонаж активный, может действовать; False= не активный, ждёт
        self.items: List[Items] = []
        self.lives: int = 0
        self.damage: int = 0
        self.item_in_hands: Optional[Items] = None  # вещь на руках

        self.action_type: str = ""  # move_to_cell, move_to_wall
        self.action_direction: str = ""  # top, down, left, light
        self.action_start_time = datetime.now()  # время начала действия
        self.action_silent: bool = False  # светофор, True запрещает начинать проигрывать звук действия
        self.actions_max: int = 0  # максимально количество действий героя за один ход игры
        self.actions: int = 0  # количество действий на данный момент
        self.armor = None
Exemplo n.º 2
0
def load_sound_file(filepath: str):
    try:
        sound = Sound(filepath)
        sound.set_volume(0.2)
        return sound
    except Exception as e:
        raise Exception(f"Failed to load sound file '{filepath}': {e}")
Exemplo n.º 3
0
    def __init__(self, name: str, image: str, xy: Tuple[int, int], actions_max: int, lives: int,
                 damage: int, iq: int, game: Game):
        """ Монстр
        @param name: имя монстра
        @param image: картинка
        @param xy: координаты клетки на карте
        @param actions_max: максимальное количество действий
        @param lives: количество здоровья
        @param damage: урон за одно действие
        @param game: ссылка на объект game
        """
        super().__init__(image, xy, game)
        self.type: str = "monster"
        self.name: str = name
        self.actions_max: int = actions_max  # максимально количество действий монстра за один ход игры
        self.lives: int = lives
        self.damage: int = damage
        self.iq: int = iq

        sound = Sound(s.S_FOOTSTEPS_MONSTER)
        sound.set_volume(0.5)
        self.sound_footsteps = Channel(2)
        self.sound_footsteps.play(sound, loops=-1)
        self.sound_footsteps.pause()
        self.sound_damage: Sound = Sound(s.S_DAMAGE["kick_monster1"])
Exemplo n.º 4
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
Exemplo n.º 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
Exemplo n.º 6
0
 def play_sfx(self, name, preload_if_not=True):
     if name not in self.audio_sources:
         raise "Attempted to play unregistered audio source"
     preloaded, path, sound_obj = self.audio_sources[name]
     if not preloaded and preload_if_not:  # preload logic
         sound_obj = Sound(path)
         self.audio_sources[name] = [True, path, sound_obj]
     sound_obj.set_volume(self.master_volume *
                          self.sfx_volume)  # set volume before playing
     sound_obj.play()
Exemplo n.º 7
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()
Exemplo n.º 8
0
    def load_assets(self):
        #=== Load background asset ===#
        for background in BACKGROUND_IMAGE:
            name = get_name_file(background)
            image = self.read(path=background,
                              convert_alpha=True,
                              convert=False)
            self.data["backgrounds"][name] = image

        #=== Load texture asset ===#
        for texture in TEXTURE_IMAGE:
            name = get_name_file(texture)
            image = self.read(path=texture, convert_alpha=True, convert=False)
            self.data["textures"][name] = image

        #=== Load anim asset ===#
        pocng_name = get_name_file(POCONG_IMAGE)
        print(POCONG_IMAGE)
        image = self.read(path=POCONG_IMAGE, convert_alpha=True, convert=False)
        self.data["anim"][pocng_name] = flip(image, True, False)

        keris_name = get_name_file(KERIS_IMAGE)
        image = self.read(path=KERIS_IMAGE, convert_alpha=True, convert=False)
        self.data["anim"][keris_name] = image

        #=== Load other asset ===#
        for other in OTHERS:
            name = get_name_file(other)
            image = self.read(path=other, convert_alpha=True, convert=False)
            self.data["other"][name] = image

        #=== Load sound asset ===#
        for sound_file in SOUND:
            name = get_name_file(sound_file)
            sound = Sound(sound_file)

            self.data["sounds"][name] = sound

        #=== Load effects asset ===#
        for effects_file in EFFECTS:
            name = get_name_file(effects_file)
            sound = Sound(effects_file)
            sound.set_volume(self.config.parse["settings"]["volume"] / 10)
            self.data["effects"][name] = sound

        #=== Load fonts ===#
        for fonts in FONTS:
            name = get_name_file(fonts)
            self.data["fonts"][name] = fonts

        self.data["icon"] = self.read(path=ICON_GAME,
                                      convert_alpha=True,
                                      convert=False)
Exemplo n.º 9
0
class Enemy(Spaceship, EventHandler):
    def __init__(self, config: EnenyConfig):
        super().__init__(image_path=f'assets/enemy_{config.image_id}.png')
        self.shoot_sound = Sound('assets/player_shoot.wav')
        self.shoot_sound.set_volume(0.5)
        self.config = config
        self.rect.y = 0
        self.rect.x = SCREEN_WITH // 2 - self.rect.width // 2
        self._random_move()
        self._random_shoot()

    def _random_move(self):
        event = Event(
            pygame.USEREVENT,
            dict(value=CreateDelayedEvent(delay=random.randint(
                *self.config.movement_freq),
                                          element=self,
                                          event=ChangeDirectionEvent())))
        pygame.event.post(event)

    def _random_shoot(self):
        event = Event(
            pygame.USEREVENT,
            dict(value=CreateDelayedEvent(delay=random.randint(
                *self.config.shoot_freq),
                                          element=self,
                                          event=ShootEvent())))

        pygame.event.post(event)

    def create_bullet(self, direction=Directon.UP):
        return Bullet(self.rect.x + self.rect.width // 2,
                      self.rect.y + self.rect.height, Directon.DOWN)

    def handle(self, event: pygame.event.Event):
        if event.type == pygame.USEREVENT:
            if isinstance(event.value, ChangeDirectionEvent):
                self.move_x = random.randint(-1, 1) * self.MOVE_STEP
                self._random_move()
            elif isinstance(event.value, ShootEvent):
                self.shoot()
                self.shoot_sound.play()
                self._random_shoot()
Exemplo n.º 10
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()
Exemplo n.º 11
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()
Exemplo n.º 12
0
class SoundBox():
    def __init__(self):
        self.explosion_sounds = []
        for filename in EXPLOSION_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(EXPLOSION_VOLUME)
            self.explosion_sounds.append(sound)

        self.multi_explosion_sounds = []
        for filename in MULTI_EXPLOSION_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(MULTI_EXPLOSION_VOLUME)
            self.multi_explosion_sounds.append(sound)

        self.laser_sounds = []
        for filename in LASER_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(LASER_VOLUME)
            self.laser_sounds.append(sound)

        self.extra_life_sound = Sound(f"snd/{EXTRA_LIFE_FILE}")
        self.extra_life_sound.set_volume(EXTRA_LIFE_VOLUME)

    def play_extra_life(self):
        self.extra_life_sound.play()

    def play_explosion(self):
        index = randint(0, len(self.explosion_sounds) - 1)
        self.explosion_sounds[index].play()

    def play_multi_explosion(self):
        index = randint(0, len(self.multi_explosion_sounds) - 1)
        self.multi_explosion_sounds[index].play()

    def play_laser(self):
        index = randint(0, len(self.laser_sounds) - 1)
        self.laser_sounds[index].play()
Exemplo n.º 13
0
class Sounds():
    """A class to store all sounds in Invertibles."""
    def __init__(self):
        """Initialize sounds."""
        # Music
        self.town_theme = Sound('data/sounds/TownTheme.ogg')

        # Sound Effects
        self.fireball = Sound('data/sounds/fireball-whoosh.ogg')
        self.select_spell = Sound('data/sounds/metal-small1.ogg')
        self.monster_kill = Sound('data/sounds/mnstr7.ogg')
        self.set_volume()

    def set_volume(self):
        """Set volume of Sounds."""
        self.town_theme.set_volume(0.5)
        self.fireball.set_volume(1)
        self.monster_kill.set_volume(0.75)
Exemplo n.º 14
0
    def __init__(self):
        self.explosion_sounds = []
        for filename in EXPLOSION_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(EXPLOSION_VOLUME)
            self.explosion_sounds.append(sound)

        self.multi_explosion_sounds = []
        for filename in MULTI_EXPLOSION_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(MULTI_EXPLOSION_VOLUME)
            self.multi_explosion_sounds.append(sound)

        self.laser_sounds = []
        for filename in LASER_FILES:
            sound = Sound(f"snd/{filename}")
            sound.set_volume(LASER_VOLUME)
            self.laser_sounds.append(sound)

        self.extra_life_sound = Sound(f"snd/{EXTRA_LIFE_FILE}")
        self.extra_life_sound.set_volume(EXTRA_LIFE_VOLUME)
Exemplo n.º 15
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)
Exemplo n.º 16
0
def load_sound(name):
    path = f"assets/sounds/{name}.wav"
    sound = Sound(path)
    sound.set_volume(.25)
    return sound
Exemplo n.º 17
0
    pygame.init()
    pygame.display.set_icon(pygame.image.load('img/icon.png'))
    result_window = pygame.display.set_mode((1500, 1000))
    pygame.display.set_caption('Pong')
    result_window.fill(ColorPalette.Background)
    return result_window


window = init_window()
win_w, win_h = window.get_size()
text_surface = None
fps_font = pygame.font.SysFont('couriernew', 20)
big_font = pygame.font.SysFont('couriernew', 60)
hit_wall_sound = Sound(
    precompute(one_period_square_wave_samples, frequency=226, milliseconds=16))
hit_wall_sound.set_volume(.1)
hit_paddle_sound = Sound(
    precompute(one_period_square_wave_samples, frequency=459, milliseconds=96))
hit_paddle_sound.set_volume(.1)
goal_sound = Sound(
    precompute(one_period_square_wave_samples, frequency=490,
               milliseconds=257))
goal_sound.set_volume(.1)
field_size = Size(width=180, height=100)
left_paddle = Paddle(10)
right_paddle = Paddle(170)
ball = Ball()
ball.kick_off(None)
left_direction, right_direction = None, None
score = (0, 0)
KICKOFF = pygame.USEREVENT + 1
Exemplo n.º 18
0
class Menu(Scene):
    def clear(self):
        self.background_sound.fadeout(100)
        self.cursor.clear()

    def start(self):
        # Scene configuration
        self.selected = MAINMENU

        # Sound configuration
        self.background_sound = Sound(
            get_asset_path('sounds', 'bensound-menu.ogg'))

        if SOUND:
            self.background_sound.play(loops=-1)
        self.background_sound.set_volume(.25)

        # Game object creation
        self.background = Background('purple.png')
        self.main_menu = MainMenu()
        self.highscore = HighScore()
        self.credits = Credits()
        self.cursor = Cursor('playerLife1_blue.png', 'sfx_zap.ogg')

        # Game object start
        self.background.start()
        self.main_menu.start()
        self.cursor.start()
        self.highscore.start()
        self.credits.start()

        # Add cursor positions
        self.main_menu.set_cursor_positions(self.cursor)

        # Add objects to groups
        self.render_group.add(
            self.background,
            *self.main_menu.get_objects(),
            self.cursor,
        )
        self.update_group.add(self.cursor, )
        self.event_group.add(self.cursor, )

    def update(self):
        if self.cursor.selected is not None:
            if self.selected == MAINMENU:
                if self.cursor.selected == 0:
                    self.exit(2)
                elif self.cursor.selected == 1:
                    self.highscore.update_scores()
                    self.cursor.clear()
                    self.highscore.set_cursor_positions(self.cursor)
                    self.render_group.empty()
                    self.render_group.add(
                        self.background,
                        self.highscore,
                        self.cursor,
                    )
                    self.selected = HIGHSCORE
                elif self.cursor.selected == 2:
                    self.cursor.clear()
                    self.credits.set_cursor_positions(self.cursor)
                    self.render_group.empty()
                    self.render_group.add(
                        self.background,
                        self.credits,
                        self.cursor,
                    )
                    self.selected = CREDITS
                elif self.cursor.selected == 3:
                    self.exit(0)
            elif self.selected == HIGHSCORE or self.selected == CREDITS:
                if self.cursor.selected == 0:
                    self.cursor.clear()
                    self.main_menu.set_cursor_positions(self.cursor)
                    self.render_group.empty()
                    self.render_group.add(
                        self.background,
                        *self.main_menu.get_objects(),
                        self.cursor,
                    )
                    self.selected = MAINMENU
Exemplo n.º 19
0
class ScreenMain(LcarsScreen):
    def setup(self, all_sprites):
        areset(a)
        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.beep_1 = Sound("assets/audio/panel/201.wav")
        self.fwoosh = Sound("assets/audio/panel/250.m4a")
        self.fwoosh.set_volume(1.0)
        self.fwoosh.play()
        time.sleep(6)
#         Sound("assets/audio/panel/220.wav").play()

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

        
        # Main Screen ------------------------------------------------------------------------------------
        #116-800: 684 : 342
        #90-440 : 350 : 175
        all_sprites.add(LcarsText(colours.WHITE, (192, 174), "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.main_text = all_sprites.get_sprites_from_layer(3)

        # Logout Screen ----------------------------------------------------------------------------------
        self.logout_image = LcarsImage("assets/intro_screen.png", (0,0), self.mainHandler)
        self.logout_image.visible = False
        all_sprites.add(self.logout_image, layer=49) #Previously layer2

        self.logout_gif = LcarsGifImage("assets/gadgets/MOSF.gif", (90, 330), 35)
        self.logout_gif.visible = False
        all_sprites.add(self.logout_gif, layer=49) #Previously 2

        all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "LONG RANGE PROBE", 3), layer=50)
        all_sprites.add(LcarsText(colours.ORANGE, (390, -1), "TOUCH TERMINAL TO PROCEED", 1.5), layer=50)
        self.logout_text = all_sprites.get_sprites_from_layer(50)
        self.hideText(self.logout_text)
        

        # Demo Screen ------------------------------------------------------------------------------------



        # About Screen -----------------------------------------------------------------------------------
        self.purpose = LcarsButton(colours.GREY_BLUE, (107, 127), "PURPOSE", self.purposeHandler)
        self.purpose.visible = False
        all_sprites.add(self.purpose, layer=4)

        self.details = LcarsButton(colours.ORANGE, (107, 262), "DETAILS", self.detailsHandler)
        self.details.visible = False
        all_sprites.add(self.details, layer=4)

        self.personnel = LcarsButton(colours.GREY_BLUE, (107, 398), "PERSONNEL", self.personnelHandler)
        self.personnel.visible = False
        all_sprites.add(self.personnel, layer=4)

        self.sources = LcarsButton(colours.ORANGE, (107, 533), "SOURCES", self.sourcesHandler)
        self.sources.visible = False
        all_sprites.add(self.sources, layer=4)

        
        # Purpose
        all_sprites.add(LcarsText(colours.WHITE, (192, 140), "To inspire", 1.25),
                        layer=5)
        #all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1),
        #                layer=3)
        #all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1),
        #                layer=3)
        #all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1),
        #                layer=3)
        self.purpose_text = all_sprites.get_sprites_from_layer(5)
        self.hideText(self.purpose_text) 

        # Details
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "LENGTH: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (192, 220), "1.5 m (4 ft 6 in)", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (212, 140), "WIDTH: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (212, 220), "0.45 m (blah)", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (232, 140), "HEIGHT: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (232, 220), "0.25 m (blah)", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "MASS: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (252, 220), "20 kg (30 slugs)", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (292, 140), "MATERIALS: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (292, 220), "Carbon fiber reinforced fiberglass shell, internal components 3-D printed PLA plastic", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (332, 140), "CONTROL: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (332, 220), "7 in touchscreen via Rasberry Pi, lights & movement via Arduino Mega", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "COST: ", 1.25), layer=6)
        all_sprites.add(LcarsText(colours.WHITE, (372, 220), "$$$", 1.25), layer=6)
        self.details_text = all_sprites.get_sprites_from_layer(6)
        self.hideText(self.details_text)

        # Personnel
        all_sprites.add(LcarsText(colours.RED_BROWN, (192, 140), "Designed and built by a team of four mechanical & aerospace", 1.25), layer=7)
        all_sprites.add(LcarsText(colours.RED_BROWN, (212, 140), "engineering students at North Carolina State University", 1.25), layer=7)
        self.personnel_text= all_sprites.get_sprites_from_layer(7)
        self.hideText(self.personnel_text)
        
        self.personnel_image1 = LcarsImage("assets/ncsu.png", (192, 560))
        self.personnel_image1.visible = False
        all_sprites.add(self.personnel_image1, layer=7)

        # Sources
        all_sprites.add(LcarsText(colours.GREY_BLUE, (192, 140), "SPECIAL THANKS TO:", 1.25), layer=8)
        all_sprites.add(LcarsText(colours.WHITE, (212, 180), "Toby Kurien", 1.25), layer=8)
        all_sprites.add(LcarsText(colours.WHITE,(232, 180), "NC State EI Garage", 1.25), layer=8)
        self.sources_text = all_sprites.get_sprites_from_layer(8)
        self.hideText(self.sources_text)


        # Explore Screen ---------------------------------------------------------------------------------

        all_sprites.add(LcarsText(colours.RED_BROWN, (142, 140), "Select a section for more information", 1.25), layer=70)
        self.explore_screen_text = all_sprites.get_sprites_from_layer(70)
        self.hideText(self.explore_screen_text)
        
        self.probe_forward_image = LcarsImage("assets/probe_front.png", (172, 500), self.forwardHandler)
        self.probe_forward_image.visible = False
        all_sprites.add(self.probe_forward_image, layer =70)

        self.probe_aft_image = LcarsImage("assets/probe_rear.png", (172, 150), self.aftHandler)
        self.probe_aft_image.visible = False
        all_sprites.add(self.probe_aft_image, layer=70)



        ##### Forward Section #####
        all_sprites.add(LcarsText(colours.RED_BROWN, (142, 140), "Select a component for more information", 1.25), layer=71)
        self.forward_text = all_sprites.get_sprites_from_layer(71)
#         self.forward_text.visible = False

        self.forward_plate = LcarsImage("assets/forward/front_section.png", (172, 533))
        self.forward_plate.visible = False
        all_sprites.add(self.probe_forward_image, layer =71)

        ## Back Forward Button ##
        self.forward_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.forwardHandler)
        self.forward_button.visible = False
        all_sprites.add(self.forward_button, layer=60)

        ## Back Aft Button ##
        self.aft_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.exploreHandler)
        self.aft_button.visible = False
        all_sprites.add(self.aft_button, layer=60)

        # BTO ARRAY #
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "B.T.O. ARRAY", 1.75), layer=61)  
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The B.T.O. Array is the primary method of communication for the probe.", 1.25), layer=61)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "The array is entirely composed of the S.B.S. High-Gain Parabolic Antenna,", 1.25), layer = 61)
        all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "which is capable of simultaneous dual transmission in the S and X bands", 1.25), layer=61)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "and receipt of control commands in the Ka and Ku bands.  The array is", 1.25), layer=61)
        all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "paired with the Yokel Sensor Suite to determine physical properties of ", 1.25), layer=61)
        all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "local bodies using microwave radiation.", 1.25), layer=61)
        self.communication_text = all_sprites.get_sprites_from_layer(61)
        self.hideText(self.communication_text)

        # YOKEL SENSOR SUITE #
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "YOKEL SENSOR SUITE", 1.75), layer=62)
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The Yokel Sensor Suite houses the scientific payload and guidance", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "system on the probe.  The instruments contained within are:", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (222, 150), "Autonomous Telemetry Guidance Unit", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (242, 150), "Energetic Particle Detector", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (262, 150), "Gravitational Mapping Unit", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (282, 150), "High Energy Multi-Spectral Analyzer", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (302, 150), "Magnetometry Suite", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (322, 150), "Radar Detection & Tracking System", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (342, 150), "Radio Science Array", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.WHITE, (362, 150), "Space Radiation Measurement System", 1.25), layer=62)
        all_sprites.add(LcarsText(colours.ORANGE, (392, 140), "Collected data is stored in the Optical Data Chips for later processing.", 1.25), layer=62)
        self.sensor_text = all_sprites.get_sprites_from_layer(62)
        self.hideText(self.sensor_text)

        # Probe Computers #
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROBE COMPUTERS", 1.75), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe features two onboard computers, the Guidance Computer and", 1.25), layer=63)        
        all_sprites.add(LcarsText(colours.WHITE, (162, 473), "Guidance Computer", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "the Data Processing Unit , which handle all data and control processes.", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.WHITE, (192, 165), "Data Processing Unit", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "The Guidance Computer receives control commands through the BTO ", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "Array, and local object data from the Yokel Sensor Suite, to ensure safe", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "travel.  The Data Processing Unit receives all raw data from the Optical", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "and processes the data for transmission.  For redundancy, both", 1.25), layer=63)
        all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "computers are independently capable of assuming the others' duties.", 1.25), layer=63)
        self.computer_text = all_sprites.get_sprites_from_layer(63)
        self.hideText(self.computer_text)

        # Optical Data Chips #
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "OPTICAL DATA CHIPS", 1.75), layer=64)
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe is equipped with 24 optical data chips for the storage of sensor", 1.25), layer=64)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "and control data.  Each chip, which can store up to 830 TB of data, is", 1.25), layer=64)
        all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "constructed of a nano-structured quartz composite.  Data is read/written", 1.25), layer=64)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "to the chips using a Smith-Taylor laser system.", 1.25), layer=64)
        self.chip_text = all_sprites.get_sprites_from_layer(64)
        self.hideText(self.chip_text)

        # Lofton Microfusion Core #
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "LOFTON MICROFUSION CORE", 1.75), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "All of the required power for the probe is provided by the Lofton", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "Microfusion Core.  Encased within a shielded tungsten-titanium shell,", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "11.3 KW of power are produced from a micro-aneutronic fusion reaction ", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "which is converted to electricity via electrostatic direct conversion.", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "Of the 11.3 KW produced, 8 KW are used by the ion propulsion system,", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "1.4 KW by the sensor suite, 1 KW by the computers, and 0.9 KW by the", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "communication array during normal operation. Helium is used for the", 1.25), layer=65)
        all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "fusion reaction which is provided by the monopropellant tank.", 1.25), layer=65)
        self.fusion_text = all_sprites.get_sprites_from_layer(65)
        self.hideText(self.fusion_text)

        

        ###### AFT SECTION ######
        all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROPULSION SYSTEM", 1.75), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "After launch, the probe is driven by the Kehrer Hybrid Ion Drive, is", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "capable of both ion and chemical propulsion, and is comprised of the ", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "engine, thrusters, and fuel tanks. Ion propulsion creates thrust by drawing", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "power from the fusion core to accelerate and expel Xenon ions from the", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "two, 420 kg storage tanks, and is the main method of propulsion. For quick", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "changes in velocity, the chemical propulsion system is activated.  This", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "system uses the monopropellant hydrazine, which is stored in the 300 kg ", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "storage tank.  The combination of two different propulsion methods allows", 1.25), layer=66)
        all_sprites.add(LcarsText(colours.ORANGE, (402, 140), "the probe a versatile mix of range and maneuverability.", 1.25), layer=66)
        self.propulsion_text = all_sprites.get_sprites_from_layer(66)
        self.hideText(self.propulsion_text)

        
        
    # ** Event Handlers **

    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 1000:
            self.stardate.setText("EARTH DATE {}".format(datetime.now().strftime("%m.%d.%y %H:%M:%S")))
            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.beep_1.play()

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

    # ** Screen Handlers ** --------------------------------------------------------------------

    def mainHandler(self, item, event, clock):
#         demo(a)
        self.hideAll()
        self.showText(self.main_text)
            
    def logoutHandler(self, item, event, clock):
#         demo(a)
        from screens.authorize import ScreenAuthorize
        self.loadScreen(ScreenAuthorize())

        # PUT TURN OFF COMMAND HERE

    def aboutHandler(self, item, event, clock):
#         demo(a)
        from screens.aboutScreen import ScreenAbout
        self.loadScreen(ScreenAbout())
        
    def demoHandler(self, item, event, clock):
        demo(a)

    def exploreHandler(self, item, event, clock):
#         demo(a)
        from screens.exploreScreen import ScreenExplore
        self.loadScreen(ScreenExplore())
#         self.hideAll()
#         
#         self.showText(self.explore_screen_text)
#         self.probe_forward_image.visible = True
#         self.probe_aft_image.visible = True

    # ** Sub Screen Handlers ** -----------------------------------------------------------------

    #       About Screen -------------------------------------
    def purposeHandler(self, item, event, clock):
        self.showText(self.purpose_text)
        self.hideText(self.details_text)
        self.hideText(self.personnel_text)
        self.personnel_image1.visible = False
        self.hideText(self.sources_text)
        
    def detailsHandler(self, item, event, clock):
        self.hideText(self.purpose_text)
        self.showText(self.details_text)
        self.hideText(self.personnel_text)
        self.personnel_image1.visible = False
        self.hideText(self.sources_text)

    def personnelHandler(self, item, event, clock):
        self.hideText(self.purpose_text)
        self.hideText(self.details_text)
        self.showText(self.personnel_text)
        self.personnel_image1.visible = True
        self.hideText(self.sources_text)

    def sourcesHandler(self, item, event, clock):
        self.hideText(self.purpose_text)
        self.hideText(self.details_text)
        self.hideText(self.personnel_text)
        self.personnel_image1.visible = False
        self.showText(self.sources_text)



    #       Explore Screen -----------------------------------
    # ** Main **
    def forwardHandler(self, item, event, clock):
        self.hideText(self.explore_screen_text)
        self.probe_forward_image.visible = False
        self.probe_aft_image.visible = False
        self.forward_button.visible = False
        
        self.hideText(self.communication_text)
        self.hideText(self.sensor_text)
        self.hideText(self.computer_text)
        self.hideText(self.chip_text)
        self.hideText(self.fusion_text)
        
        self.showText(self.forward_text)
        self.aft_button.visible = True        
        #Put others here
        self.forward_plate.visible = True

    def aftHandler(self, item, event, clock):
        self.hideText(self.explore_screen_text)
        self.probe_forward_image.visible = False
        self.probe_aft_image.visible = False

        self.showText(propulsion_text)
        self.aft_button.visible = True

    # ** Forward **
    def communicationsHandler(self, item, event, clock):
        self.showText(self.communication_text)
        self.aft_button.visible = False
        self.forward_button.visible = True

    def sensorsHandler(self, item, event, clock):
        self.showText(sensor_text)
        self.aft_button.visible = False
        self.forward_button.visible = True

    def computerHandler(self, item, event, clock):
        self.showText(computer_text)
        self.aft_button.visible = False
        self.forward_button.visible = True

    def chipsHandler(self, item, event, clock):
        self.showText(chip_text)
        self.aft_button.visible = False
        self.forward_button.visible = True

    def powerHandler(self, item, event, clock):
        self.showText(fusion_text)
        self.aft_button.visible = False
        self.forward_button.visible = True





    # ** Content Handlers ** --------------------------------------------------------
    
    def hideText(self, name):
        if name[0].visible:
            for sprite in name:
                sprite.visible = False

    def showText(self, name):
        for sprite in name:
            sprite.visible = True

    def hideAll(self):
        #MAIN
        self.hideText(self.main_text)
        #LOGOUT
        self.logout_image.visible = False
        self.logout_gif.visible = False
        self.hideText(self.logout_text)
        #ABOUT
        self.purpose.visible = False
        self.details.visible = False
        self.personnel.visible = False
        self.sources.visible = False        
        self.hideText(self.purpose_text)
        self.hideText(self.details_text)
        self.hideText(self.personnel_text)
        self.personnel_image1.visible = False
        self.hideText(self.sources_text)
        #EXPLORE
        self.probe_forward_image.visible = False
        self.probe_aft_image.visible = False
        self.forward_plate.visible = False
        self.aft_button.visible = False
        self.forward_button.visible = False
        self.hideText(self.explore_screen_text)
        self.hideText(self.forward_text)
        self.hideText(self.propulsion_text)
        self.hideText(self.communication_text)
        self.hideText(self.sensor_text)
        self.hideText(self.computer_text)
        self.hideText(self.chip_text)
        self.hideText(self.fusion_text)
Exemplo n.º 20
0
def prep_sound_file(sound_list, volume=1.0):
    rand_choice = choice(sound_list)
    rand_sound = Sound(rand_choice)
    rand_sound.set_volume(volume)
    return rand_sound
Exemplo n.º 21
0
def prep_shutdown_sound():
    global SHUTDOWN_SOUND
    global SHUTDOWN_DUR
    SHUTDOWN_SOUND = Sound(SHUTDOWN_PATH)
    SHUTDOWN_SOUND.set_volume(.1)
    SHUTDOWN_DUR = SHUTDOWN_SOUND.get_length()
Exemplo n.º 22
0
 aim = smoothscale(aim,(len_aim,len_aim))
 
 p1w = load('resource/p1win.png').convert_alpha()
 w,h = p1w.get_size()
 h = int(maxn_x*size_win*h/w)
 w = int(maxn_x*size_win)
 p1w = smoothscale(p1w,(w,h))
 
 p2w = load('resource/p2win.png').convert_alpha()
 w,h = p2w.get_size()
 h = int(maxn_x*size_win*h/w)
 w = int(maxn_x*size_win)
 p2w = smoothscale(p2w,(w,h))
 
 sound = Sound('sound.wav') 
 sound.set_volume(1)
 BGM = Sound('BGM.wav')
 BGM.set_volume(0.3)
 
 button_restart = myButton('resource/red_cm.png','resource/blue_cm.png', (int(maxn_x/2),int(maxn_y-len_menu/2)))
 button_set = myButton('resource/red_cm_set.png','resource/blue_cm_set.png', (int(maxn_x/4),int(maxn_y-len_menu/2)))
 button_retract = myButton('resource/red_cm_retract.png','resource/blue_cm_retract.png', (int(3*maxn_x/4),int(maxn_y-len_menu/2)))
 
 pos_win_x = int(maxn_x*(1-size_win)/2)
 #pos_win_x -= int(w/2)
 pos_win_y = int(maxn_y*0.1)
 #pos_win_y -= int(h/2)
 tcm_x = 1
 tcm_y = 1
 pos_line=[]
 pos_raw=[]
Exemplo n.º 23
0
class Sounds():
    """A class to store all sounds in Tetris."""

    def __init__(self):
        """Initialize Sounds."""
        # Music
        self.title_music = Sound('sounds/music/title_music.ogg')
        self.a_type_music = Sound('sounds/music/a_type_music.ogg')
        self.b_type_music = Sound('sounds/music/b_type_music.ogg')
        self.c_type_music = Sound('sounds/music/c_type_music.ogg')
        self.high_score_music = Sound('sounds/music/high_score_music.ogg')

        # Sound Effects
        self.board_land_after_clear = Sound('sounds/sound_effects/board_land_after_clear.ogg')
        self.clear_line = Sound('sounds/sound_effects/clear_line.ogg')
        self.game_over = Sound('sounds/sound_effects/game_over.ogg')
        self.game_over_wall = Sound('sounds/sound_effects/game_over_wall.ogg')
        self.level_up = Sound('sounds/sound_effects/level_up.ogg')
        self.move_sideways = Sound('sounds/sound_effects/move_sideways.ogg')
        self.option_select = Sound('sounds/sound_effects/option_select.ogg')
        self.pause = Sound('sounds/sound_effects/pause.ogg')
        self.rotate = Sound('sounds/sound_effects/rotate.ogg')
        self.shape_land = Sound('sounds/sound_effects/shape_land.ogg')
        self.switch_option_screen = Sound('sounds/sound_effects/switch_option_screen.ogg')
        self.tetris_clear = Sound('sounds/sound_effects/tetris_clear.ogg')

        self.set_volume()


    def set_volume(self):
        """Set volume of Sounds."""
        self.title_music.set_volume(.75)
        self.a_type_music.set_volume(.75)
        self.b_type_music.set_volume(.75)
        self.c_type_music.set_volume(.75)
        self.high_score_music.set_volume(.75)
        self.level_up.set_volume(.75)

        self.board_land_after_clear.set_volume(.75)
        self.clear_line.set_volume(.75)
        self.game_over.set_volume(.75)
        self.game_over_wall.set_volume(.75)
        self.level_up.set_volume(.75)
        self.move_sideways.set_volume(.75)
        self.option_select.set_volume(.75)
        self.pause.set_volume(.75)
        self.rotate.set_volume(.75)
        self.shape_land.set_volume(.75)
        self.switch_option_screen.set_volume(.75)
        self.tetris_clear.set_volume(.75)
Exemplo n.º 24
0
def play_sound(filename, volume=0.75):
    global SOUND_PATH
    sound = Sound(SOUND_PATH + filename)
    sound.set_volume(volume)
    sound.play()
Exemplo n.º 25
0
def load_sound(filename: str):
    filepath = str(Path(__file__).parent.joinpath(filename))
    sound = Sound(filepath)
    sound.set_volume(0.2)
    return sound
Exemplo n.º 26
0
class Rocket:

    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

    @gl_utilities.sprites_configuration
    def _draw_sprites(self):
        self.beam.draw()
        self.plume.draw()

    @gl_utilities.shader_configuration(config.basedir+"/shaders/vertex.txt", 
                                       config.basedir+"/shaders/fragment.txt")
    def _draw_shader(self):
        glPushMatrix()

        glRotate(self.angle,0.0,0.0,1.0)
        glRotate(90.0,-1.0,0.0,0.0)

        glCallList(self.model.gl_list)
        glPopMatrix()

    def draw(self):

        glPushMatrix()

        glTranslate(-self.position.x, -self.position.y, 0.0)

        self._draw_sprites()
        self._draw_shader()

        glPopMatrix()

#        _draw_bounding_box(self.bounding_box)

    def _fire(self):
#    angle, position, blaster_color, blaster_list):

        direction=Vector2D(math.sin(math.radians(self.angle)),
                           -math.cos(math.radians(self.angle)))

        self.blaster_list.append(Blaster(self.blaster_color,
                                         self.position+2.001*direction,
                                         direction))

    def update(self,clock):

        seconds_passed=clock.get_time()/1000.0

        self.angle += (self.maximum_roll_rate*
                       self.controls.get_rotate()*
                       seconds_passed)

        if 0 < self.controls.get_throttle():
            if self.plume.is_off():
                self.plume.on()

            self.engine_sound.play()

            self.plume.throttle=self.controls.get_throttle()

            thrust=self.maximum_acceleration*seconds_passed*self.plume.throttle

            accel=Vector2D(math.sin(math.radians(self.angle))*thrust,
                           -math.cos(math.radians(self.angle))*thrust)
            
            self.velocity += accel
            
        elif self.controls.get_throttle() <= 0 and self.plume.is_on():
            self.plume.off()
            self.engine_sound.stop()

        self.velocity += self.gravity*seconds_passed

        speed = self.velocity.length()
 
        if self.maximum_speed < speed:
            self.velocity *= self.maximum_speed/speed

        self.position += self.velocity*seconds_passed

        self.bounding_box.position=self.position
        self.bounding_box.angle=self.angle

        self.bounding_box.update()

        if self.controls.get_beam_activated() and self.beam.is_off():
            tmp_beam_angle = self.controls.get_beam_angle()

            if tmp_beam_angle is None:
                self.beam.angle = self.angle + 90
            else:
                self.beam.angle = math.degrees(tmp_beam_angle)

            self.beam.on()
        elif not self.controls.get_beam_activated():
            self.beam.off()

        if self.controls.fire() or (0 < self.fire_counter < 3) :
            if 0 < self.fire_counter:
                self.blaster_sound.play()
                self._fire()
                self.fire_counter -= 1
        else:
            self.fire_counter=3

        self.beam.update(clock)
        self.plume.update(clock)

        self.plume.angle = self.angle


        if self.beam.is_on() and not self.beam.is_extending():
            self.beam.off()