def set_genre_filter(self): print_bold("Use default genres (y/n)?") ans = input() if ans.lower() in ("n", "no", "0"): print_bold("Choose genres:") print_color("hiphop, house, r&b, latin, pop, reggae, other", Color.cyan) genres = [ i.strip().lower() for i in input().split(",") if i.strip().lower() in self.genres ] if not genres: print("No genres specified, using all...") return else: genres = ("hiphop", "house", "r&b", "pop", "other") print(f"Genres: {get_color(', '.join(genres), Color.yellow)}") self.filter = "&f=ddfilter" for genre in genres: genre_id = self.genre_map[genre.lower()] self.filter += f"&{genre_id}=on" self.current_url = ( f"https://www.djcity.com/uk/digital/records.aspx?p={self.current_num}" ) self.current_url += self.filter self.driver.get(self.current_url)
def print_playlist(self): if not self.playlist: raise RuntimeError("No playlist. Read a playlist first!") width_artist = max(len(row["artist"]) for row in self.playlist) width_title = max(len(row["song"]) for row in self.playlist) heading = "{:<{width_artist}s} {:<{width_title}s} {:9s} {:9s} {:9s}".format( "ARTIST", "SONG", "TIME", "PLAYTIME", "STARTTIME", width_artist=width_artist + 2, width_title=width_title, ) print_bold(heading) print_color("".join(["-"] * len(heading))) for row in self.playlist: print("{:<{width_artist}s} - {:<{width_title}s} {} {} {}". format( row["artist"], row["song"], Color.yellow + str(row["time"]).split(", ")[-1], Color.green + str(row["playtime"]).split(", ")[-1], Color.blue + row["starttime"].strftime("%H:%M:%S"), width_artist=width_artist, width_title=width_title, ) + colorama.Style.RESET_ALL) print_color("".join(["-"] * len(heading)) + "\n")
def game_loop(self): """Keep making moves until both players can't make a move anymore.""" while self.board.can_play() and (self.player_black.can_play() or self.player_white.can_play()): self.rounds_played += 1 print_bold( f"\n=========== ROUND: {self.rounds_played} ===========") self.player_black.play_one_move(self.board) print("-------------------------------") self.player_white.play_one_move(self.board)
def print_result(self): """Print ending status and winner info.""" print_bold("\n===============================") print_bold("The game is finished!\n", Color.green) print_bold("Result:") self.print_status() print("") winner = self.board.result() if winner == Disk.EMPTY: print_bold("The game ended in a tie...") else: print_bold(f"The winner is {str(winner)}!")
def run_loop(self): print_bold("\nChoose mode:") print(" 0: Single page") print(">0: Multiple pages") try: number = int(input()) print() if number > 0: self.multi_page_loop(number) else: self.single_page_loop() except ValueError: self.single_page_loop()
def init_game(self): """Initialize game board and players for a new game.""" self.board = Board(self.size) self.player_black = Player(Disk.BLACK) self.player_white = Player(Disk.WHITE) self.rounds_played = 0 if self.get_answer("Would you like to play against the computer"): if self.get_answer("Would you like to play as black or white", yes="b", no="w"): self.player_white.set_human(False) else: self.player_black.set_human(False) print_bold("\nPlayers:") self.print_status()
def multi_page_loop(self, pages=1): self.pool.update_current_page() last_page = self.pool.current_num + pages - 1 for _ in range(1, pages + 1): print_bold(f"--- Page: {self.pool.current_num} / {last_page} ---") self.single_page_download() if not self.pool.next_page(): print_color("No more pages!", Color.red) return print_bold("Continue for pages?") self.play_notification_sound() try: num = int(input()) if num > 0: self.multi_page_loop(num) except ValueError: return
def single_page_loop(self): self.pool.update_current_page() while True: print_bold(f"--- Page: {self.pool.current_num} ---") try: number = int( input( "Give number of tracks to download from current page, 0 = all\n" ) ) number = max(0, number) except ValueError: number = 0 self.single_page_download(number) if not self.pool.next_page(): print_color("No more pages!", Color.red) break self.play_notification_sound() if not input("Continue?\n").lower() in ("y", "1"): break
def fill_basso(self, show, start_index=0): """Fill radioshow playlist to Bassoradio database using Selenium.""" print_bold("Uploading playlist to dj.basso.fi...", Color.red) start_time = timer() if len(self.playlist) <= start_index: print("Index not valid.") return self.open_basso_driver(show) print("\nFilling playlist for show:") print_color(show, Color.cyan) # input song data print_color("\nAdding songs...", Color.magenta) for index, row in enumerate(self.playlist[start_index:]): input_index = 0 print(" {:d}: {:s} - {:s}".format(index + 1, row["artist"], row["song"])) while True: # increase index so we don't send the first letter multiple times when trying again input_index += 1 try: time.sleep(0.5) find_track = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( (By.ID, "find-track-textfield"))) find_track.send_keys(row["artist"][:input_index]) WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( (By.ID, "new-track-entry-form"))) artist = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "[ng-model*='newTrack.artist']"))) time.sleep(0.5) artist.send_keys(row["artist"][input_index:]) song = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "[ng-model*='newTrack.title']"))) song.send_keys(row["song"]) mins = row["playtime"].seconds // 60 minutes = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "[ng-model*='newTrack.minutes']"))) minutes.send_keys(mins) secs = row["playtime"].seconds % 60 seconds = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, "[ng-model*='newTrack.seconds']"))) seconds.send_keys(secs) save = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//input[@type='button' and @value='Tallenna uusi biisi']", ))) save.click() submit_button = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(( By.XPATH, "//input[@type='submit' and @value='Lisää biisilistaan']", ))) submit_button.click() except Exception as e: print_color(str(e), Color.red) continue else: break print_color(f"Done in {timer() - start_time:.2f} seconds!", Color.green)
def get_answer(question: str, yes="y", no="n") -> bool: """Ask a question with two options, and return bool from user answer.""" ans = input(f"{question} ({yes}/{no})? ") return ans.lower() == yes.lower() @staticmethod def get_board_size() -> int: """Ask and return the desired board size.""" while True: try: ans = int(input("Choose board board_size (default is 8): ")) return clamp(ans, 4, 8) except ValueError: print_error("give a number...") if __name__ == "__main__": print_bold("OTHELLO GAME - Python", Color.green) try: try: # try to read board size from command line args size = int(sys.argv[1]) print(f"Using board size: {size}") except (ValueError, IndexError): size = Othello.get_board_size() game = Othello(size) game.play() except KeyboardInterrupt: sys.exit("\nGame stopped...")
threading.Thread( target=self._play_notification, args=(self.pool.mac_os(),) ).start() @staticmethod def _play_notification(mac: bool): if mac: os.system("afplay /System/Library/Sounds/Glass.aiff") else: import winsound winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS) if __name__ == "__main__": print_bold("/////// RECORDPOOL AUTO-DL ///////", Color.green) args = sys.argv[1:] site = None if not args else args[0].lower() while not site: print_bold("\nChoose record pool:") # get all pool implementations automatically pools = tuple(pool.__name__ for pool in RecordPool.__subclasses__()) options = dict(zip((str(i) for i in range(1, len(pools) + 1)), pools)) # arguably this would have been cleaner for the current options but wanted to make it generalized and scalable # options = dict(zip(("1", "2", "3", "4"), ("Bandcamp", "Beatjunkies", "BPMSupreme", "DJCity"))) for key, value in options.items(): print(f"{key}: {value}") ans = input() if options.get(ans): site = options[ans].lower()
import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QPalette from PyQt5.QtWidgets import QApplication from PlaylistFormatter import PlaylistFormatter from PlaylistGui import PlaylistGui from colorprint import print_bold, print_color, Color if __name__ == "__main__": if len(sys.argv) > 1: # arguments given, run on command line print_bold("\n///// PLAYLIST FORMATTER /////\n", Color.red) filename = sys.argv[1] outfile = sys.argv[2] if len(sys.argv) == 2 else filename formatter = PlaylistFormatter() formatter.read_playlist(filename) formatter.print_playlist() print("exporting formatted playlist to:") print_color(outfile, Color.yellow) formatter.export_csv(outfile) print_bold("\n/////////// DONE ////////////\n", Color.green) else: # open GUI app = QApplication(sys.argv) app.setStyle("Fusion")