def tournaments_scrape(): tour_champ_end = datetime.datetime(year=2014, month=9, day=16) #shitty way of dates url = 'http://www.pgatour.com/tournaments/schedule.html' r = requests.get(url) soup = BeautifulSoup(r.text) table = soup.find_all('table', id='tableFirst') asdf = r.text.find("initLb") for row in table[0].tbody: try: info = row.find_all('td') tdate = info[0].string.split() #date is now a list. we need to get the dates from the strings. Odd error here: #some times the dates come back in different forms, so we try all just to make #sure year = '2014' #this can be changed later tourney_name = info[1].a.string.strip() try: begin_date = datetime.datetime.strptime(tdate[1]+tdate[2]+tdate[5],'%b%d%Y') end_date = datetime.datetime.strptime(tdate[8]+tdate[9]+tdate[12],'%b%d%Y') except IndexError: begin_date = datetime.datetime.strptime(tdate[0]+tdate[1]+year,'%b%d%Y') try: end_date = datetime.datetime.strptime(tdate[0]+tdate[3]+year,'%b%d%Y') except ValueError: end_date = datetime.datetime.strptime(tdate[3]+tdate[4]+year,'%b%d%Y') try: tourney_link = info[1].a['href'][0] except TypeError: print "no link for " + tourney_name continue if tourney_link == '/': tourney_url = 'http://www.pgatour.com'+info[1].a['href'] else: tourney_url = info[1].a['href'] #we need to get the tid... stupidest way to do this........ tourney_pga_id = _get_tourney_id(tourney_url) tourney_leaderboard_json_url = 'http://www.pgatour.com/data/r/' + tourney_pga_id + '/leaderboard.json' print tourney_name if end_date < tour_champ_end: try: tourney = Tournament.objects.get(pga_id=tourney_pga_id) except me.queryset.DoesNotExist: tourney = Tournament(pga_id=tourney_pga_id, begin_date=begin_date,end_date=end_date,name=tourney_name,main_page_url=tourney_url,leaderboard_json_url=tourney_leaderboard_json_url) tourney.field_url = tournament.main_page_url[0:-5]+'/field.html' tourney.quarter = 1 tourney.save() except AttributeError: # incase it's just a string pass
def get_command(self): """Create a new tournament.""" name = Input.for_string("Please enter tournament's name : ") location = Input.for_string("Please enter tournament's location : ") date = datetime.date.today().strftime("%d/%m/%Y") mode = Input.for_string("How would you like to play ? bullet / blitz / fast : ") nb_rounds = 4 rounds = [] serialized_rounds = [] description = input("Please enter tournament's description : ") # CHOOSE BETWEEN AUTO or MANUAL list of players : players = self.create_auto_players() # players = self.create_list_players() tournament = Tournament( name, location, date, mode, nb_rounds, rounds, description, players ) tournament.save() print(tournament) first_round = self.progress_first_round( tournament, players, serialized_rounds, ) if first_round == "main menu": return "main menu" nb_rounds = tournament.nb_rounds next_round = self.progress_next_rounds( tournament, players, serialized_rounds, nb_rounds, ) if next_round == "main menu": return "main menu" return "main menu"
class TournamentControler: """Tournament controler Attributes: screen (object): display for tournament controler tournament_infos (dict): Dictionnary contains infos for a tournament tournament (object): tournament on course """ def __init__(self): self.screen = Screen() self.screen.info_users([ " GESTION DES TOURNOIS ", "\n\n\n", "[1] Créer un tournoi", "\n", "[2] Charger un tournoi", "\n", "[3] Modifier un tournoi", "\n" ]) self.screen.clear() self.screen.on_screen() menu = input_menu_verification(3, "Saisissez le menu désiré") if menu == 1: self.create() elif menu == 2: self.load() elif menu == 3: self.modify() def create(self): """Create a new tournmanent""" self.screen.info_users( [" CREATION DE TOURNOI \n\n\n"]) self.screen.clear() self.screen.on_screen() tournament_infos = {} tournament_infos['id'] = max_id(tournaments_db) + 1 tournament_infos['name'] = input("Nom du Tournoi : ") tournament_infos['location'] = input("Lieu du tournoi : ") tournament_infos['date_start'] = strftime("%A %d %B %Y %H:%M:%S") tournament_infos['date_end'] = "on_course" tournament_infos['total_round'] = ROUNDS_NB self.screen.info_users([ "Choix du controleur de temps :\n", " [1] Blitz \n", " [2] Bullet \n", " [3] Coup Rapide \n" ]) self.screen.on_screen() controler_saisie = input_menu_verification( 3, "Veuillez saisir le numéro correspondant à votre choix") if controler_saisie == 1: tournament_infos['time_controler'] = "Blitz" elif controler_saisie == 2: tournament_infos['time_controler'] = "Bullet" elif controler_saisie == 3: tournament_infos['time_controler'] = "Coup rapide" tournament_infos['description'] = input("Description : ") tournament_infos['players_list'] = [] tournament_infos['rounds_list'] = [] self.tournament = Tournament(tournament_infos) self.tournament.save(tournaments_db) self.players_on_load = [] while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB: self.add_player_on_tournament() self.tournament.save(tournaments_db) self.play() def add_player_on_tournament(self): """Add a player in a tournament""" self.screen.clear() report = Reports(players_db, tournaments_db) self.screen.info_users(report.list_of_players('id')) self.screen.add_infos([ "{} joueurs ajoutés au tournoi".format( len(self.tournament.players_list)) ]) self.screen.on_screen() id_player = input_menu_verification( max_id(players_db), "Entrez le numéro du joueur à ajouter au tournoi") while id_player in self.players_on_load: self.screen.warning( "Le joueur {} est déjà inscrit dans ce tournoi".format( id_player)) id_player = input_menu_verification( max_id(players_db), "Entrez le numéro du joueur à ajouter au tournoi") valid_player = search_db(id_player, players_db) if valid_player is not False: self.tournament.add_player(valid_player) self.players_on_load.append(id_player) else: self.screen.warning("Le joueur {} n'existe pas.".format(id_player)) sleep(1) def load(self): """Load a tournament""" report = Reports(players_db, tournaments_db) self.screen.clear() self.screen.info_users(report.tournaments_list()) self.screen.on_screen() tournament_id = input_menu_verification( max_id(tournaments_db), "Saisissez le numéro du tournoi à charger") valid_tournament = search_db(tournament_id, tournaments_db) if valid_tournament is False: self.screen.warning( "Le tournoi {} n'existe pas.".format(tournament_id)) sleep(1) self.load() else: tournament_on_load = Tournament(valid_tournament) tournament_on_load.deserialized() self.tournament = tournament_on_load self.players_on_load = [] for player in self.tournament.players_list: self.players_on_load.append(player.player_id) while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB: self.add_player_on_tournament() self.play() def play(self): """Play a tournament Args: tournament (object): Tournament object """ self.screen.clear() tournament_infos_list = [ self.tournament.name, "\n", "Lieu : ", self.tournament.location, "\n", "Début du tournoi : ", self.tournament.date_start, "\n" ] while self.tournament.round < ROUNDS_NB: if self.tournament.rounds_list == [] or self.tournament.rounds_list[ -1].date_end != 'On course': self.tournament.create_round() self.tournament.save(tournaments_db) while self.tournament.rounds_list[-1].date_end == 'On course': self.screen.info_users( [" TOURNOI EN COURS \n\n\n"]) self.screen.add_infos(tournament_infos_list) round_infos = [str(self.tournament.rounds_list[-1]), "\n\n"] for match in self.tournament.rounds_list[-1].matchs_list: round_infos.append(str(match)) round_infos.append("\n") self.screen.add_infos(round_infos) self.screen.on_screen() self.actions() self.tournament.save(tournaments_db) if self.tournament.date_end == 'on_course': self.tournament.date_end = strftime("%A %d %B %Y %H:%M:%S") self.tournament.save(tournaments_db) self.tournament.players_list = sorted( self.tournament.players_list, key=lambda player: player.elo_ranking) self.tournament.players_list = sorted( self.tournament.players_list, key=lambda player: player.tournament_score, reverse=True) self.result() input_menu_verification(1, "") def actions(self): """choice of actions in tournament""" self.screen.info_users([ "Actions possibles :\n", " [1] Saisir le score d'un match\n", " [2] Modifiez le classement d'un joueur\n" ]) self.screen.on_screen() choice = input_menu_verification( 2, "Saisissez le numéro de l'action souhaitée") if choice == 1: self.update_score() elif choice == 2: self.modify_player_rank() def update_score(self): """Updating a match score""" match_index = input_menu_verification( int(TOURNAMENT_PLAYERS_NB / 2), "Pour quel match voulez vous rentrer les résultats") if self.tournament.rounds_list[-1].matchs_list[ match_index - 1].statement == "Validé": self.screen.info_users(["Match déjà joué."]) sleep(1) self.update_score() player_1 = str( self.tournament.rounds_list[-1].matchs_list[match_index - 1].player1) player_2 = str( self.tournament.rounds_list[-1].matchs_list[match_index - 1].player2) self.screen.info_users([ "Choix du score pour les joueurs :\n", " [1] ", player_1, " remporte le match\n", " [2] Match nul\n", " [3] ", player_2, " remporte le match\n" ]) self.screen.on_screen() choix_score = input_menu_verification(3, "") if choix_score == 1: score_p1 = 1 score_p2 = 0 elif choix_score == 2: score_p1 = 0.5 score_p2 = 0.5 elif choix_score == 3: score_p1 = 0 score_p2 = 1 self.tournament.rounds_list[-1].validate_match(match_index, score_p1, score_p2) self.screen.clear() def modify_player_rank(self): """Modify a player's rank""" self.screen.clear() report = Reports(players_db, tournaments_db) self.screen.info_users( report.t_players_list(self.tournament.id, 'surname')) self.screen.on_screen() id_player = input_menu_verification( self.max_player_id_tournament(), "Saisissez l'id du joueur dont vous souhaitez modifier le rang") id_players_list = [] for player in self.tournament.players_list: id_players_list.append(player.player_id) if id_player not in id_players_list: self.screen.warning( "Le joueur {} n'est pas présent dans le tournoi.".format( id_player)) sleep(1) self.modify_player_rank() new_ranking = input_menu_verification( 1000000000, "Saisissez le nouveau classement du joueur") for player in self.tournament.players_list: if player.player_id == id_player: player.modify_ranking(new_ranking) update_item_in_db(players_db, 'elo_ranking', new_ranking, id_player) self.screen.clear() def max_player_id_tournament(self): """Define maximum player id""" i = 0 for player in self.tournament.players_list: if player.player_id > i: i = player.player_id return i def result(self): """Display result for a tournament""" tournament_result = [ "Classement ", "NOM ", "PRENOM ", "SCORE ", "\n\n" ] t_rank = 1 for player in self.tournament.players_list: player_infos = [] player_infos.append(str(t_rank)) player_infos.append(player.surname) player_infos.append(player.name) player_infos.append(str(player.tournament_score)) for i in range(4): dif = len(tournament_result[i]) - len(player_infos[i]) if dif < 0: tournament_result.append( str(player_infos[i])[:(dif - 1)] + " ") elif dif > 0: tournament_result.append(str(player_infos[i]) + dif * " ") tournament_result.append("\n") t_rank += 1 self.screen.info_users(tournament_result) self.screen.on_screen() def modify(self): """Modify info for a tournament""" report = Reports(players_db, tournaments_db) self.screen.clear() self.screen.info_users(report.tournaments_list()) self.screen.on_screen() tournament_id = input_menu_verification( max_id(tournaments_db), "Saisissez le numéro du tournoi à modifier") self.screen.info_users([ "Choix de la modification :\n", " [1] Nom \n", " [2] Lieu \n", " [3] Description \n" ]) self.screen.on_screen() modify = input_menu_verification( 3, "Saisissez le numéro de la donnée à modifier") info_modify = input("Saisissez la modification : ") if modify == 1: key = 'name' if modify == 2: key = 'location' if modify == 3: key = 'description' update_item_in_db(tournaments_db, key, info_modify, tournament_id) self.modify()