Exemplo n.º 1
0
 def update(self, time):
     print('update', self._filename, self._playing, time, self._start_time,
           self._end_time)
     if time < self._start_time: pass
     elif self._playing == 'no':
         try:
             music.stop()
             music.load(self._filename)
             music.set_volume(0.01)  # 0.0 stops pygame.mixer.music.
             # Workaround for a pygame/libsdl mixer bug.
             #music.play(0, self._start)
             music.play(0, 0)
             self._playing = 'yes'
         except:  # Filename not found? Song is too short? SMPEG blows?
             music.stop()
             self._playing = 'no'
     elif time < self._start_time + 1000:  # mixer.music can't fade in
         music.set_volume((time - self._start_time) / 1000.0)
     elif (time > self._end_time - 1000) and self._playing == 'yes':
         self._playing = 'fadeout'
         music.fadeout(1000)
     elif time > self._end_time:
         music.stop()
         dt = pygame.time.get_ticks() + 1000 - self._start_time
         self._end_time = dt + self._end_time
         self._start_time = dt + self._start_time
         self._playing = 'no'
Exemplo n.º 2
0
 def update(self, time):
   print ('update', self._filename, self._playing, time, self._start_time, self._end_time)
   if time < self._start_time: pass
   elif self._playing == 'no':
     try:
       music.stop()
       music.load(self._filename)
       music.set_volume(0.01) # 0.0 stops pygame.mixer.music.
       # Workaround for a pygame/libsdl mixer bug.
       #music.play(0, self._start)
       music.play(0, 0)
       self._playing = 'yes'
     except: # Filename not found? Song is too short? SMPEG blows?
       music.stop()
       self._playing = 'no'
   elif time < self._start_time + 1000: # mixer.music can't fade in
     music.set_volume((time - self._start_time) / 1000.0)
   elif (time > self._end_time - 1000) and self._playing == 'yes':
     self._playing = 'fadeout'
     music.fadeout(1000)
   elif time > self._end_time:
     music.stop()
     dt = pygame.time.get_ticks() + 1000 - self._start_time
     self._end_time = dt + self._end_time
     self._start_time = dt + self._start_time
     self._playing = 'no'
Exemplo n.º 3
0
 def redraw(self):
     for i in range(self.height - 1):
         for j in range(self.width - 1):
             # Figure out what to draw
             intensity = self.get_intensity(i, j)
             particle = self.get_particle(intensity)
             color = self.get_color(intensity)
             # Where to draw it
             x, y = j, self.height - i - 1
             self.screen.addch(y, x, particle, color)
             self.prev_fire[i][j] = int(intensity)
             # Save for the next iteration
     ch = self.screen.getch()
     if ch != curses.ERR:
         if pygame_available:
             if ch == ord('-') and self.volume != 0.0:
                 self.volume = self.volume - .10
                 music.set_volume(self.volume)
             elif ch == ord('+') or ch == ord('=') and self.volume != 1.0:
                 self.volume = self.volume + .10
                 music.set_volume(self.volume)
         if ch == ord('q') or ch == curses.KEY_ESCAPE:
             end_session(0)
     self.screen.refresh()
     self.screen.timeout(50)
     time.sleep(1.0 / self.speed)
Exemplo n.º 4
0
 def redraw(self):
   for i in range(self.height - 1):
     for j in range(self.width - 1):
       # Figure out what to draw
       intensity = self.get_intensity(i, j)
       particle = self.get_particle(intensity)
       color = self.get_color(intensity)
       # Where to draw it
       x, y = j, self.height - i - 1
       self.screen.addch(y, x, particle, color)
       self.prev_fire[i][j] = int(intensity)
       # Save for the next iteration
   ch = self.screen.getch()
   if ch != curses.ERR:
     if pygame_available:
         if ch == ord('-') and self.volume != 0.0:
           self.volume = self.volume - .10
           music.set_volume(self.volume)
         elif ch == ord('+') or ch == ord('=') and self.volume != 1.0:
           self.volume = self.volume + .10
           music.set_volume(self.volume)
     if ch == ord('q') or ch == curses.KEY_ESCAPE:
       end_session(0)
   self.screen.refresh()
   self.screen.timeout(50)
   time.sleep(1.0 / self.speed)
Exemplo n.º 5
0
    def mouse_drag(self, e: Event):

        m = self.margin
        w = self.width - 2 * m
        x = max(0.0, min(1.0, (e.local[0] - m) / w))
        music.set_volume(x)
        self.invalidate()
Exemplo n.º 6
0
def play_song(filename, volume=0.75):
    global current_song
    global MUSIC_PATH
    if filename != current_song:
        music.load(MUSIC_PATH + filename)
        music.set_volume(volume)
        music.play(-1)
        current_song = filename
Exemplo n.º 7
0
def CreditsMenu():
    music.load(join(f_music, 'Credits_Music.ogg'))
    music.set_volume(0.5)
    music.play(loops=-1)
    check_credits_menu = True
    coin_animation = 1
    coin_animation_control = 0
    num_image = 1
    y_mov = 0
    background_animation_control = 0
    button_back = Rect(400, 690, 192, 42)
    button_cat_sound = Rect(850, 500, 100, 100)
    while check_credits_menu:

        CLOCK.tick(60)
        mouse_pos = mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == MOUSEBUTTONDOWN and event.button == 1:
                if button_back.collidepoint(mouse.get_pos()):
                    sfxButtonClick.play()
                    check_credits_menu = False
                if button_cat_sound.collidepoint(mouse.get_pos()):
                    sfxCat.play()

        ButtonsPrint(button_cat_sound, ':3', menuFont)
        SCREEN.blit(scale(load(join(f_backgrounds, f'Credits_{num_image}.png'))
                          .convert_alpha(), (1040, 701)), (0, 80))
        y_move = y_mov % imgCredits.get_rect().height
        SCREEN.blit(imgCredits, (0, (y_move - imgCredits.get_rect().height)))
        if y_move < Height:
            SCREEN.blit(imgCredits, (0, y_move))
        SCREEN.blit(scale(load(join(f_backgrounds, f'CreditsT_{num_image}.png'))
                          .convert_alpha(), (1040, 701)), (0, 80))
        ButtonsPrint(button_back, 'BACK', menuFont)
        SCREEN.blit(imgCursor, (mouse_pos[0], mouse_pos[1]))
        SCREEN.blit(bgArcadeMenu, (0, 0))
        SCREEN.blit(scale(load(join(f_coin, f'Coin_{coin_animation}.png'))
                          .convert_alpha(), (220, 150)), (370, 855))

        y_mov -= 0.75
        coin_animation_control += 0.5
        background_animation_control += 1

        if background_animation_control % 8 == 0:
            num_image += 1
        if num_image == 9:
            num_image = 1

        if coin_animation_control % 6 == 0:
            coin_animation += 1
        if coin_animation > 6:
            coin_animation = 1
            coin_animation_control = 0
        display.update()
    music.stop()
Exemplo n.º 8
0
    def __init__(self, songs, courses, screen, game):
        InterfaceWindow.__init__(self, screen, "courseselect-bg.png")

        recordkeys = dict([(k.info["recordkey"], k) for k in songs])

        self._courses = [CourseDisplay(c, recordkeys, game) for c in courses]
        self._all_courses = self._courses
        self._index = 0
        self._clock = pygame.time.Clock()
        self._game = game
        self._config = dict(game_config)
        self._configs = []

        self._list = ListBox(FontTheme.Crs_list, [255, 255, 255], 32, 10, 256,
                             [373, 150])
        if mainconfig["folders"]:
            self._create_folders()
            self._create_folder_list()
        else:
            self._folders = None
            self._base_text = _("All Courses")
            self._courses.sort(SORTS[SORT_NAMES[mainconfig["sortmode"] %
                                                NUM_SORTS]])
            self._list.set_items([s.name for s in self._courses])

        self._course = self._courses[self._index]
        self._course.render()

        players = games.GAMES[game].players

        for i in range(players):
            self._configs.append(dict(player_config))

        ActiveIndicator([368, 306], height=32, width=266).add(self._sprites)
        HelpText(CS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help,
                 [186, 20]).add(self._sprites)

        self._list_gfx = ScrollingImage(self._course.image, [15, 80], 390)
        self._coursetitle = TextDisplay('Crs_course_name', [345, 28], [20, 56])
        self._title = TextDisplay('Crs_course_list_head', [240, 28], [377, 27])
        self._banner = ImageDisplay(self._course.banner, [373, 56])
        self._sprites.add([
            self._list, self._list_gfx, self._title, self._coursetitle,
            self._banner
        ])
        self._screen.blit(self._bg, [0, 0])
        pygame.display.update()
        self.loop()
        music.fadeout(500)
        pygame.time.wait(500)
        # FIXME Does this belong in the menu code? Probably.
        music.load(os.path.join(sound_path, "menu.ogg"))
        music.set_volume(1.0)
        music.play(4, 0.0)
        player_config.update(self._configs[0])  # Save p1's settings
        game_config.update(self._config)  # save game settings
Exemplo n.º 9
0
def load_sound_paths():
    global MUSIC_PATH
    global SOUND_PATH

    path = os.path.dirname(os.path.abspath(__file__))

    MUSIC_PATH = path + '/assets/music/'
    SOUND_PATH = path + '/assets/sounds/'

    pygame.mixer.init()
    music.set_volume(0.80)
Exemplo n.º 10
0
 def check_volume(self, *args):
     music.set_volume(args[1])
     print(self.ids.volume.cursor_size)
     if self.ids.volumeImage.source.split('/')[1] == 'volume.png':
         if not self.ids.volume.value:
             self.ids.volumeImage.source = self.ids.volumeImage.source.split(
                 '/')[0] + '/mute.png'
     else:
         if self.ids.volume.value:
             self.ids.volumeImage.source = self.ids.volumeImage.source.split(
                 '/')[0] + '/volume.png'
Exemplo n.º 11
0
 def check():
     if canvas.coords(id_)[1] <= canvas.winfo_height():
         canvas.after(delay, check)
     else:
         canvas.setvar(GAME_IS_RUNNING, '0')
         canvas.wait_variable(BALL_IS_MOVING)
         canvas.unbind_all(KEY_LEFT)
         canvas.unbind_all(KEY_RIGHT)
         music.set_volume(MENU_VOLUME)
         make_menu(tk)
         canvas.destroy()
Exemplo n.º 12
0
    def play_menu_music(self):
        """Проигрывание музыки во время нахождения в меню"""

        if self.sound:
            for sound in self.sounds.values():
                sound: Sound
                sound.stop()
            music.unpause()
            music.unload()
            music.load('music/background.mp3')
            music.set_volume(1)
            music.play(-1)
Exemplo n.º 13
0
    def __init__(self):
        """
            Args: -

            Action:
                Create a Song that can be played.
        """
        name_song = choice(Music_Config['NAME_MUSIC'])+'_'+\
     choice(Music_Config['NAME_GEN'])
        music.load(Directory['DIR_MUSIC'] + name_song +
                   Music_Config['EXTENSION'])
        music.set_volume(Music_Config['VOLUME'] / 100)
Exemplo n.º 14
0
def load_sound_paths():
    global MUSIC_PATH
    global SOUND_PATH
    if globals.on_cpi:
        MUSIC_PATH = '/home/cpi/games/Python/diner-mafia/pygine/assets/music/'
        SOUND_PATH = '/home/cpi/games/Python/diner-mafia/pygine/assets/sounds/'
    else:
        MUSIC_PATH = 'pygine/assets/music/'
        SOUND_PATH = 'pygine/assets/sounds/'

    pygame.mixer.init()
    music.set_volume(0.80)
Exemplo n.º 15
0
  def __init__(self, songs, courses, screen, game):
    InterfaceWindow.__init__(self, screen, "courseselect-bg.png")

    recordkeys = dict([(k.info["recordkey"], k) for k in songs])

    self._courses = [CourseDisplay(c, recordkeys, game) for c in courses]
    self._all_courses = self._courses
    self._index = 0
    self._clock = pygame.time.Clock()
    self._game = game
    self._config = dict(game_config)
    self._configs = []

    self._list = ListBox(FontTheme.Crs_list,
                         [255, 255, 255], 32, 10, 256, [373, 150])
    if len(self._courses) > 60 and mainconfig["folders"]:
      self._create_folders()
      self._create_folder_list()
    else:
      self._folders = None
      self._base_text = _("All Courses")
      self._courses.sort(SORTS[SORT_NAMES[mainconfig["sortmode"] % NUM_SORTS]])
      self._list.set_items([s.name for s in self._courses])

    self._course = self._courses[self._index]
    self._course.render()

    players = games.GAMES[game].players

    for i in range(players):
      self._configs.append(dict(player_config))

    ActiveIndicator([368, 306], height = 32, width = 266).add(self._sprites)
    HelpText(CS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help,
             [186, 20]).add(self._sprites)

    self._list_gfx = ScrollingImage(self._course.image, [15, 80], 390)
    self._coursetitle = TextDisplay('Crs_course_name', [345, 28], [20, 56])
    self._title = TextDisplay('Crs_course_list_head', [240, 28], [377, 27])
    self._banner = ImageDisplay(self._course.banner, [373, 56])
    self._sprites.add([self._list, self._list_gfx, self._title,
                       self._coursetitle, self._banner])
    self._screen.blit(self._bg, [0, 0])
    pygame.display.update()
    self.loop()
    music.fadeout(500)
    pygame.time.wait(500)
    # FIXME Does this belong in the menu code? Probably.
    music.load(os.path.join(sound_path, "menu.ogg"))
    music.set_volume(1.0)
    music.play(4, 0.0)
    player_config.update(self._configs[0]) # Save p1's settings
Exemplo n.º 16
0
    def play_game_music(self):
        """Проигрывание музыки во время нахождения в игре"""

        if self.sound:
            for sound in self.sounds.values():
                sound: Sound
                sound.stop()

            music.unpause()
            music.unload()
            music.load('music/background_tango_short.wav')
            music.set_volume(0.1)
            music.play(-1)
    def play_sound(self, type):
        """Play soundtrack."""

        if type == 'menu' or type == 'playing':
            music.load(self.sound_files[type])
            music.play(loops=-1)
            if type == 'playing':
                music.set_volume(0.2)
            else:
                music.set_volume(0.5)
        else:
            if type == 'game_over':
                music.stop()
                sleep(1.5)
            self.channels[type].play(self.opened_sounds[type])
Exemplo n.º 18
0
def voldown():
    global vol
    global playing
    vol -= 0.02
    mp3.set_volume(vol)
    #cvol = mp3.get_volume()
    newlogline("Volume down")
    print(mp3.get_volume())
    sense.show_letter("-", text_colour=g, back_colour=b)
    sleep(0.3)
    if playing == False:
        displayH("pause")
    elif playing == True:
        displayH("play")
    else:
        displayH("smile")
Exemplo n.º 19
0
def main():
    """
    This is the game entrypoint. Here tkinter and pygame are ste up. Desktop window size, required
    widgets, music player and so on are configured here.
    """
    tk = Tk()
    tk.wm_title('ping-pong')
    tk.wm_geometry(f'{tk.winfo_screenwidth()}x{tk.winfo_screenheight()}')
    tk.wm_resizable(0, 0)
    tk.wm_attributes('-topmost', 1, '-type', 'splash')
    tk.configure(background=BACKGROUND_COLOR)
    init()
    music.load(Path('assets') / 'ambience.ogg')
    music.set_volume(MENU_VOLUME)
    music.play(-1)
    make_menu(tk)
    tk.mainloop()
Exemplo n.º 20
0
def make_game(tk: Tk):
    """
    The main activity constructor. It turns on the music volume to max level, allocates canvas and
    manages its entity motions. Generally speaking, there're just two sprites over here: the ball
    and the paddle. The first one is periodically re-rendered by the game, the last one's managed
    by the player. The endgame condition is the ball being fallen over the bottom viewport border.
    """
    music.set_volume(GAME_VOLUME)
    canvas_width, canvas_height = tk.winfo_width(), tk.winfo_height()
    canvas = Canvas(tk,
                    width=canvas_width,
                    height=canvas_height,
                    highlightthickness=0,
                    bg=BACKGROUND_COLOR)
    canvas.pack_configure(expand=True, fill='both')
    canvas.setvar(GAME_IS_RUNNING)
    canvas.setvar(BALL_IS_MOVING)
    canvas.update()
    paddle_width, paddle_height = 150, 10
    paddle_x, paddle_y = (canvas.winfo_width() -
                          paddle_width) // 2, canvas.winfo_height() - 300
    paddle_id = canvas.create_rectangle(paddle_x,
                                        paddle_y,
                                        paddle_x + paddle_width,
                                        paddle_y + paddle_height,
                                        width=0,
                                        fill=SPRITE_COLOR)
    paddle_vx = 8
    canvas.bind_all(KEY_LEFT, move_paddle_left(canvas, paddle_id, paddle_vx))
    canvas.bind_all(KEY_RIGHT, move_paddle_right(canvas, paddle_id, paddle_vx))
    ball_x, ball_y, ball_r = 455, 300, 15
    ball_id = canvas.create_oval(ball_x,
                                 ball_y,
                                 ball_x + 2 * ball_r,
                                 ball_y + 2 * ball_r,
                                 width=0,
                                 fill=SPRITE_COLOR)
    ball_vx, ball_vy = uniform(-3, -1), uniform(-4, -2)
    delay = 10
    canvas.after(
        0,
        move_ball(canvas, ball_id, paddle_id, choice([ball_vx, -ball_vx]),
                  ball_vy, delay))
    canvas.after(0, check_fall(tk, canvas, ball_id, delay))
Exemplo n.º 21
0
def _init_audio_stream():
    global AUDIO_LIBRARY

    init()
    music.set_volume(VOLUME)

    # Get music files in dir
    AUDIO_LIBRARY = [
        '{}{}{}'.format(MUSIC_DIR, sep, music_file)
        for music_file in listdir(MUSIC_DIR) if music_file.endswith('.mp3')
    ]
    shuffle(AUDIO_LIBRARY)

    if len(AUDIO_LIBRARY) == 0:
        raise RuntimeError(
            'No MP3 files found in directory: {}'.format(MUSIC_DIR))

    # Load first song and queue up others
    schedule_next()
Exemplo n.º 22
0
 def update(self, time):
     if self._filename is None: pass
     elif time < self._start_time: pass
     elif not self._playing:
         try:
             music.stop()
             music.load(self._filename)
             music.set_volume(0.01)  # 0.0 stops pygame.mixer.music.
             # Workaround for a pygame/libsdl mixer bug.
             #music.play(0, self._start)
             music.play(0, 0)
             self._playing = True
         except:  # Filename not found? Song is too short? SMPEG blows?
             music.stop()
             self.playing = False
     elif time < self._start_time + 1000:  # mixer.music can't fade in
         music.set_volume((time - self._start_time) / 1000.0)
     elif time > self._end_time - 1000:
         music.fadeout(1000)
         self._playing = False
         self._filename = None
Exemplo n.º 23
0
 def update(self, time):
   if self._filename is None: pass
   elif time < self._start_time: pass
   elif not self._playing:
     try:
       music.stop()
       music.load(self._filename)
       music.set_volume(0.01) # 0.0 stops pygame.mixer.music.
       # Workaround for a pygame/libsdl mixer bug.
       #music.play(0, self._start)
       music.play(0, 0)
       self._playing = True
     except: # Filename not found? Song is too short? SMPEG blows?
       music.stop()
       self.playing = False
   elif time < self._start_time + 1000: # mixer.music can't fade in
     music.set_volume((time - self._start_time) / 1000.0)
   elif time > self._end_time - 1000:
     music.fadeout(1000)
     self._playing = False
     self._filename = None
Exemplo n.º 24
0
 def redraw(self):
   for i in range(self.height - 1):
     for j in range(self.width - 1):
       # Figure out what to draw
       intensity = self.get_intensity(i, j)
       particle = self.get_particle(intensity)
       color = self.get_color(intensity)
       # Where to draw it
       y = (self.height-1) - i
       self.screen.addch(y, j, particle, color)
       # Save for the next iteration
       self.prev_fire[i][j] = int(intensity)
   ch = self.screen.getch()
   if ch != curses.ERR:
     if ch == ord('-') and self.volume != 0.0:
       self.volume = self.volume - .10
       music.set_volume(self.volume)
     elif ch == ord('+') and self.volume != 1.0:
       self.volume = self.volume + .10
       music.set_volume(self.volume)
   self.screen.refresh()
   self.screen.timeout(50)
   time.sleep(1.0 / self.speed)
Exemplo n.º 25
0
    def __init__(self):
        self.dt = 0
        self.timer = 0  # 1seconde
        self.timer_gen_e = 0
        self.timer_event = 0  # 1seconde
        self.menu_timer = 0

        self.last_update = 0

        pygame.mixer.pre_init(frequency=22050,
                              size=-16,
                              channels=2,
                              buffer=1024)
        pygame.init()
        pygame.mixer.set_num_channels(64)
        pygame.mixer.init()

        # Set input frequency
        pygame.key.set_repeat(1, 1)

        # This is a list of every sprite.
        self.all_sprites = pygame.sprite.Group()

        self.sprites_level_backgrounds = pygame.sprite.Group()
        self.sprites_level_menu_backgrounds = pygame.sprite.Group()
        self.sprites_main_menu_backgrounds = pygame.sprite.Group()

        self.sprites_level_text = pygame.sprite.Group()
        self.sprites_level_menu_text = pygame.sprite.Group()
        self.sprites_main_menu_text = pygame.sprite.Group()

        self.sprites_players = pygame.sprite.Group()
        self.sprites_enemies = pygame.sprite.Group()
        self.sprites_items = pygame.sprite.Group()

        self.sprites_allies_shoots = pygame.sprite.Group()
        self.sprites_enemies_shoots = pygame.sprite.Group()
        #		self.sprites_neutrals_list = pygame.sprite.Group()

        self.sprites_explosions = pygame.sprite.Group()

        # self.sprites_hitbox = pygame.sprite.Group()

        self.sound_explosion = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'explosion42.wav'))
        self.sound_shoot = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'laser51.wav'))

        self.sound_move_cursor = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'cursor.wav'))
        self.sound_launch_game = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'launch_game_iceball.wav'))
        self.sound_select = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'select_flaunch.wav'))
        self.sound_off = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'off_Close.wav'))
        self.sound_on = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'on_Open.wav'))
        self.sound_return = pygame.mixer.Sound(
            os.path.join(sounds_folder, 'back_Wrong_2.wav'))

        # self.music_channel_level = pygame.mixer.Channel(0)
        # self.music_channel_main_menu = pygame.mixer.Channel()
        self.opt_music = False
        self.opt_sfx = True
        self.opt_autoshoot = True

        self.speed_game = NORMAL_SPEED_GAME

        music.load(os.path.join(sounds_folder, 'main_menu_music.wav'))
        music.set_volume(100)
        music.play(-1)
        if (self.opt_music is False):
            music.pause()

        # self.music_level = pygame.mixer.Sound(os.path.join(media_folder, 'game_music.wav'))
        # self.music_main_menu = pygame.mixer.music.load(os.path.join(media_folder, 'main_menu_music.wav'))

        # self.music_channel_level.load(self.music_level)
        # self.music_main_menu.play(-1)

        # self.sound_shoot = []
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser42.wav')))
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser43.wav')))
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser44.wav')))
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser45.wav')))
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser46.wav')))
        # self.sound_shoot.append(pygame.mixer.Sound(os.path.join(media_folder, 'laser47.wav')))

        self.window = pygame.display.set_mode(
            (X_WINDOW, Y_WINDOW), HWSURFACE | DOUBLEBUF)  # | RESIZABLE)
        self.window_rect = self.window.get_rect()
        self.icone = IMG_PLAYER.convert_alpha()
        self.title = pygame.display.set_caption("BEST GAME EVER -- Py_SHMUP")

        self.mode = F_MAIN_MENU
        self.previous_mode = F_MAIN_MENU

        self.explosion_imgs = []
        self.explosion_imgs.append(
            self.load_sprites(IMG_EXPLOSION1,
                              width=256,
                              height=256,
                              ratio=1 / 3))
        self.explosion_imgs.append(
            self.load_sprites(IMG_EXPLOSION2,
                              width=256,
                              height=256,
                              ratio=1 / 2))
        self.explosion_imgs.append(
            self.load_sprites(IMG_EXPLOSION3,
                              width=256,
                              height=256,
                              ratio=1 / 2))

        # Init Player:
        self.player = Player(self)

        # Init all backgrounds:
        self.level_backgrounds = Level_backgrounds(self)
        self.level_menu_backgrounds = Level_menu_backgrounds(self)
        self.main_menu_backgrounds = Main_menu_backgrounds(self)

        # Init all Menu:
        self.level_text = Text_level(self)
        self.level_menu = Level_menu(self)
        self.main_menu = Main_menu(self)
        self.death_menu = Death_menu(self)
        self.gameover_menu = Gameover_menu(self)
        self.opt_level_menu = Opt_level_menu(self)
Exemplo n.º 26
0
def dance(screen, song, players, prevscr, ready_go, game):
  songFailed = False

  # text group, e.g. judgings and combos
  tgroup =  RenderUpdates()
  # lyric display group
  lgroup = RenderUpdates()

  background = pygame.Surface([640, 480])

  if song.movie != None:
    backmovie = BGMovie(song.movie)
  else:
    backmovie = None
    
  background.fill(colors.BLACK)
  screen.fill(colors.BLACK)

  if ready_go:
    ready_go_time = min(100, *[plr.ready for plr in players])
    tgroup.add(ReadyGoSprite(ready_go_time))
  
  if mainconfig['showbackground'] > 0:
    if backmovie is None:
      bgkludge = pygame.image.load(song.background).convert()
      bgkrect = bgkludge.get_rect()
      if (bgkrect.size[0] == 320) and (bgkrect.size[1] == 240):
        bgkludge = pygame.transform.scale2x(bgkludge)
      else:
        bgkludge = pygame.transform.scale(bgkludge, [640, 480])
      bgkludge.set_alpha(mainconfig['bgbrightness'], RLEACCEL)
      
      q = mainconfig['bgbrightness'] / 256.0
      # FIXME
      for i in range(0, 101, 5):
        p = i / 100.0
        prevscr.set_alpha(256 * (1 - p) * q, RLEACCEL)
        screen.fill(colors.BLACK)
        screen.blit(prevscr, [0, 0])
        screen.blit(bgkludge, [0, 0])
        pygame.display.update()
        pygame.time.delay(1)

      background.blit(bgkludge, [0, 0])
    else:
      pygame.display.update()
  else:
    pygame.display.update()

  if mainconfig["strobe"]: tgroup.add(Blinky(song.bpm))

  if mainconfig["fpsdisplay"]:
    fpstext = FPSDisp()
    timewatch = TimeDisp()
    tgroup.add([fpstext, timewatch])
  else: fpstext = None

  if mainconfig['showlyrics']:
    lgroup.add(song.lyricdisplay.channels())

  fontfn, basesize = FontTheme.Dance_title_artist
  songtext = fontfx.zztext(song.title, 480, 12, basesize, fontfn)
  grptext = fontfx.zztext(song.artist, 160, 12, basesize, fontfn)

  songtext.zin()
  grptext.zin()

  tgroup.add([songtext, grptext])

  song.init()

  if song.crapout != 0:
    error.ErrorMessage(screen, _("The audio file for this song ") +
                       song.filename + _(" could not be found."))
    return False # The player didn't fail.

  if mainconfig['assist']: music.set_volume(0.6)
  else: music.set_volume(1.0)

  song.play()
  for plr in players: plr.start_song()

  autofail = mainconfig['autofail']

  screenshot = False
  pad.empty()

  while True:
    if autofail:
      songFailed = True
      for plr in players:
        if not plr.lifebar.gameover:
          songFailed = False
          break
      if songFailed:
        song.kill()

    for plr in players: plr.get_next_events(song)

    if song.is_over(): break
    else: curtime = music.get_pos()/1000.0

    key = []

    ev = pad.poll()

    for i in range(len(players)):
      if (pad.states[(i, pad.START)] and pad.states[(i, pad.SELECT)]):
        ev = (0, pad.QUIT)
        break
      else:
        pass

    while ev[1] != pad.PASS:
      if ev[1] == pad.QUIT:
        for p in players: p.escaped = True
        break
      elif ev[1] == pad.SCREENSHOT:
        screenshot = True
      elif ev[1] == pad.LEFT: key.append((ev[0], 'l'))
      elif ev[1] == pad.DOWNLEFT: key.append((ev[0], 'w'))
      elif ev[1] == pad.UPLEFT: key.append((ev[0], 'k'))
      elif ev[1] == pad.RIGHT: key.append((ev[0], 'r'))
      elif ev[1] == pad.UPRIGHT: key.append((ev[0], 'z'))
      elif ev[1] == pad.DOWNRIGHT: key.append((ev[0], 'g'))
      elif ev[1] == pad.UP: key.append((ev[0], 'u'))
      elif ev[1] == pad.DOWN: key.append((ev[0], 'd'))
      elif ev[1] == pad.CENTER: key.append((ev[0], 'c'))

      ev = pad.poll()

    if ev[1] == pad.QUIT: return False
  
    for ev in key:
      if game.double: pid = ev[0] / 2
      else: pid = ev[0]
      
      if pid < len(players): players[pid].handle_key(ev, curtime)

    rectlist = []

    if backmovie:
      backmovie.update(curtime)
      if backmovie.changed or (fpstext.fps() > 30):
        backmovie.resetchange()
        screen.blit(backmovie.image, [0, 0])

    for plr in players: rectlist.extend(plr.game_loop(curtime, screen))

    lgroup.update(curtime)
    tgroup.update(curtime)
    rectlist.extend(tgroup.draw(screen))
    rectlist.extend(lgroup.draw(screen))

    if backmovie is None: pygame.display.update(rectlist)
    else: pygame.display.update()

    if screenshot:
      fn = os.path.join(rc_path, "screenshot.bmp")
      print _("Saving a screenshot to"), fn
      pygame.image.save(screen, fn)
      screenshot = False

    if backmovie is None:
      lgroup.clear(screen, background)
      tgroup.clear(screen, background)
      for plr in players: plr.clear_sprites(screen, background)

    if ((curtime > players[0].length - 1) and
        (songtext.zdir == 0) and (songtext.zoom > 0)):
      songtext.zout()
      grptext.zout()

  if fpstext: print _("Average FPS for this song was %d.") % fpstext.fps()
  return songFailed
Exemplo n.º 27
0
    def __init__(self, songs, courses, screen, game):

        InterfaceWindow.__init__(self, screen, "newss-bg.png")
        songs = [s for s in songs if s.difficulty.has_key(game)]

        if len(songs) == 0:
            error.ErrorMessage(
                screen,
                _("You don't have any songs for the game mode (") + game +
                _(") that you selected.")
            )  #TODO: format using % for better i18n
            return

        # Construct a mapping between songs displays and dance displays.
        songs_and_dances = [
            (SongItemDisplay(s, game),
             [DanceItemDisplay(s, game, diff) for diff in s.diff_list[game]])
            for s in songs
        ]

        for (s, ds) in songs_and_dances:
            for d in ds:
                s.danceitems[d.diff] = d
                d.songitem = s

        self._songs = [s[0] for s in songs_and_dances]
        self._dances = reduce(lambda x, y: x + y[1], songs_and_dances, [])

        self._index = 0
        self._game = game
        self._config = dict(game_config)
        self._all_songs = self._songs
        self._all_dances = self._dances
        self._all_valid_songs = [s for s in self._songs if s.info["valid"]]
        self._all_valid_dances = [d for d in self._dances if d.info["valid"]]

        self._list = ListBox(FontTheme.SongSel_list, [255, 255, 255], 26, 16,
                             220, [408, 56])
        # please use set constructions after python 2.4 is adopted
        sort_name = self._update_songitems()

        if mainconfig["folders"]:
            self._create_folders()
            self._create_folder_list()
        else:
            self._folders = None
            self._base_text = sort_name.upper()

            self._songitems.sort(key=SORTS[sort_name])
            self._list.set_items([s.info["title"] for s in self._songitems])

        self._preview = SongPreview()
        self._preview.preview(self._songitems[self._index])
        self._song = self._songitems[self._index]

        # Both players must have the same difficulty in locked modes.
        self._locked = games.GAMES[self._game].couple

        players = games.GAMES[game].players
        #    self._diffs = [] # Current difficulty setting
        self._diff_widgets = []  # Difficulty widgets
        self._configs = []
        self._diff_names = []  # Current chosen difficulties
        self._pref_diff_names = []  # Last manually selected difficulty names
        self._last_player = 0  # Last player to change a difficulty

        for i in range(players):
            self._configs.append(dict(player_config))
            d = DifficultyBox([84 + (233 * i), 434])
            self._pref_diff_names.append(util.DIFFICULTY_LIST[0])
            if not self._song.isfolder:
                self._diff_names.append(self._song.diff_list[0])
                diff_name = self._diff_names[i]
                rank = records.get(self._song.info["recordkey"], diff_name,
                                   self._game)[0]
                grade = grades.grades[self._config["grade"]].grade_by_rank(
                    rank)
                d.set(diff_name, DIFF_COLORS.get(diff_name, [127, 127, 127]),
                      self._song.difficulty[diff_name], grade)
            else:
                self._diff_names.append(" ")
                d.set(_("None"), [127, 127, 127], 0, "?")
            self._diff_widgets.append(d)

        ActiveIndicator([405, 259], width=230).add(self._sprites)
        self._banner = BannerDisplay([205, 230])
        self._banner.set_song(self._song)
        self._sprites.add(
            HelpText(SS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help,
                     [206, 20]))

        self._title = TextDisplay('SongSel_sort_mode', [210, 28], [414, 27])
        self._sprites.add(self._diff_widgets +
                          [self._banner, self._list, self._title])
        self._screen.blit(self._bg, [0, 0])
        pygame.display.update()
        self.loop()
        music.fadeout(500)
        pygame.time.wait(500)
        # FIXME Does this belong in the menu code? Probably.
        music.load(os.path.join(sound_path, "menu.ogg"))
        music.set_volume(1.0)
        music.play(4, 0.0)
        player_config.update(self._configs[0])  # Save p1's settings
        game_config.update(self._config)  # save game settings
Exemplo n.º 28
0
#For more Information on pyttsx3 refer to this link - https://pyttsx3.readthedocs.io/en/latest/engine.html

###############Get the Computer Name
computer_name = platform.node()

#Create Speech Recognizer Object
#For more Information on Speech Recognizer refer to this link - https://pypi.org/project/SpeechRecognition/
r = sr.Recognizer()

################## Background Music Part
#Mixer Initialize
pygame.mixer.init()
#Load the background Music file
music.load("News_Music/news_background_music.mp3")
#Set the Music Volume
music.set_volume(0.1)


#Create a speak function
def speak(text):
    engine.say(text)
    #Run the speech and wait
    engine.runAndWait()


def popular_ai_news(app, var):
    """ Scrap the News headlines from website and speak """
    while True:
        try:
            #Check the Internet Connection
            socket.create_connection(("Google.com", 80))
Exemplo n.º 29
0
def dance(screen, song, players, prevscr, ready_go, game):
    songFailed = False

    # text group, e.g. judgings and combos
    tgroup = RenderUpdates()
    # lyric display group
    lgroup = RenderUpdates()

    background = pygame.Surface([640, 480])

    if song.movie != None:
        backmovie = BGMovie(song.movie)
    else:
        backmovie = None

    background.fill(colors.BLACK)
    screen.fill(colors.BLACK)

    if ready_go:
        ready_go_time = min(100, *[plr.ready for plr in players])
        tgroup.add(ReadyGoSprite(ready_go_time))

    if mainconfig['showbackground'] > 0:
        if backmovie is None:
            bgkludge = pygame.image.load(song.background).convert()
            bgkrect = bgkludge.get_rect()
            if (bgkrect.size[0] == 320) and (bgkrect.size[1] == 240):
                bgkludge = pygame.transform.scale2x(bgkludge)
            else:
                bgkludge = pygame.transform.scale(bgkludge, [640, 480])
            bgkludge.set_alpha(mainconfig['bgbrightness'], RLEACCEL)

            q = mainconfig['bgbrightness'] / 256.0
            # FIXME
            for i in range(0, 101, 5):
                p = i / 100.0
                prevscr.set_alpha(256 * (1 - p) * q, RLEACCEL)
                screen.fill(colors.BLACK)
                screen.blit(prevscr, [0, 0])
                screen.blit(bgkludge, [0, 0])
                pygame.display.update()
                pygame.time.delay(1)

            background.blit(bgkludge, [0, 0])
        else:
            pygame.display.update()
    else:
        pygame.display.update()

    if mainconfig["strobe"]: tgroup.add(Blinky(song.bpm))

    if mainconfig["fpsdisplay"]:
        fpstext = FPSDisp()
        timewatch = TimeDisp()
        tgroup.add([fpstext, timewatch])
    else:
        fpstext = None

    if mainconfig['showlyrics']:
        lgroup.add(song.lyricdisplay.channels())

    fontfn, basesize = FontTheme.Dance_title_artist
    songtext = fontfx.zztext(song.title, 480, 12, basesize, fontfn)
    grptext = fontfx.zztext(song.artist, 160, 12, basesize, fontfn)

    songtext.zin()
    grptext.zin()

    tgroup.add([songtext, grptext])

    song.init()

    if song.crapout != 0:
        error.ErrorMessage(
            screen,
            _("The audio file for this song ") + song.filename +
            _(" could not be found."))
        return False  # The player didn't fail.

    if mainconfig['assist']: music.set_volume(0.6)
    else: music.set_volume(1.0)

    song.play()
    for plr in players:
        plr.start_song()

    autofail = mainconfig['autofail']

    screenshot = False
    ui.ui.clear()

    while True:
        if autofail:
            songFailed = True
            for plr in players:
                if not plr.lifebar.gameover:
                    songFailed = False
                    break
            if songFailed:
                song.kill()

        for plr in players:
            plr.get_next_events(song)

        if song.is_over(): break
        else: curtime = music.get_pos() / 1000.0

        key = []

        ev = ui.ui.poll_dance()

        while ev[1] != ui.PASS:
            if ev[1] == ui.CANCEL:
                for p in players:
                    p.escaped = True
                return False
            elif ev[1] == ui.SCREENSHOT:
                screenshot = True
            elif ev[1] == ui.LEFT:
                key.append((ev[0], 'l'))
            elif ev[1] == ui.DOWNLEFT:
                key.append((ev[0], 'w'))
            elif ev[1] == ui.UPLEFT:
                key.append((ev[0], 'k'))
            elif ev[1] == ui.RIGHT:
                key.append((ev[0], 'r'))
            elif ev[1] == ui.UPRIGHT:
                key.append((ev[0], 'z'))
            elif ev[1] == ui.DOWNRIGHT:
                key.append((ev[0], 'g'))
            elif ev[1] == ui.UP:
                key.append((ev[0], 'u'))
            elif ev[1] == ui.DOWN:
                key.append((ev[0], 'd'))
            elif ev[1] == ui.CENTER:
                key.append((ev[0], 'c'))
            elif ev[1] == -ui.LEFT:
                key.append((ev[0], '-l'))
            elif ev[1] == -ui.DOWNLEFT:
                key.append((ev[0], '-w'))
            elif ev[1] == -ui.UPLEFT:
                key.append((ev[0], '-k'))
            elif ev[1] == -ui.RIGHT:
                key.append((ev[0], '-r'))
            elif ev[1] == -ui.UPRIGHT:
                key.append((ev[0], '-z'))
            elif ev[1] == -ui.DOWNRIGHT:
                key.append((ev[0], '-g'))
            elif ev[1] == -ui.UP:
                key.append((ev[0], '-u'))
            elif ev[1] == -ui.DOWN:
                key.append((ev[0], '-d'))
            elif ev[1] == -ui.CENTER:
                key.append((ev[0], '-c'))

            ev = ui.ui.poll_dance()

        for ev in key:
            if game.double: pid = ev[0] / 2
            else: pid = ev[0]

            if pid >= 0 and pid < len(players):
                if ev[1][0] != '-':
                    players[pid].handle_keydown(ev, curtime)
                else:
                    players[pid].handle_keyup((ev[0], ev[1][1:]), curtime)

        rectlist = []

        if backmovie:
            backmovie.update(curtime)
            if backmovie.changed or (fpstext.fps() > 30):
                backmovie.resetchange()
                screen.blit(backmovie.image, [0, 0])

        for plr in players:
            rectlist.extend(plr.game_loop(curtime, screen))

        lgroup.update(curtime)
        tgroup.update(curtime)
        rectlist.extend(tgroup.draw(screen))
        rectlist.extend(lgroup.draw(screen))

        if backmovie is None: pygame.display.update(rectlist)
        else: pygame.display.update()

        if screenshot:
            fn = os.path.join(rc_path, "screenshot.bmp")
            print(_("Saving a screenshot to"), fn)
            pygame.image.save(screen, fn)
            screenshot = False

        if backmovie is None:
            lgroup.clear(screen, background)
            tgroup.clear(screen, background)
            for plr in players:
                plr.clear_sprites(screen, background)

        if ((curtime > players[0].length - 1) and (songtext.zdir == 0)
                and (songtext.zoom > 0)):
            songtext.zout()
            grptext.zout()

    if fpstext: print(_("Average FPS for this song was %d.") % fpstext.fps())
    return songFailed
Exemplo n.º 30
0
    def do(self,argument):
        Map.readMap(argument[0],argument[1])
        readMusic()
        
        self.register=[]
        if MAPINFO:
            print(vars(Map.songMap))

        background=loadBackground()
        reg=Register((self.size-background.get_size())//2,surface=background)
        self.register.append(reg)

        trace['Width']=trace['Skin'][0].get_size()[0]
        for i in range(trace['Number']): #根據先前設定好的軌道數量,利用相對位置生成整齊的軌道圖片
            if i==0:
                reg=Animation(((self.size[0]-trace['BoxWidth']*(trace['Number']-1)-trace['Number']*trace['Width'])//2,0),surface=trace['Skin'][0])
            else:
                reg=Animation((self.register[-1].rect.topright[0]+trace['BoxWidth'],0),surface=trace['Skin'][0])
            reg.animation(trace['Skin'])
            self.register.append(reg)
        TraceSkin=self.register[-trace['Number']::]#保存位置,以後方便使用

        #生成判定線
        reg=Register((TraceSkin[0].rect.topleft[0],trace['Judge']),(TraceSkin[-1].rect.topright[0]-TraceSkin[0].rect.topleft[0],5))
        reg.surface.fill(trace['Color'])
        self.register.append(reg)
        TraceJudge=self.register[-1]
        TraceJudgeLineY=TraceJudge.rect.centery

        #生成掉落方塊
        note=pygame.image.load_extended(path.join(skinDir,'mania-note1.png')).convert_alpha()
        noteX,noteY=note.get_size()
        hnote=pygame.image.load_extended(path.join(skinDir,'mania-note1L-0.png')).convert_alpha()
        hnote=pygame.transform.scale(hnote,(TraceSkin[0].size[0]//2,1))
        noteType={
            'Hold':0,
            'Down':1,
            'Up':2
        }
        hnoteX,hnoteY=hnote.get_size()
        hnoteD=2*trace['Speed']

        area=TraceJudge.size
        reg=Register(((self.size[0]-area[0])//2,0),(area[0],self.size[1]))
        self.register.append(reg)
        Notes=self.register[-1]

        mania300=[pygame.image.load_extended(path.join(skinDir,'hit300-'+str(i)+ '.png')).convert_alpha() for i in range(30)]
        mania100=[pygame.image.load_extended(path.join(skinDir,'hit100-'+str(i)+ '.png')).convert_alpha() for i in range(30)]
        mania50=[pygame.image.load_extended(path.join(skinDir,'hit50-'+str(i)+ '.png')).convert_alpha() for i in range(30)]
        mania0=[pygame.image.load_extended(path.join(skinDir,'hit0-'+str(i)+ '.png')).convert_alpha() for i in range(35)]

        #設定擊中時的動畫效果
        for i in range(trace['Number']):
            reg=AnimationMultipleEffectCenter((TraceSkin[i].rect.center[0],trace['Judge']))
            reg.animation(mania300)
            reg.animation(mania100)
            reg.animation(mania50)
            reg.animation(mania0)
            self.register.append(reg)
        TracePoint=self.register[-trace['Number']:]

        moveTime=1500/trace['Speed']#設定物體掉落的速度(EX:若1倍速,則物體掉落的時間為1.5sec)
        music.set_volume(Map.songMap.timing_points[0].volume/100)            
        
        hit_obj=Map.songMap._hit_objects.copy()#copy掉落物件的屬性
        hit_obj.reverse()#把list反轉,提高讀取速度(由最後一個往前讀取)
        hit_objTime=hit_obj[-1].time.total_seconds()*1000
        
        timeBoard={'Perfect':75,'Great':150,'Good':350,'Miss':500}
        scoreBoard={'Perfect':0,'Great':0,'Good':0,'Miss':0,'Combo':[0]}
        comboBoard=ScoreBoard()#顯示連擊數
        comboBoard.color=(0,255,255)
        self.register.append(comboBoard)

        self.KEY=[True for i in range(trace['Number'])]
        music.play()
        music.set_endevent(MUSIC_END)
        while 1:
            time=music.get_pos()
            NotesClear=[]
            event_get=pygame.fastevent.get()
            for event in event_get:
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if not AUTO:
                        if event.unicode in trace['BtnKey']:#取得以設定的按鍵值(EX: D F J K)
                            index=trace['BtnKey'][event.unicode] #把值給變數index
                            TraceSkin[index].frame=1
                            if self.KEY[index]:
                                for i,v in enumerate(Notes.register):
                                    if v.trace != index or v.type != noteType['Down']:
                                        continue
                                    for i0,k in enumerate(timeBoard.keys()):
                                        if -timeBoard[k]<=time-v.time<=timeBoard[k]:#判斷按下去時,是得到perfect great good miss
                                            if k!='Miss':
                                                scoreBoard['Combo'][-1]+=1 #增加combo
                                            else: #結束combo
                                                scoreBoard['Combo'][-1]=int(scoreBoard['Combo'][-1])
                                                scoreBoard['Combo'].append(0)
                                            if scoreBoard['Combo'][-1]>0: #有combo才顯示combo數
                                                comboBoard.content=str(int(scoreBoard['Combo'][-1]))
                                            TracePoint[index].begin(i0)
                                            scoreBoard[k]+=1
                                            NotesClear.append(i)
                                            break
                                    else:
                                        continue
                                    break
                                self.KEY[index]=False
                    if event.unicode =='\x1b':
                        music.stop()
                        return
                if event.type==KEYUP:
                    if not AUTO:
                        if event.unicode in trace['BtnKey']:
                            index=trace['BtnKey'][event.unicode]
                            TraceSkin[index].frame=0
                            self.KEY[index]=True
                            for i,v in enumerate(Notes.register):
                                if v.trace!=index: 
                                    continue
                                if v.type!=noteType['Up']:
                                    break
                                for i0,k in enumerate(timeBoard.keys()):
                                    if -timeBoard[k]<=time-v.time<=timeBoard[k]:
                                        if k!='Miss':
                                            scoreBoard['Combo'][-1]+=1
                                        else:
                                            scoreBoard['Combo'][-1]=int(scoreBoard['Combo'][-1])
                                            scoreBoard['Combo'].append(0)
                                        if scoreBoard['Combo'][-1]>0:
                                            comboBoard.content=str(int(scoreBoard['Combo'][-1]))
                                        TracePoint[index].begin(i0)
                                        scoreBoard[k]+=1
                                        NotesClear.append(i)
                                        break
                                else:
                                    continue
                                break
                            TracePoint[index].end()

                if event.type == music.get_endevent():
                    print(scoreBoard)
                    return
                if EVENT_PRINT:
                    print(event)

            def compute(dt): #計算位置
                return TraceJudgeLineY*dt//moveTime

            if AUTO:
                for index in range(trace['Number']):
                    for i,v in enumerate(Notes.register):
                        k='Perfect'
                        if v.type==noteType['Hold'] and time>=v.starttime:
                            length=compute(v.endtime-time)
                            v.surface.set_clip(pygame.Rect((0,0),(v.size[0],length)))
                        if v.trace==index and time>=v.endtime:
                            scoreBoard['Combo'][-1]+=1
                            comboBoard.content=str(int(scoreBoard['Combo'][-1]))
                            TracePoint[index].trigger(0)
                            scoreBoard[k]+=1
                            NotesClear.append(i)


            if len(hit_obj)>0 and time>hit_objTime-moveTime:
                t=assignTrace(hit_obj[-1].position[0])  #取得軌道
                length=TraceJudgeLineY-compute(hit_objTime-time)
                pos=TraceSkin[t].rect.centerx-Notes.pos[0]
                if type(hit_obj[-1]) is slider.beatmap.HoldNote:#判斷現在讀取的hit_obj屬性是否為hold_note,然後生成出register
                    endtime=eval(hit_obj[-1].addition.split(':')[0])
                    endlength=TraceJudgeLineY-compute(endtime-time)
                    totalL=int((length-endlength))
                    reg=Register((pos-hnoteX//2,totalL-hnoteY//2),surface=pygame.transform.scale(hnote,(hnoteX,totalL)))
                    reg.starttime=hit_objTime
                    reg.endtime=endtime
                    reg.time=(reg.starttime+endtime)//2
                    reg.height=reg.rect.centery
                    reg.trace=t
                    reg.type=noteType['Hold']
                    Notes.register.append(reg)
                    reg=Register((pos-noteX//2,length-noteY//2),surface=note)
                    reg.starttime=hit_objTime
                    reg.endtime=hit_objTime
                    reg.time=hit_objTime
                    reg.height=reg.rect.centery
                    reg.trace=t
                    reg.type=noteType['Down']
                    Notes.register.append(reg)
                    reg=Register((pos-noteX//2,endlength-noteY//2),surface=note)
                    reg.starttime=endtime
                    reg.endtime=endtime
                    reg.time=endtime
                    reg.height=reg.rect.centery
                    reg.trace=t
                    reg.type=noteType['Up']
                    Notes.register.append(reg)
                else:   #判斷現在讀取的hit_obj屬性是否為note,然後生成出register
                    reg=Register((TraceSkin[t].rect.centerx-noteX//2-Notes.pos[0],length-noteY//2),surface=note)
                    reg.starttime=hit_objTime
                    reg.endtime=hit_objTime
                    reg.time=hit_objTime
                    reg.height=reg.rect.centery
                    reg.trace=t
                    reg.type=noteType['Down']
                    Notes.register.append(reg)
                hit_obj.pop()
                try: #先嘗試計算下一個欲掉落物件的時間
                    hit_objTime=hit_obj[-1].time.total_seconds()*1000
                except:
                    pass
            for index,key in enumerate(self.KEY):
                TracePoint[index].update(10)
                if not key: #如果按鍵按下
                    for i,v in enumerate(Notes.register):
                        if v.trace!=index or v.type != noteType['Hold']: #判斷掉落物件是否為hold屬性
                            continue
                        if v.type==noteType['Hold'] and time>=v.starttime:
                            length=TraceJudgeLineY*(v.endtime-time)//moveTime
                            v.surface.set_clip(pygame.Rect((0,0),(v.size[0],length))) #把超出範圍的圖形,利用set_clip切割掉不顯示
                        if time >v.endtime:
                            TracePoint[index].trigger(0) #觸發特效(0代表perfect)
                            NotesClear.append(i) #把要刪除的index丟入垃圾桶
                            break
            for i,v in enumerate(Notes.register): #判定掉落物件是否超出判定線
                v.rect.centery=TraceJudgeLineY-compute(v.time-time)
                if  v.rect.centery>=TraceJudge.rect.centery and time-v.endtime>timeBoard['Miss']: #判定物件位置超出Miss的預設值
                    scoreBoard['Miss']+=1
                    if scoreBoard['Combo'][-1]>0:scoreBoard['Combo'].append(0) #combo設定為0
                    comboBoard.content=""
                    NotesClear.append(i)

            NotesClear.sort(reverse=1) #把欲清除的list排列
            for i in NotesClear: 
                del Notes.register[i] #清理垃圾桶

            comboBoard.pos=(self.size-comboBoard.size)//2 #置中comboBoard
            comboBoard.update()
            
            Notes.clear()
            Notes.blit()

            
            if not all(self.size-screen.get_size()):#判斷self.size與預設大小1366*768是否相同,若相同則直接把內容顯示出來
                screen.fill((128,128,128))
                screen.blits([(sur.surface,sur.pos,sur.surface.get_clip(),BLEND_ALPHA_SDL2) for sur in self.register])
            else:#調整視窗大小,避免因調整而座標系統跑掉
                self.clear()
                self.blit()
                BlitToWindow(self.surface)
            pygame.display.flip()
Exemplo n.º 31
0
 def set_volume(volume):
     music.set_volume(volume)
Exemplo n.º 32
0
def mute_volume(m):
    music.set_volume(m)
Exemplo n.º 33
0
 def set_volume(self,volume):
     volume = float(volume) 
     music.set_volume(volume)
Exemplo n.º 34
0
 def set_volume(self, volume):
     self._logger.info('Setting volume to %d', volume)
     music.set_volume(volume)
     self.volume = volume
Exemplo n.º 35
0
 def mouse_drag(self, e):
     m = self.margin
     w = self.width - 2 * m
     x = max(0.0, min(1.0, (e.local[0] - m) / w))
     music.set_volume(x)
     self.invalidate()
Exemplo n.º 36
0
  def __init__(self, songs, courses, screen, game):

    InterfaceWindow.__init__(self, screen, "newss-bg.png")
    songs = [s for s in songs if s.difficulty.has_key(game)]
    
    if len(songs) == 0:
      error.ErrorMessage(screen, _("You don't have any songs for the game mode (")
                         + game + _(") that you selected.")) #TODO: format using % for better i18n
      return


    # Construct a mapping between songs displays and dance displays.
    songs_and_dances = [(SongItemDisplay(s, game),
                         [DanceItemDisplay(s, game, diff) for diff in s.diff_list[game]])
                        for s in songs]

    for (s,ds) in songs_and_dances:
      for d in ds:
        s.danceitems[d.diff]=d
        d.songitem=s

    self._songs = [s[0] for s in songs_and_dances]
    self._dances = reduce(lambda x,y: x+y[1],songs_and_dances,[])

    self._index = 0
    self._game = game
    self._config = dict(game_config)
    self._all_songs = self._songs
    self._all_dances = self._dances
    self._all_valid_songs = [s for s in self._songs if s.info["valid"]]
    self._all_valid_dances = [d for d in self._dances if d.info["valid"]]

    self._list = ListBox(FontTheme.SongSel_list,
                         [255, 255, 255], 26, 16, 220, [408, 56])
    # please use set constructions after python 2.4 is adopted
    sort_name = self._update_songitems()

    if len(self._songs) > 60 and mainconfig["folders"]:
      self._create_folders()
      self._create_folder_list()
    else:
      self._folders = None
      self._base_text = sort_name.upper()

      self._songitems.sort(key=SORTS[sort_name])
      self._list.set_items([s.info["title"] for s in self._songitems])

    self._preview = SongPreview()
    self._preview.preview(self._songitems[self._index])
    self._song = self._songitems[self._index]

    # Both players must have the same difficulty in locked modes.
    self._locked = games.GAMES[self._game].couple

    players = games.GAMES[game].players
#    self._diffs = [] # Current difficulty setting
    self._diff_widgets = [] # Difficulty widgets
    self._configs = []
    self._diff_names = [] # Current chosen difficulties
    self._pref_diff_names = [] # Last manually selected difficulty names
    self._last_player = 0 # Last player to change a difficulty

    for i in range(players):
      self._configs.append(dict(player_config))
      d = DifficultyBox([84 + (233 * i), 434])
      self._pref_diff_names.append(util.DIFFICULTY_LIST[0])
      if not self._song.isfolder:
        self._diff_names.append(self._song.diff_list[0])
        diff_name = self._diff_names[i]
        rank = records.get(self._song.info["recordkey"],
                           diff_name, self._game)[0]
        grade = grades.grades[self._config["grade"]].grade_by_rank(rank)
        d.set(diff_name, DIFF_COLORS.get(diff_name, [127, 127, 127]),
              self._song.difficulty[diff_name], grade)
      else:
        self._diff_names.append(" ")        
        d.set(_("None"), [127, 127, 127], 0, "?")
      self._diff_widgets.append(d)
    
    ActiveIndicator([405, 259], width = 230).add(self._sprites)
    self._banner = BannerDisplay([205, 230])
    self._banner.set_song(self._song)
    self._sprites.add(HelpText(SS_HELP, [255, 255, 255], [0, 0, 0],
                               FontTheme.help, [206, 20]))

    self._title = TextDisplay('SongSel_sort_mode', [210, 28], [414, 27])
    self._sprites.add(self._diff_widgets +
                      [self._banner, self._list, self._title])
    self._screen.blit(self._bg, [0, 0])
    pygame.display.update()
    self.loop()
    music.fadeout(500)
    pygame.time.wait(500)
    # FIXME Does this belong in the menu code? Probably.
    music.load(os.path.join(sound_path, "menu.ogg"))
    music.set_volume(1.0)
    music.play(4, 0.0)
    player_config.update(self._configs[0]) # Save p1's settings
Exemplo n.º 37
0
 def set_volume(self):
     volume = int(not self.muted)
     music.set_volume(volume)
     if self.current_channel:
         self.current_channel.set_volume(volume)
Exemplo n.º 38
0
 def set_volume(self, volume):
     self._logger.info('Setting volume to %d', volume)
     music.set_volume(volume)
     self.volume = volume
Exemplo n.º 39
0
 def set_volume(self, volume: float):
     music.set_volume(volume)
Exemplo n.º 40
0
def on_off():
    if (music.get_volume() > 0):
        music.set_volume(0)
    elif (music.get_volume() == 0):
        music.set_volume(0.5)
Exemplo n.º 41
0
    #START - SenseHat event handler
    sense = SenseHat()  # semse Hat inicializálása
    # SYSTEMD BugFix
    import signal

    def handler(signum, frame):
        pass

    try:
        signal.signal(signal.SIGHUP, handler)
    except AttributeError:
        pass
    #_________________
    pygame.init()  # pygame importált moduljaninak inicializálása
    mp3.set_volume(vol)  # kezdeti hangerő beállítása
    sense.show_message("Welcome! Lets start listening...",
                       scroll_speed=0.08,
                       text_colour=g,
                       back_colour=b)  # üdvözlő üzenet
    displayH("smile")  # smile jelzi, hogy betöltött a program
    while True:
        acceleration = sense.get_accelerometer_raw(
        )  # gyorsulámérő gyers adatok lekérése
        x = abs(acceleration['x'])
        y = abs(acceleration['y'])
        z = abs(acceleration['z'])
        if x > 2 or y > 2 or z > 2:  # az eszköz "rázásának" érzékelése
            newlogline("==========================================")
            print("==========================================")
            newlogline("Accelerometer triggered shake")