Exemplo n.º 1
0
 def _init_managers(self):
     live_data_parser = LiveDataParser(self._current_event)
     threads = list(
         map(
             lambda id_: TransfersManager(id_, self._current_event,
                                          live_data_parser), self.__ids))
     return threads
    def __init__(self,
                 ids_file,
                 league_name="",
                 league_id=-1,
                 managers_count=-1):
        [self.__current_event, self.__gw_name, self.__is_dgw] = get_gw_info()

        self.__ids = read_ids(ids_file, league_id, managers_count)

        self.__live_data_parser = LiveDataParser(self.__current_event,
                                                 self.__is_dgw)

        self.__managers = self.__init_managers()
        self.__init_each_manager_players_played()

        self.__output = []  # A list which stores the whole output
        self.__output_file = set_output_file(self.__current_event, "rivals",
                                             ids_file, league_name, league_id)
Exemplo n.º 3
0
    def __init_managers(self):
        threads = []
        gw = 1

        for i in range(gw, self.__current_event + 1):
            live_data_parser = LiveDataParser(i)
            manager = AutosubsManager(team_id=self.__id,
                                      current_event=i,
                                      live_data_parser=live_data_parser)
            threads.append(manager)

        return threads
    def _init_managers(self):
        threads = []
        gw_one = 1

        for i in range(gw_one, self._current_event + 1):
            live_data_parser = LiveDataParser(i)
            manager = TransfersManager(team_id=self.__id_,
                                       current_event=i,
                                       live_data_parser=live_data_parser)
            threads.append(manager)

        return threads
Exemplo n.º 5
0
    def __init_managers(self):
        threads = []
        gw = 1

        for i in range(gw, self.__current_event + 1):
            live_data_parser = LiveDataParser(i)
            self.__live_data_parsers.append(live_data_parser)

            threads.append(
                ClassicManager(team_id=self.__id,
                               current_event=i,
                               is_dgw=False,
                               live_data_parser=live_data_parser))

        return threads
Exemplo n.º 6
0
class HthAnalyzer(ABC):
    _current_event = get_current_event()
    _players_names = {}
    _live_data_parser = LiveDataParser(_current_event)
    _wins = _draws = _losses = 0

    def __init__(self, team_id, set_leagues):
        self._id = team_id

        # Create our manager and start it (because it's a thread)
        self._team = HthManager(self._id, self._current_event, set_leagues)
        self._team.start()
        self._team.join()

        self.__manager_name = self._team.manager_name.split(" ")[0]

        self._output = []

    @abstractmethod
    def print_all_matchups(self):
        pass

    def save_output_to_file(self, output_file):
        save_output_to_file(output_file, "w", self._output)

    def _print_one_matchup(self, opponent):
        ((team_unique_players, team_points), (opp_unique_players, opp_points)) = \
            self._list_of_unique_players_and_their_points(opponent)

        team_manager = self._team.manager_name
        opponent_manager = opponent.manager_name

        unique_players = ["{}: [{}] vs.".format(team_manager, team_unique_players),
                          "{}: [{}]".format(opponent_manager, opp_unique_players)]
        log_list_of_strings(unique_players, self._output)

        if self._team.active_chip != "None" or opponent.active_chip != "None":
            active_chip = ["[Active chip]",
                           "{} vs. {}".format(self._team.active_chip, opponent.active_chip)]
            log_list_of_strings(active_chip, self._output)

        hits_taken = ["[Hits taken]",
                      "{}: {}".format(team_manager, self._team.gw_hits),
                      "{}: {}".format(opponent_manager, opponent.gw_hits)]
        log_list_of_strings(hits_taken, self._output)

        different_players_points = ["[Points gained by different players]",
                                    "{}: {}".format(team_manager, team_points),
                                    "{}: {}".format(opponent_manager, opp_points)]
        log_list_of_strings(different_players_points, self._output)

        if self._team.gw_hits != opponent.gw_hits:
            hit_cost = 4
            team_points -= self._team.gw_hits*hit_cost
            opp_points -= opponent.gw_hits*hit_cost

        # Take hits into account
        self._current_points_difference(team_points, opp_points)

        winner = self._define_winner(team_manager, team_points, opponent_manager, opp_points)
        winner_string = "[Winner: {}]\n".format(winner)
        log_string(winner_string, self._output)

    def _print_record(self):
        record = "[Record: {}W, {}D, {}L]\n".format(self._wins, self._draws, self._losses)
        log_string(record, self._output)

        print("Good luck, {}! :)".format(self.__manager_name))

    def _list_of_unique_players_and_their_points(self, opponent):
        (team_unique_players, team_points) = self._unique_players_and_points(self._team.players_ids,
                                                                             opponent.players_ids,
                                                                             self._team.captain_id)

        (opp_unique_players, opp_points) = self._unique_players_and_points(opponent.players_ids,
                                                                           self._team.players_ids,
                                                                           opponent.captain_id)

        if self._team.captain_id == opponent.captain_id:
            (team_unique_players, points) = self._check_same_captains(self._team, opponent, team_unique_players)
            team_points += points

            (opp_unique_players, points) = self._check_same_captains(opponent, self._team, opp_unique_players)
            opp_points += points

        elif self._team.captain_id != opponent.captain_id:
            (team_unique_players, points) \
                = self._check_different_captains(self._team, team_unique_players, opponent.players_ids)
            team_points += points

            (opp_unique_players, points) = \
                self._check_different_captains(opponent, opp_unique_players, self._team.players_ids)
            opp_points += points

        final_result = ((team_unique_players, team_points), (opp_unique_players, opp_points))

        return final_result

    def __find_different_ids(self, team_a, team_b):
        return team_a.difference(team_b)

    def _unique_players_and_points(self, team_a, team_b, captain_id):
        players_ids = self.__find_different_ids(team_a, team_b)

        def helper():
            result = []
            points = 0

            for player_id in players_ids:
                if player_id == captain_id:
                    continue

                curr_player_points = self._live_data_parser.get_player_points(player_id)

                if player_id in self._players_names:
                    curr_player = "{}={}".format(self._players_names[player_id], curr_player_points)
                    result.append(curr_player)
                else:
                    player_name = self._team.event_data_parser.get_player_name(player_id)
                    self._players_names[player_id] = player_name

                    curr_player = "{}={}".format(player_name, curr_player_points)
                    result.append(curr_player)

                points += curr_player_points

            unique_players = ", ".join(result)
            result = (unique_players, points)

            return result

        return helper()

    def _check_same_captains(self, team_a, team_b, unique_players):
        result = (unique_players, 0)

        if team_a.active_chip == "TC" and team_b.active_chip != "TC":
            captain_points = self._live_data_parser.get_player_points(self._team.captain_id)
            captain_formatted = ", {}={}".format(self._team.captain_name, captain_points)

            unique_players += captain_formatted
            result = (unique_players, captain_points)

        return result

    def _check_different_captains(self, team, unique_players, opponent_players_ids):
        captain_name = team.captain_name
        captain_points = self._live_data_parser.get_player_points(team.captain_id)

        if team.active_chip == "TC":
            if team.captain_id in opponent_players_ids:
                points_to_add = 2*captain_points
                multiplier = "X2"
            else:
                points_to_add = 3*captain_points
                multiplier = "X3"

            captain_name = ", {} {}={}".format(captain_name, multiplier, points_to_add)

        else:
            if team.captain_id in opponent_players_ids:
                points_to_add = captain_points
                captain_name = ", {}={}".format(captain_name, points_to_add)
            else:
                points_to_add = 2*captain_points
                captain_name = ", {} X2={}".format(captain_name, points_to_add)

        unique_players = "{}{}".format(unique_players, captain_name)
        result = (unique_players, points_to_add)

        return result

    def _current_points_difference(self, team_a_points, team_b_points):
        current_result = "trailing" if team_a_points < team_b_points else "leading"
        points_difference = abs(team_a_points - team_b_points)
        formatter = "point" if points_difference == 1 else "points"

        points_difference_string = "You're {} by: {} {}.".format(current_result, abs(team_a_points - team_b_points),
                                                                 formatter)
        log_string(points_difference_string, self._output)

    def _define_winner(self, team_a_manager, team_a_points, team_b_manager, team_b_points):
        if team_a_points > team_b_points:
            self._wins += 1
            return team_a_manager
        elif team_a_points < team_b_points:
            self._losses += 1
            return team_b_manager
        else:
            self._draws += 1
            return "Draw!"

    @abstractmethod
    def _init_opponents_ids(self):
        pass

    @abstractmethod
    def _init_opponents(self):
        pass
class ClassicAnalyzer:
    __LAST_EVENT = 38

    @performance
    def __init__(self,
                 ids_file,
                 league_name="",
                 league_id=-1,
                 managers_count=-1):
        [self.__current_event, self.__gw_name, self.__is_dgw] = get_gw_info()

        self.__ids = read_ids(ids_file, league_id, managers_count)

        self.__live_data_parser = LiveDataParser(self.__current_event,
                                                 self.__is_dgw)

        self.__managers = self.__init_managers()
        self.__init_each_manager_players_played()

        self.__output = []  # A list which stores the whole output
        self.__output_file = set_output_file(self.__current_event, "rivals",
                                             ids_file, league_name, league_id)

    def print_table(self):
        self.__sort_managers()
        self.__format_managers_properties()

        self.__print_legend()
        self.__print_table_output()

    def print_stats(self):
        stats = ClassicAnalyzerStats(self.__managers, self.__current_event,
                                     self.__output_file)
        stats.stats_menu()

        stats.save_stats_output_to_file()

    def save_output_to_file(self):
        save_output_to_file(self.__output_file, "w", self.__output)

    def find_manager_id(self, name):
        for manager in self.__managers:
            if manager.manager_name == name:
                return manager.get_id()

        return -1

    @start_threads
    def __init_managers(self):
        threads = list(
            map(
                lambda id_: ClassicManager(id_, self.__current_event, self.
                                           __is_dgw), self.__ids))
        return threads

    def __init_each_manager_players_played(self):
        for manager in self.__managers:
            (sgw_players_count,
             dgw_players_info) = self.__live_data_parser.count_players_played(
                 manager.players_ids)
            manager.format_players_played(sgw_players_count)

            if self.__is_dgw:
                manager.format_dgw_players_played(*dgw_players_info)

    def __sort_managers(self):
        """
                menu returns an integer which indicates how the data is going to be sorted by:
                1: total points
                2: gameweek points
                3: team value
                """
        comparator = self.__menu()

        # sort the data
        if comparator[0] == 1:
            self.__managers.sort(key=attrgetter(comparator[1]), reverse=False)
        elif comparator[0] == 2:
            self.__managers.sort(key=cmp_to_key(ClassicManager.cmp_gw_pts))
        else:
            self.__managers.sort(key=attrgetter(comparator[1]), reverse=True)

    """
    # This method prints a menu and returns a tuple which contains:
    # user choice and a string associated with it
    """

    def __menu(self):
        option = -1
        result = (-1, "")

        options_number = {1, 2, 3}

        while option not in options_number:
            options = [
                "* How do you want to sort the sample by:", "1) Total points",
                "2) Gameweek points", "3) Total team value"
            ]
            exception_msg = "\n[!] Please enter an *integer*: either 1, 2 or 3."

            option = select_option_from_menu(options, exception_msg)

            if option == -1:
                continue

            if option == 1:
                result = (1, "overall_rank")
            elif option == 2:
                result = (2, "gw_points")
            elif option == 3:
                result = (3, "team_value")

            else:
                print("\n[!] Invalid option. Try again!")

        return result

    def __format_managers_properties(self):
        row_num = 1

        # format some of its columns
        for manager in self.__managers:
            manager.format_total_points_and_overall_rank()
            manager.format_gw_points()

            manager.row_num = row_num
            row_num += 1

    def __init_headers(self):
        headers = [
            "No", "Manager", "OR", "OP", "Used Chips",
            "{} P".format(self.__gw_name), "C".format(self.__gw_name),
            "VC".format(self.__current_event),
            "Chip".format(self.__current_event), "PP",
            "{} TM".format(self.__gw_name), "{} H".format(self.__gw_name),
            "TV", "Bank", "Tot"
        ]

        if self.__is_dgw:
            index = 10
            headers.insert(index, "PP II")

        return headers

    def __print_legend(self):
        print()
        legend = [
            "> Legend: ", "OR = Overall Rank, OP = Overall Points,\n"
            "C = Captain, VC = Vice Captain,\n"
            "PP = Players Played, TM = Transfers Made, H = Hit(s),\n"
            "TV = Team Value", "Tot = TV + Bank\n"
        ]

        for string in legend:
            log_string(string, self.__output)

    def __print_table_output(self):
        # tabulate requires a list of lists, so that's why it's needed
        list_of_lists = [manager.to_list() for manager in self.__managers]
        headers = self.__init_headers()

        # tablefmt="fancy_grid"
        table_output = tabulate(list_of_lists,
                                headers=headers,
                                tablefmt="orgtbl",
                                floatfmt=".1f",
                                numalign="center",
                                stralign="center")

        log_string(table_output, self.__output)
        log_string("", self.__output)

        formatter = "entry" if len(self.__managers) < 2 else "entries"
        print("\n{} {} have been loaded successfully.".format(
            len(self.__managers), formatter))
Exemplo n.º 8
0
class MiniLeagueAnalyzer:
    __current_event = get_current_event()
    __live_data_parser = LiveDataParser(__current_event)

    __ZARATA_LEAGUE_ID = 156718
    __ELITE_64_LEAGUE_ID = 2379

    __DEFAULT_SAVE_PATH = "csv"

    def __init__(self, ids_file, save_dir="", league_name="", league_id=-1):
        self.__managers_ids = self.__load_ids(league_id, ids_file)
        self.__config_zarata(league_id)
        self.__managers = self.__init_managers()

        self.__all_players_ids = self.__collect_players_ids()
        self.__all_players_names = self.__collect_players_data()

        self.__csv_data = self.__all_managers_to_list()

        [self.__save_dir,
         self.__save_path] = self.__set_save_path(ids_file, save_dir,
                                                  league_name, league_id)

    def write_data_to_csv(self):
        # headers = ["Manager Name",
        #            "Player 1", "Player 2", "Player 3", "Player 4", "Player 5", "Player 6",
        #            "Player 7", "Player 8", "Player 9", "Player 10", "Player 11",
        #            "Sub 1", "Sub 2", "Sub 3", "Sub 4"]

        Path(self.__save_dir).mkdir(parents=True, exist_ok=True)
        with open(self.__save_path, "w", newline="\n",
                  encoding="utf-8") as csvfile:
            csvwriter = csv.writer(csvfile)
            #csvwriter.writerow(headers)
            csvwriter.writerows(zip(*self.__csv_data))

    def __load_ids(self, league_id, ids_file):
        if league_id == -1:
            managers_ids = read_ids_from_file(ids_file)
        else:
            managers_ids = extract_teams_ids_from_league(league_id)

        # managers_ids = read_ids_from_file(ids_file) if league_id == -1 else extract_teams_ids_from_league(league_id)
        return managers_ids

    def __config_zarata(self, league_id):
        if league_id == self.__ZARATA_LEAGUE_ID:
            self.__managers_ids.sort()
            self.__managers_ids_sorted = self.__managers_ids

            self.__managers_ids = [115, 21074, 99, 1908330, 503269
                                   ]  # General, Sutherns, Will, Magnus, Dayvy

            for id_ in self.__managers_ids_sorted:
                self.__managers_ids.append(id_)

    @start_threads
    def __init_managers(self):
        threads = list(
            map(lambda id_: ClassicManager(id_, self.__current_event),
                self.__managers_ids))
        return threads

    def __collect_players_ids(self):
        result = set()

        for manager in self.__managers:
            players_ids = manager.all_players_ids

            for player_id in players_ids:
                result.add(player_id)

        return result

    """
    This method returns a dictionary,
    which values are: (player_name, player_points)
    """

    def __collect_players_data(self):
        result = {}
        event_data_parser = EventDataParser(1, self.__current_event)

        for player_id in self.__all_players_ids:
            result[player_id] = (
                event_data_parser.get_player_name(player_id),
                self.__live_data_parser.get_player_points(player_id),
                event_data_parser.get_player_team(player_id))

        return result

    def __one_manager_to_list(self, manager, result):
        #result = [manager.manager_name]
        result[0].append(manager.manager_name)
        #manager.format_gw_points()
        #result[1].append(manager.gw_points_string)
        result_length = len(result)
        for i in range(1, result_length):
            result[i].append("\n")

        players_ids = manager.all_players_ids

        for player_id in players_ids:
            (player_name, player_points,
             player_team) = self.__all_players_names[player_id]

            if player_id == manager.captain_id:
                captain_points = self.__live_data_parser.get_player_points(
                    player_id)

                if manager.active_chip != "TC":
                    result[0].append(player_name)
                    result[1].append(captain_points * 2)
                    result[2].append("C")
                else:
                    result[0].append(player_name)
                    result[1].append(captain_points * 3)
                    result[2].append("TC")

            else:
                if player_id == manager.vice_captain_id:
                    result[0].append(player_name)
                    result[2].append("VC")
                else:
                    result[0].append(player_name)
                    result[2].append("-")

                result[1].append(
                    self.__live_data_parser.get_player_points(player_id))

            result[3].append(player_team)

        [row.append("\n") for row in result]
        #return result

    def __all_managers_to_list(self):
        # col 1: players' names
        # col 2: players' points
        # col 3: - / c / vc
        # col 4: players' teams

        result = [[], [], [], []]

        for manager in self.__managers:
            #result.append(self.__manager_to_list(manager))
            self.__one_manager_to_list(manager, result)

        return result

    def __set_save_path(self, ids_file, save_dir, league_name, league_id):
        save_dir = self.__DEFAULT_SAVE_PATH if save_dir == "" else save_dir
        csv_filename = league_name if league_id != -1 else extract_file_name_from_path(
            ids_file)
        save_path = "{}/{}_gw{}.csv".format(save_dir, csv_filename,
                                            self.__current_event)

        result = (save_dir, save_path)
        return result