示例#1
0
 def play_click(self, music_file):
     while True:
         if music.get_busy():
             music.stop()
         else:
             break
     t = threading.Thread(target=self.__play, args=[music_file])
     t.start()
示例#2
0
 def start(self, frame_rate):
     self.group.draw(self.screen)
     music.play(-1)
     self.running = True
     while self.running:
         deltaT = self.clock.tick(frame_rate)
         self.update(deltaT)
     if self.music:
         music.stop(self.music)
示例#3
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()
示例#4
0
    def set_music(self, on):
        if not self.has_audio:
            return

        if on and not self.music_on:
            music.play(-1)
            self.music_on = True
        elif not on and self.music_on:
            music.stop()
            self.music_on = False
示例#5
0
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))
            #Send the request to the News website
            base_page = requests.get(
                "https://artificialintelligence-news.com/news/")
            #Extract all page text
            bp_text = bs(base_page.text, 'lxml')
            ####Play Background News Music
            music.play()
            var.set("Hey {}, \nHere is the top Headlines for today".format(
                computer_name))
            app.update()
            speak("Hey {}, Here is the top Headline for today".format(
                computer_name))
            #Create empty list to store news headlines for later use
            saved_headline = []
            #Search all link which under class "widget techforge-post-types"
            for base_links in bp_text.find(
                    "div", {
                        "class": "widget techforge-post-types"
                    }).findAll("a", href=True):
                #Find the top headlines
                headlines = base_links.find("h3")
                if headlines is not None:
                    #print(headlines.text)
                    #Tkinter part
                    var.set(headlines.text)
                    app.update()
                    #Call the speak function
                    speak(headlines.text)
                    #Store the headlines for later use
                    saved_headline.append(headlines.text)
                else:
                    continue
                t.sleep(1)
            #Stop the background music
            music.stop()
        except OSError:
            print("No Internet Connection Found")
            t.sleep(5)
            continue
        #Return the scraped news headline for reuse
        return saved_headline
        app.destroy()
        break
    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])
 def update(self, events):
     self.sprites.update()
     keys = pygame.key.get_pressed()
     if keys[K_q]:
         self.win()
     elif (keys[K_RIGHT] or keys[K_d]) and (keys[K_LEFT] or keys[K_a]):
         pass
     elif keys[K_LEFT] or keys[K_a]:
         self.e_eskimo.rect.x = max(self.e_eskimo.rect.x - 15, 0)
     elif keys[K_RIGHT] or keys[K_d]:
         self.e_eskimo.rect.x = min(locals.WIDTH -57, self.e_eskimo.rect.x + 15)
     for icicle in self.e_icicles:
         if self.e_eskimo.rect.colliderect(icicle.rect):
             music.stop()
             self.lose()
示例#8
0
    def input(self, event, next_state):
        next_state = super(InGame, self).input(event, next_state)

        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                next_state = set_next_state(next_state, STATES.MENU)
            elif event.key == K_m:
                if music.get_busy():
                    music.stop()
                else:
                    music.play()

        self.camera.input(event)
        self.unitmgr.input(event, self.camera, self.mouse_rect, self.tilemgr)
        self.input_mouse(event)

        return next_state
def toggle_controller():
    global IS_STOPPED
    global _NEXT_EVENT

    if IS_STOPPED:
        _init_audio_stream()
        IS_STOPPED = False
    else:
        # Music is playing, stop it
        music.stop()
        quit()

        # Cancel the scheduled thread for the next song
        _NEXT_EVENT.cancel()

        IS_STOPPED = True
        print("Audio {} was stopped.".format(_get_current_song()))
示例#10
0
def set_music_enabled(state):
    global music_enabled
    if music_enabled != state:
        music_enabled = state
        if state:
            # Music pausing doesn't always seem to work.
            #music.unpause()
            if current_music:
                # After stopping and restarting currently loaded music,
                # fadeout no longer works.
                #print "albow.music: reloading", repr(current_music) ###
                music.load(current_music)
                music.play()
            else:
                jog_music()
        else:
            #music.pause()
            music.stop()
示例#11
0
文件: music.py 项目: shaik9/rdrive
def set_music_enabled(state):
    global music_enabled
    if music_enabled != state:
        music_enabled = state
        if state:
            # Music pausing doesn't always seem to work.
            #music.unpause()
            if current_music:
                # After stopping and restarting currently loaded music,
                # fadeout no longer works.
                #print "albow.music: reloading", repr(current_music) ###
                music.load(current_music)
                music.play()
            else:
                jog_music()
        else:
            #music.pause()
            music.stop()
 def jogo(self, jogador):
     observable = self.inicializa_observable()
     self.exibir_musica(self.apljogo.personagem.musicaatual)
     self.apljogo.configuracao()
     self.lmoedas = self.apljogo.cria_bloco_bonus(11, "moeda")
     self.lesqueletos = self.apljogo.cria_bloco_bonus(3, "esqueleto")
     continua = True
     while continua:
         observable.verifica_evento()
         self.apljogo.jogar()
         self.atualiza_tela()
         self.verifica_colisao_obstaculo()
         if self.apljogo.fimdejogo:
             for moeda in self.lmoedas:
                 moeda.ehtangivel = False
             self.aplcadastrarjogador.cadastrar_pontuacao(jogador, self.apljogo.pontos)
             self.exibir_fim_de_jogo()
             continua = self.continuarjogo
     music.stop()
示例#13
0
def LoadGameScreen():
    music.stop()
    load_bar = 0
    loading = True

    while loading:
        CLOCK.tick(144)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        SCREEN.blit(bgLoading, (-240, 0))
        SCREEN.blit(imgLoad, (0, 0))
        pygame.draw.rect(SCREEN, (35, 100, 198), (185, 552, load_bar, 36))
        SCREEN.blit(bgArcadeGame, (0, 0))
        load_bar += 2
        display.update()
        if load_bar >= 632:
            loading = False
    sleep(2)
示例#14
0
def PlayerBusted(background_game1, background_move1, background_game2,
                 background_move2, player, enemies, siren):
    music.stop()
    busted = True
    sfxBusted.play()
    while busted:
        CLOCK.tick(8)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
        SCREEN.blit(background_game1, background_move1)
        player.draw(SCREEN)
        enemies.draw(SCREEN)
        SCREEN.blit(background_game2, background_move2)
        siren.draw(SCREEN)
        SCREEN.blit(imgBusted, (0, 0))
        SCREEN.blit(bgArcadeLose, (0, 0))
        display.update()
        sleep(7)
        busted = False
示例#15
0
 def jogo(self, jogador):
     observable = self.inicializa_observable()
     self.exibir_musica(self.apljogo.personagem.musicaatual)
     self.apljogo.configuracao()
     self.lmoedas = self.apljogo.cria_bloco_bonus(11, "moeda")
     self.lesqueletos = self.apljogo.cria_bloco_bonus(3, "esqueleto")
     continua = True
     while continua:
         observable.verifica_evento()
         self.apljogo.jogar()
         self.atualiza_tela()
         self.verifica_colisao_obstaculo()
         if self.apljogo.fimdejogo:
             for moeda in self.lmoedas:
                 moeda.ehtangivel = False
             self.aplcadastrarjogador.cadastrar_pontuacao(
                 jogador, self.apljogo.pontos)
             self.exibir_fim_de_jogo()
             continua = self.continuarjogo
     music.stop()
示例#16
0
 def preview(self, song):
   if mainconfig["previewmusic"] and not song.isfolder:
     if (song.info["filename"].lower().endswith("mp3") and
         mainconfig["previewmusic"] == 2):
       music.stop()
       self._playing = False
       return
     if len(song.info["preview"]) == 2:
       # A DWI/SM/dance-style preview, an offset in the song and a length
       # to play starting at the offset.
       self._start, length = song.info["preview"]
       self._filename = song.info["filename"]
     else:
       # KSF-style preview, a separate filename to play.
       self._start, length = 0, 100
       self._filename = song.info["preview"]
     if self._playing: music.fadeout(500)
     self._playing = False
     self._start_time = pygame.time.get_ticks() + 500
     self._end_time = int(self._start_time + length * 1000)
   elif song.isfolder: music.fadeout(500)
示例#17
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
示例#18
0
文件: songselect.py 项目: asb/pydance
 def preview(self, song):
   if mainconfig["previewmusic"] and not song.isfolder:
     if (song.info["filename"].lower().endswith("mp3") and
         mainconfig["previewmusic"] == 2):
       music.stop()
       self._playing = False
       return
     if len(song.info["preview"]) == 2:
       # A DWI/SM/dance-style preview, an offset in the song and a length
       # to play starting at the offset.
       self._start, length = song.info["preview"]
       self._filename = song.info["filename"]
     else:
       # KSF-style preview, a separate filename to play.
       self._start, length = 0, 100
       self._filename = song.info["preview"]
     if self._playing: music.fadeout(500)
     self._playing = False
     self._start_time = pygame.time.get_ticks() + 500
     self._end_time = int(self._start_time + length * 1000)
   elif song.isfolder: music.fadeout(500)
示例#19
0
文件: songselect.py 项目: asb/pydance
 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
示例#20
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'
示例#21
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'
示例#22
0
def setcolors():
    global state, r, g, b
    global play
    while 1:
        if state == 'b0':
            a.timedfade(r,g,b,1)
            music.stop()
            play = False
            state = 'b1'
        elif state == 'b1':
            time.sleep(.1)
        elif state == 'r1':
            a.timedfade(255,0,0,.4)
            if not play:
            	music.play(-1)
                play = True
            state = 'r2'
            time.sleep(.4);
        elif state == 'r2':
            a.timedfade(0,0,0,.4)
            state = 'r1'
            time.sleep(.4)
示例#23
0
def PlayerCrash(background_game1, background_move1, background_game2,
                background_move2, player, enemies, siren, x, y):
    music.stop()
    crash = True
    coin_animation = 0
    sfxCrash.play()
    while crash:
        CLOCK.tick(8)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
        SCREEN.blit(background_game1, background_move1)
        player.draw(SCREEN)
        enemies.draw(SCREEN)
        SCREEN.blit(
            load(join(f_vfx,
                      f'explosion_{coin_animation}.png')).convert_alpha(),
            (x - 30, y - 9))
        SCREEN.blit(background_game2, background_move2)
        siren.draw(SCREEN)
        SCREEN.blit(imgCrash, (0, 0))
        SCREEN.blit(bgArcadeGameOver, (0, 0))
        display.update()
        coin_animation += 1
        if coin_animation == 7:
            crash = False
    player.draw(SCREEN)
    enemies.draw(SCREEN)
    SCREEN.blit(
        load(join(f_vfx, 'explosion_3.png')).convert_alpha(), (x - 30, y - 9))
    SCREEN.blit(background_game2, background_move2)
    siren.draw(SCREEN)
    SCREEN.blit(imgCrash, (0, 0))
    SCREEN.blit(bgArcadeLose, (0, 0))
    display.update()
    sleep(1)
示例#24
0
 def stop_click(self):
     music.stop()
示例#25
0
文件: pydance.py 项目: cpina/pydance
def main():
  print("pydance", VERSION, "<*****@*****.**> - irc.freenode.net/#pyddr")

  if mainconfig["usepsyco"]:
    try:
      import psyco
      print(_("Psyco optimizing compiler found. Using psyco.full()."))
      psyco.full()
    except ImportError: print(_("W: Psyco optimizing compiler not found."))

  # default settings for play_and_quit.
  mode = "SINGLE"
  difficulty = "BASIC"
  test_file = None
  for opt, arg in getopt(sys.argv[1:],
                         "hvf:d:m:", ["help", "version", "filename=",
                                      "difficulty=", "mode="])[0]:
    if opt in ["-h", _("--help")]: print_help()
    elif opt in ["-v", _("--version")]: print_version()
    elif opt in ["-f", _("--filename")]: test_file = arg
    elif opt in ["-m", _("--mode")]: mode = arg
    elif opt in ["-d", _("--difficulty")]: difficulty = arg

  if test_file: play_and_quit(test_file, mode, difficulty)

  song_list = []
  course_list = []
  for dir in mainconfig["songdir"].split(os.pathsep):
    print(_("Searching for songs in"), dir)

    # The order of patterns is significant. Deduplication will remove songs that
    # match a later pattern if they are in the same directory as a song with the
    # same basename but a different extension that matches an earlier pattern.
    # E.g. many ZIP files contain both .sm and .dwi. The .dwi will be ignored in
    # this case.
    song_list.extend(util.find(dir, ['*.dance', '*.sm', '*.dwi', '*/song.*'], 1))
  for dir in mainconfig["coursedir"].split(os.pathsep):
    print(_("Searching for courses in"), dir)
    course_list.extend(util.find(dir, ['*.crs'], 0))

  screen = set_display_mode()
  
  pygame.display.set_caption("pydance " + VERSION)
  pygame.mouse.set_visible(False)
  try:
    if os.path.exists("/usr/share/pixmaps/pydance.png"):
      icon = pygame.image.load("/usr/share/pixmaps/pydance.png")
    else: icon = pygame.image.load(os.path.join(pydance_path, "icon.png"))
    pygame.display.set_icon(icon)
  except: pass

  music.load(os.path.join(sound_path, "menu.ogg"))
  music.play(4, 0.0)

  songs = load_files(screen, song_list, _("songs"), SongItem, (False,))

  # Construct the song and record dictionaries for courses. These are
  # necessary because courses identify songs by title and mix, rather
  # than filename. The recordkey dictionary is needed for player's
  # picks courses.
  song_dict = {}
  record_dict = {}
  for song in songs:
    mix = song.info["mix"].lower()
    title = song.info["title"].lower()
    if song.info["subtitle"]: title += " " + song.info["subtitle"].lower()
    if mix not in song_dict: song_dict[mix] = {}
    song_dict[mix][title] = song
    record_dict[song.info["recordkey"]] = song

  crs = load_files(screen, course_list, _("courses"), courses.CourseFile,
                   (song_dict, record_dict))
  crs.extend(courses.make_players(song_dict, record_dict))
  records.verify(record_dict)

  # Let the GC clean these up if it needs to.
  song_list = None
  course_list = None
  record_dict = None
  ui.ui.clear()

  if len(songs) < 1:
    ErrorMessage(screen,
                 (_("You don't have any songs or step files. Check out "
                  "http://icculus.org/pyddr/get.php#songs "
                  "and download some free ones. "
                  "If you already have some, make sure they're in ")) +
                 mainconfig["songdir"])
    raise SystemExit(_("You don't have any songs. Check http://icculus.org/pyddr/get.php#songs ."))

  menudriver.do(screen, (songs, crs, screen))

  # Clean up shit.
  music.stop()
  pygame.quit()
  mainconfig.update(game_config)
  mainconfig.update(player_config)
  mainconfig.write(os.path.join(rc_path, "pydance.cfg"))
  records.write()
示例#26
0
文件: Audio.py 项目: ohsqueezy/pgfw
 def stop_current_channel(self):
     music.stop()
     if self.current_channel:
         self.current_channel.stop()
     self.current_channel = None
     self.paused = False
示例#27
0
def GameLoop(vehicle_selected):

    fuel = Fuel()
    rails = [156, 233, 313, 390, 470, 546, 627, 703, 783, 861]

    player_group = Group()
    enemies_group = Group()
    score_goal = Group()
    fuel_item = Group()
    bonus_items = Group()
    police_siren_animation = Group()
    kill_bonus_animation = Group()

    player = Player(vehicle_selected)
    player_group.add(player)

    player_score = ScoreGoal()
    score_goal.add(player_score)

    police_siren_images = PoliceSirenAnimation()
    police_siren_animation.add(police_siren_images)

    new_bonus = Bonus()
    bonus_items.add(new_bonus)

    game = True
    music.load(join(f_music, 'Game_Music.ogg'))
    music.set_volume(0.5)
    music.play(loops=-1)
    sfxLowFuel.set_volume(0.05)
    score = 0
    remaining_fuel = 219
    mov_y = 0

    while game:

        CLOCK.tick(FPS)

        if not fuel_item:
            fuel_item.add(fuel)

        if not enemies_group:
            for i in rails:
                enemy_type = Enemy(i)
                enemies_group.add(enemy_type)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    pygame.mixer.music.set_volume(0.2)
                    GamePause()
                    pygame.mixer.music.set_volume(0.7)

        y_move = mov_y % bgGameMap1.get_rect().height
        SCREEN.blit(bgGameMap1, (0, (y_move - bgGameMap1.get_rect().height)))
        if y_move < Height:
            SCREEN.blit(bgGameMap1, (0, y_move))

        player_collision = pygame.sprite.spritecollide(player, enemies_group, False)

        if player_collision:
            sfxLowFuel.stop()
            PlayerCrash(bgGameMap1, (0, (y_move - bgGameMap1.get_rect().height) - 15),
                        bgGameMap2, (0, (y_move - bgGameMap2.get_rect().height) - 15),
                        player_group, enemies_group, police_siren_animation,
                        player.rect.x, player.rect.y)
            GameOver(0, score)
            game = False

        if remaining_fuel <= 0:
            music.stop()
            sfxLowFuel.stop()
            PlayerBusted(bgGameMap1, (0, (y_move - bgGameMap1.get_rect().height) - 15),
                         bgGameMap2, (0, (y_move - bgGameMap2.get_rect().height) - 15),
                         player_group, enemies_group, police_siren_animation)
            GameOver(1, score)
            game = False

        player_group.update()
        fuel_item.update()
        kill_bonus_animation.update()
        bonus_items.update()
        enemies_group.update()
        score_goal.update()
        police_siren_animation.update()

        recharge = pygame.sprite.spritecollide(player, fuel_item, False)
        if recharge:
            sfxLowFuel.stop()
            if vehicle_selected == 1:
                score += 50
            elif vehicle_selected == 2:
                score += 100
            elif vehicle_selected == 3:
                score += 200
            else:
                score += 300
            Fuel.recharge(fuel)
            if remaining_fuel <= 50:
                remaining_fuel += 50
            elif remaining_fuel <= 150:
                remaining_fuel += 25
            else:
                remaining_fuel += 219 - remaining_fuel

        win_score = pygame.sprite.spritecollide(player_score, enemies_group, False)
        if win_score:
            if vehicle_selected == 1:
                score += 1
            elif vehicle_selected == 2:
                score += 1
            elif vehicle_selected == 3:
                score += 2
            else:
                score += 2

        bonus_kill = pygame.sprite.spritecollide(player, bonus_items, False)
        if bonus_kill:
            kill = BloodAnimation(new_bonus.rect.x, new_bonus.rect.y)
            kill_bonus_animation.add(kill)
            sfxLowFuel.stop()
            bonus_type = new_bonus.kill_bonus()
            if bonus_type == 1:
                score += 200
            elif bonus_type == 2:
                score += 100
            else:
                score += 300

        player_group.draw(SCREEN)
        enemies_group.draw(SCREEN)
        fuel_item.draw(SCREEN)
        bonus_items.draw(SCREEN)
        kill_bonus_animation.draw(SCREEN)
        police_siren_animation.draw(SCREEN)
        score_goal.draw(SCREEN)

        y_move = mov_y % bgGameMap2.get_rect().height
        SCREEN.blit(bgGameMap2, (0, (y_move - bgGameMap2.get_rect().height)))

        if y_move < Height:
            SCREEN.blit(bgGameMap2, (0, y_move))

        SCREEN.blit(bgArcadeGame, (0, 0))

        if 1 < remaining_fuel <= 70:
            music.set_volume(0.3)
            sfxLowFuel.play()
            SCREEN.blit(imgLowFuel, (185, 150))
            pygame.draw.rect(SCREEN, (200, 100, 100), (418, 941, remaining_fuel, 15))
        elif 70 < remaining_fuel <= 149:
            music.set_volume(0.5)
            pygame.draw.rect(SCREEN, (252, 209, 42), (418, 941, remaining_fuel, 15))
        else:
            music.set_volume(0.5)
            pygame.draw.rect(SCREEN, (100, 200, 100), (418, 941, remaining_fuel, 15))

        remaining_fuel -= 0.06
        ScorePrint(str(score).zfill(10), 540, 900, (0, 0, 0), 20)
        mov_y += 15
        pygame.display.update()

    return score
示例#28
0
 def stop(self):
     music.stop()
示例#29
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()
示例#30
0
 def kill(self):
   music.stop()
示例#31
0
 def stop(self):
     # TODO: Clean-up code here
     music.stop()
示例#32
0
文件: Music.py 项目: tcolar/Stylus2X
 def shutdown(self):
     music.stop();
     self.updater.shutdown();
     self.done=True;
示例#33
0
import os
import time
from pygame import mixer #I am using Pygame for this, though it would be nice to make a few different files to play from the built in player
#Pygame can be downloaded from: http://www.pygame.org/download.shtml
from pygame.mixer import music

for i in os.listdir(os.getcwd()): #Goes through the folder. The current file is put in variable "i"
    if i.endswith(".wav"): #Looks for .wav file types. m4a files don't work with Pygame
        #mixer.init(frequency=16000) #Determines how high pitch the voice is played back. 16000 is normal
        mixer.init() 
        music.load(i) #Loads the file that it is currently on ("i") to play
        music.play() #Plays the file
        time.sleep(3) #Delays the player to stop after X seconds
        music.stop() #stops the music
        mixer.quit() #Quits Pygame
        continue
    else:
        continue
示例#34
0
    global pre_dist, pre_time

    velocity = (distance - pre_dist) / (stop_t - pre_time)
    pre_dist = distance
    pre_time = stop_t

    return abs(velocity)


if __name__ == '__main__':
    try:
        setup()
        pre_dist = 30
        pre_time = 0

        while True:
            v = get_velocity()
            print('Measured Velocity = {}'.format(v))

            if v >= 30:
                music.play()
                for i in range(3):
                    gpio.output(13, gpio.HIGH)
                    time.sleep(0.5)
                    gpio.output(13, gpio.LOW)
                    time.sleep(0.5)
                music.stop()
            time.sleep(1)
    finally:
        gpio.cleanup()
示例#35
0
def main():
  print "pydance", VERSION, "<*****@*****.**> - irc.freenode.net/#pyddr"

  if mainconfig["usepsyco"]:
    try:
      import psyco
      print _("Psyco optimizing compiler found. Using psyco.full().")
      psyco.full()
    except ImportError: print _("W: Psyco optimizing compiler not found.")

  # default settings for play_and_quit.
  mode = "SINGLE"
  difficulty = "BASIC"
  test_file = None
  for opt, arg in getopt(sys.argv[1:],
                         "hvf:d:m:", ["help", "version", "filename=",
                                      "difficulty=", "mode="])[0]:
    if opt in ["-h", _("--help")]: print_help()
    elif opt in ["-v", _("--version")]: print_version()
    elif opt in ["-f", _("--filename")]: test_file = arg
    elif opt in ["-m", _("--mode")]: mode = arg
    elif opt in ["-d", _("--difficulty")]: difficulty = arg

  if test_file: play_and_quit(test_file, mode, difficulty)

  song_list = {}
  course_list = []
  for dir in mainconfig["songdir"].split(os.pathsep):
    print _("Searching for songs in"), dir
    song_list.update(util.find_songs(dir, ['*.dance', '*.sm', '*.dwi', '*/song.*']))
  for dir in mainconfig["coursedir"].split(os.pathsep):
    print _("Searching for courses in"), dir
    course_list.extend(util.find(dir, ['*.crs']))

  screen = set_display_mode()
  
  pygame.display.set_caption("pydance " + VERSION)
  pygame.mouse.set_visible(False)
  try:
    if os.path.exists("/usr/share/pixmaps/pydance.png"):
      icon = pygame.image.load("/usr/share/pixmaps/pydance.png")
    else: icon = pygame.image.load(os.path.join(pydance_path, "icon.png"))
    pygame.display.set_icon(icon)
  except: pass

  music.load(os.path.join(sound_path, "menu.ogg"))
  music.play(4, 0.0)

  songs = load_files(screen, song_list.values(), _("songs"), SongItem, (False,))

  # Construct the song and record dictionaries for courses. These are
  # necessary because courses identify songs by title and mix, rather
  # than filename. The recordkey dictionary is needed for player's
  # picks courses.
  song_dict = {}
  record_dict = {}
  for song in songs:
    mix = song.info["mix"].lower()
    title = song.info["title"].lower()
    if song.info["subtitle"]: title += " " + song.info["subtitle"].lower()
    if not song_dict.has_key(mix): song_dict[mix] = {}
    song_dict[mix][title] = song
    record_dict[song.info["recordkey"]] = song

  crs = load_files(screen, [course_list], _("courses"), courses.CourseFile,
                   (song_dict, record_dict))
  crs.extend(courses.make_players(song_dict, record_dict))
  records.verify(record_dict)

  # Let the GC clean these up if it needs to.
  song_list = None
  course_list = None
  record_dict = None
  pad.empty()

  if len(songs) < 1:
    ErrorMessage(screen,
                 (_("You don't have any songs or step files. Check out "
                  "http://icculus.org/pyddr/get.php#songs "
                  "and download some free ones. "
                  "If you already have some, make sure they're in ")) +
                 mainconfig["songdir"])
    raise SystemExit(_("You don't have any songs. Check http://icculus.org/pyddr/get.php#songs ."))

  menudriver.do(screen, (songs, crs, screen))

  # Clean up shit.
  music.stop()
  pygame.quit()
  mainconfig.write(os.path.join(rc_path, "pydance.cfg"))
  # FIXME -- is this option a good idea?
  if mainconfig["saveinput"]: pad.write(os.path.join(rc_path, "input.cfg"))
  records.write()
示例#36
0
文件: steps.py 项目: EvilDrW/pydance
 def is_over(self):
   if not music.get_busy(): return True
   elif self.endat and music.get_pos() > self.endat * 1000:
     music.stop()
     return True
   else: return False
示例#37
0
 def lost(self):
     music.stop()
     self.running = False
     self.image = self.load_image(Screen.DEATH_SCENE, self.rect.size)
示例#38
0
def start_news(app, var, Label, img1, img2, img3):
    """ Start the AI News Function """
    saved_headline = popular_ai_news(app, var)
    wait_count = 0
    while True:
        try:
            var.set("Do you want to listen again?")
            app.update()
            speak("Do you want to listen again")
            Label.configure(image=img2,
                            borderwidth=0,
                            compound="center",
                            highlightthickness=0,
                            padx=0,
                            pady=0)
            var.set("Listening.....")
            app.update()
            with sr.Microphone() as source:
                #Listen the audio through Microphone
                #r.adjust_for_ambient_noise(source)
                audio = r.listen(source, phrase_time_limit=1.5)
                Label.configure(image=img1,
                                borderwidth=0,
                                compound="center",
                                highlightthickness=0,
                                padx=0,
                                pady=0)
                var.set(r.recognize_google(audio))
                app.update()
            if "yes" in r.recognize_google(audio):
                ##Play Background News Music
                music.play()
                var.set("Oky \nHere is the top Headlines for today")
                app.update()
                speak("Oky, Here is the top headline for today")
                for headline in saved_headline:
                    var.set(headline)
                    app.update()
                    speak(headline)
                    t.sleep(1)
                ##Stop Background Music
                music.stop()
            else:
                var.set("Oky  \nHave a nice day")
                app.update()
                speak("Oky, Have a nice day")
                app.destroy()
                break
        except KeyboardInterrupt as k:
            app.destroy()
            break
        except:
            if wait_count < 3:
                if wait_count != 2:
                    Label.configure(image=img1,
                                    borderwidth=0,
                                    compound="center",
                                    highlightthickness=0,
                                    padx=0,
                                    pady=0)
                    var.set("Sorry \nI can't listen properly")
                    app.update()
                    speak("Sorry, I can't listen properly")
                    wait_count += 1
                    continue
                else:
                    wait_count += 1
                    continue
            else:
                Label.configure(image=img3,
                                borderwidth=0,
                                compound="center",
                                highlightthickness=0,
                                padx=0,
                                pady=0)
                var.set(
                    "Sorry \nDue to no response I am closed the programmme")
                app.update()
                speak("Sorry, Due to no response I am closed the programmme")
                app.destroy()
                break
    app.mainloop()
示例#39
0
 def stop(self):
     music.stop()
     self._stopped = True
示例#40
0
 def finalize():
     music.stop()
     tk.quit()
示例#41
0
文件: steps.py 项目: EvilDrW/pydance
 def kill(self):
   music.stop()
s2.play(2)  # optional parameter loops three times
time.sleep(10)

# set volume down
s1.set_volume(0.1)
time.sleep(5)

# set volume up
s1.set_volume(1)
time.sleep(5)

s1.stop()
s2.stop()
mixer.quit()

# MP3
import time
from pygame import mixer
from pygame.mixer import music

mixer.init()
music.load('test.mp3')

music.play()
time.sleep(10)

music.stop()
mixer.quit()

os.system("pause")
示例#43
0
 def stop(self):
     #line
     music.stop()
示例#44
0
 def stop(self):
     music.stop()
     self.lose()
示例#45
0
 def stop(self,fadeout=3):
     fadeout = int(fadeout)
     if fadeout:
         music.fadeout(fadeout*1000)
     else:
         music.stop()
示例#46
0
 def stopBackground(self):
     music.stop()
示例#47
0
    def play_sound_game_over(self):
        """Проигрывание мелодии при проигрыше уровня"""

        music.stop()
        self.sounds['game_over_sound'].play()
示例#48
0
 def is_over(self):
   if not music.get_busy(): return True
   elif self.endat and music.get_pos() > self.endat * 1000:
     music.stop()
     return True
   else: return False
示例#49
0
def stop():
    music.stop()
示例#50
0
 def stop(self):
     music.stop()
示例#51
0
 def stop(self):
     pymusic.stop()