Example #1
0
def handle_data(data: dict) -> None:
    # not in order
    team1_champ_ids = [p.get('championId') for p in data.get('myTeam')]
    team2_champ_ids = [p.get('championId') for p in data.get('theirTeam')]

    # team_champ_ids must be length=5
    if len(team1_champ_ids) == 5 and len(team2_champ_ids) == 5:
        roles1 = get_roles(champion_roles, team1_champ_ids)
        roles2 = get_roles(champion_roles, team2_champ_ids)

        # in order
        team1_champ_ids = list(roles1.values())
        team2_champ_ids = list(roles2.values())

    all_champ_ids = team1_champ_ids + team2_champ_ids
    all_champ_names = [get_champion_name(p) for p in all_champ_ids]
    if len(all_champ_ids) == 10:
        arr = np.array([all_champ_ids])
        prediction = model.predict(x=arr, batch_size=32, verbose=0)
    else:
        prediction = [-1]

    champs = {
        'champ_ids': all_champ_ids,
        'champ_names': all_champ_names,
        'pred': float(prediction[0]),
    }
    print(json.dumps(champs))
Example #2
0
def getParticipantData(champion_roles, participantDataMap,
                       unsortedChampListBlue, unsortedChampListRed):
    participantData = []
    roles = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY']
    #champion_roles[360] = {'JUNGLE': 0.0, 'TOP': 0.0, 'MIDDLE': 0.0, 'BOTTOM': 1.0, 'UTILITY': 0.0}
    blueRoles = get_roles(champion_roles, unsortedChampListBlue)
    redRoles = get_roles(champion_roles, unsortedChampListRed)
    teams = [blueRoles, redRoles]
    for team in teams:
        participantDataList = []
        for role in roles:
            participantDataMap[team[role]]['role'] = role
            participantDataList.append(participantDataMap[team[role]])
        participantData.append(participantDataList)
    return participantData
def main():
    print("Pulling data...")
    champion_roles = get_data()
    print("Finished pulling data.")
    print()

    if len(sys.argv) == 6:
        c1, c2, c3, c4, c5 = sys.argv[1:6]
        roles, prob, confidence, alternative = get_roles(champion_roles,
                                                         [c1, c2, c3, c4, c5],
                                                         verbose=True)
    else:
        roles, prob, confidence, alternative = get_roles(
            champion_roles,
            ['Galio', 'Maokai', 'Jarvan IV', 'Tristana', 'Tahm Kench'],
            verbose=True)
        roles, prob, confidence, alternative = get_roles(
            champion_roles, ['Brand', 'Caitlyn', 'Vi', 'Lulu', 'Cassiopeia'],
            verbose=True)
def main():
    print("Pulling data...")
    champion_roles = pull_data()
    print("Finished pulling data.")
    print()

    champions = [122, 64, 69, 119,
                 201]  # ['Darius', 'Lee Sin', 'Cassiopeia', 'Draven', 'Braum']
    roles = get_roles(champion_roles, champions)
    print(roles)
Example #5
0
 def roleidentification(self):
     resp = {}
     for team in self.teams:
         roles = dict_key_value_swap(
             roleidentification.get_roles(champion_roles.get(), [
                 participant.champion_id
                 for participant in team.participants
             ]))
         resp[team.id] = roles
         for participant in team.participants:
             participant.timeline.position = roles[participant.champion_id]
             participant.timeline._meta.data['position'] = roles[
                 participant.champion_id]
     return resp
Example #6
0
        game_duration = float(split[columns_mapper['gameDuration']])

        participant_identities = json.loads(split[columns_mapper['participantIdentities']] \
                                            .replace('\'', '\"'))

        participants = json.loads(split[columns_mapper['participants']] \
                                  .replace('\'', '\"') \
                                  .replace('False', '0') \
                                  .replace('True', '1'))

        champions = []
        for participant in participants:
            champions.append(participant['championId'])

        roles = list(get_roles(champion_roles, champions[0:5]).items())
        roles += list(get_roles(champion_roles, champions[5:10]).items())

        for participantIdentity, participant, role in zip(participant_identities, participants, roles):

            summoner_id = participantIdentity['player']['summonerId']
            role_name = role[0]

            participant_stats = participant['stats']
            win = participant_stats['win']
            kills = participant_stats['kills']
            deaths = participant_stats['deaths']
            assists = participant_stats['assists']
            gold_earned = participant_stats['goldEarned']
            total_damage_dealt_to_champions = participant_stats['totalDamageDealtToChampions']
            total_minions_killed = participant_stats['totalMinionsKilled']
Example #7
0
    async def live_match(self,
                         ctx: commands.Context,
                         *,
                         name: str = "Empadão de Tatu"):
        """!live <summoner_name> => Retorna o lobby da partida ao vivo do invocador
        - O invocador DEVE estar em uma partida ao vivo
        - É possível obter informações sobre os participantes da partida em tempo real, utilizando dos botões disponíveis no Embed
        """

        try:
            summoner = watcher.summoner.by_name(region, name)
        except Exception:
            no_summ_embed = discord.Embed(
                description=f"Não consegui encontrar o invocador **{name}**!")
            return await ctx.send(embed=no_summ_embed)

        try:
            spec = watcher.spectator.by_summoner(region, summoner["id"])
        except Exception:
            no_live_match_embed = discord.Embed(
                description=
                f'Parece que o invocador **{summoner["name"]}** não está em uma partida no momento!'
            )
            return await ctx.send(embed=no_live_match_embed)

        participants = spec["participants"]

        blue_champion_id_list = []
        red_champion_id_list = []
        count = 0
        for row in participants:
            # Get list of champions in Blue/Red side
            if count < 5:
                blue_champion_id_list.append(row["championId"])
                count += 1
            else:
                red_champion_id_list.append(row["championId"])
                count += 1
        # Get the Blue/Red side champions roles
        champion_roles = pull_data()
        blue_team = get_roles(champion_roles, blue_champion_id_list)
        red_team = get_roles(champion_roles, red_champion_id_list)

        def get_rank(summonerId):
            current_rank = watcher.league.by_summoner(region, summonerId)
            player_rank = ""

            if current_rank == []:
                player_rank = "UNRANKED"
            else:
                for item in current_rank:
                    if item["queueType"] == "RANKED_SOLO_5x5":
                        player_rank = f'{item["tier"]} {item["rank"]} ({item["leaguePoints"]} LP)'

            return player_rank

        for row in participants:
            # BLUE TEAM
            if row["championId"] == blue_team["TOP"]:
                rank = get_rank(row["summonerId"])
                blue_team.update({
                    "TOP": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == blue_team["JUNGLE"]:
                rank = get_rank(row["summonerId"])
                blue_team.update({
                    "JUNGLE": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == blue_team["MIDDLE"]:
                rank = get_rank(row["summonerId"])
                blue_team.update({
                    "MIDDLE": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == blue_team["BOTTOM"]:
                rank = get_rank(row["summonerId"])
                blue_team.update({
                    "BOTTOM": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == blue_team["UTILITY"]:
                rank = get_rank(row["summonerId"])
                blue_team.update({
                    "UTILITY": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })

            # RED TEAM
            if row["championId"] == red_team["TOP"]:
                rank = get_rank(row["summonerId"])
                red_team.update({
                    "TOP": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == red_team["JUNGLE"]:
                rank = get_rank(row["summonerId"])
                red_team.update({
                    "JUNGLE": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == red_team["MIDDLE"]:
                rank = get_rank(row["summonerId"])
                red_team.update({
                    "MIDDLE": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == red_team["BOTTOM"]:
                rank = get_rank(row["summonerId"])
                red_team.update({
                    "BOTTOM": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })
            elif row["championId"] == red_team["UTILITY"]:
                rank = get_rank(row["summonerId"])
                red_team.update({
                    "UTILITY": {
                        "name": row["summonerName"],
                        "id": row["summonerId"],
                        "champion": dd.get_champion_name(row["championId"]),
                        "championId": row["championId"],
                        "rank": rank,
                    }
                })

        live_match_embed = discord.Embed(
            title=f'Partida ao vivo de {summoner["name"]}',
            url="https://br.op.gg/summoner/userName="******"+".join(name.split(" ")),
        )

        live_match_embed.add_field(
            name="Summoner",
            value=f'🔹 {blue_team["TOP"]["name"]}\n' +
            f'🔹 {blue_team["JUNGLE"]["name"]}\n' +
            f'🔹 {blue_team["MIDDLE"]["name"]}\n' +
            f'🔹 {blue_team["BOTTOM"]["name"]}\n' +
            f'🔹 {blue_team["UTILITY"]["name"]}\n' + "\n" +
            f'🔸 {red_team["TOP"]["name"]}\n' +
            f'🔸 {red_team["JUNGLE"]["name"]}\n' +
            f'🔸 {red_team["MIDDLE"]["name"]}\n' +
            f'🔸 {red_team["BOTTOM"]["name"]}\n' +
            f'🔸 {red_team["UTILITY"]["name"]}\n',
            inline=True,
        )

        live_match_embed.add_field(
            name="Champion",
            value=f'{dd.EMOJI_TOP} {blue_team["TOP"]["champion"]}\n' +
            f'{dd.EMOJI_JUNGLE} {blue_team["JUNGLE"]["champion"]}\n' +
            f'{dd.EMOJI_MIDDLE} {blue_team["MIDDLE"]["champion"]}\n' +
            f'{dd.EMOJI_BOTTOM} {blue_team["BOTTOM"]["champion"]}\n' +
            f'{dd.EMOJI_UTILITY} {blue_team["UTILITY"]["champion"]}\n' + "\n" +
            f'{dd.EMOJI_TOP} {red_team["TOP"]["champion"]}\n' +
            f'{dd.EMOJI_JUNGLE} {red_team["JUNGLE"]["champion"]}\n' +
            f'{dd.EMOJI_MIDDLE} {red_team["MIDDLE"]["champion"]}\n' +
            f'{dd.EMOJI_BOTTOM} {red_team["BOTTOM"]["champion"]}\n' +
            f'{dd.EMOJI_UTILITY} {red_team["UTILITY"]["champion"]}\n',
            inline=True,
        )

        live_match_embed.add_field(
            name="Rank",
            value=f'® {blue_team["TOP"]["rank"]}\n' +
            f'® {blue_team["JUNGLE"]["rank"]}\n' +
            f'® {blue_team["MIDDLE"]["rank"]}\n' +
            f'® {blue_team["BOTTOM"]["rank"]}\n' +
            f'® {blue_team["UTILITY"]["rank"]}\n' + "\n" +
            f'® {red_team["TOP"]["rank"]}\n' +
            f'® {red_team["JUNGLE"]["rank"]}\n' +
            f'® {red_team["MIDDLE"]["rank"]}\n' +
            f'® {red_team["BOTTOM"]["rank"]}\n' +
            f'® {red_team["UTILITY"]["rank"]}\n',
            inline=True,
        )

        message = await ctx.send(embed=live_match_embed)

        # Lidando com os "botões"
        #
        await message.add_reaction("🔹")
        await message.add_reaction("🔸")
        await message.add_reaction("1️⃣")
        await message.add_reaction("2️⃣")
        await message.add_reaction("3️⃣")
        await message.add_reaction("4️⃣")
        await message.add_reaction("5️⃣")
        await message.add_reaction("❌")

        def check(reaction, user):
            return user == ctx.author

        reaction = None
        blue_flag = 1
        red_flag = 0
        command_call_flag_control = 1

        call_summ_msg_embed = discord.Embed(
            description=
            "Utilize os botões acima para obter informações sobre os invocadores"
        )
        call_summ_msg = await ctx.send(embed=call_summ_msg_embed)
        while True:

            if str(reaction) == "🔹":
                blue_flag = 1
                red_flag = 0
            if str(reaction) == "🔸":
                blue_flag = 0
                red_flag = 1

            if str(reaction) == "1️⃣":
                if blue_flag:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=blue_team["TOP"]["name"],
                        current_champion=blue_team["TOP"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
                else:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=red_team["TOP"]["name"],
                        current_champion=red_team["TOP"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
            elif str(reaction) == "2️⃣":
                if blue_flag:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=blue_team["JUNGLE"]["name"],
                        current_champion=blue_team["JUNGLE"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
                else:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=red_team["JUNGLE"]["name"],
                        current_champion=red_team["JUNGLE"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
            elif str(reaction) == "3️⃣":
                if blue_flag:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=blue_team["MIDDLE"]["name"],
                        current_champion=blue_team["MIDDLE"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
                else:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=red_team["MIDDLE"]["name"],
                        current_champion=red_team["MIDDLE"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
            elif str(reaction) == "4️⃣":
                if blue_flag:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=blue_team["BOTTOM"]["name"],
                        current_champion=blue_team["BOTTOM"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
                else:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=red_team["BOTTOM"]["name"],
                        current_champion=red_team["BOTTOM"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
            elif str(reaction) == "5️⃣":
                if blue_flag:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=blue_team["UTILITY"]["name"],
                        current_champion=blue_team["UTILITY"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
                else:
                    await ctx.invoke(
                        self.bot.get_command("summ"),
                        name=red_team["UTILITY"]["name"],
                        current_champion=red_team["UTILITY"]["championId"],
                        command_call_flag=command_call_flag_control,
                        msg=call_summ_msg,
                    )
            elif str(reaction) == "❌":
                await call_summ_msg.delete()
                await message.clear_reactions()
                await message.delete()
                return

            try:
                reaction, user = await self.bot.wait_for("reaction_add",
                                                         timeout=90.0,
                                                         check=check)

                if str(reaction) == "🔹" and not blue_flag:
                    await message.remove_reaction("🔸", user)
                elif str(reaction) == "🔸" and not red_flag:
                    await message.remove_reaction("🔹", user)
                else:
                    await message.remove_reaction(reaction, user)
            except Exception:
                break

        await message.clear_reactions()
Example #8
0
def create_match_row(players_perfomance_at_10, players_events_at_10,
                     participant_game_info, champion_roles, match_id):
    '''
     Essa função toma como parâmetro obrigatório 3 DataFrames, o match_id (int) e o objeto champion_roles.

     Ela une todos as informações, eventos e estatísticas de uma partida reunidas utilizando as funçoes desse arquivo em
     apenas uma linha, transformando a partida em uma única observação. 
    '''

    # Merge nos DataFrames de Entrada
    full_players_info = participant_game_info.merge(players_perfomance_at_10,
                                                    on='participantId')
    full_players_info = full_players_info.merge(players_events_at_10,
                                                on='participantId')

    # Dicionário definindo a função agregadora de acordo com a estatística
    agg_func = {
        'totalGold': 'sum',
        'isWinner': 'max',
        'xp': 'sum',
        'minionsKilled': 'sum',
        'jungleMinionsKilled': 'sum',
        'wardsPlaced': 'sum',
        'wardsKilled': 'sum',
        'nKills': 'sum',
        'nDeaths': 'sum',
        'nAssists': 'sum',
        'firstBlood': 'max',
        'firstTower': 'max',
        'midTowersDestroyed': 'max',
        'botTowersDestroyed': 'max',
        'topTowersDestroyed': 'max',
        'inhibitorsDestroyed': 'max',
        'fireDragonsDestroyed': 'max',
        'airDragonsDestroyed': 'max',
        'waterDragonsDestroyed': 'max',
        'earthDragonsDestroyed': 'max',
        'riftHeraldDestroyed': 'max'
    }

    # Unir os players por time (DataFrame dos times > 2 observações)
    grouped_by_team = full_players_info.groupby('teamId').agg(
        agg_func).sort_index()

    # Utilizando o objeto champion_roles, definir a role de cada campeão e adiciono ao DataFrame dos times
    champions_100 = full_players_info[full_players_info.teamId ==
                                      100].championId.tolist()
    roles_100 = get_roles(champion_roles, champions_100)

    champions_200 = full_players_info[full_players_info.teamId ==
                                      200].championId.tolist()
    roles_200 = get_roles(champion_roles, champions_200)

    for k, v in roles_100.items():
        pairs = [v, roles_200[k]]
        grouped_by_team[k] = pairs

    # Desenrolar o DataFrame dos times e alterar a nomenclatura das colunas pra facilitar a análise
    match_row = grouped_by_team.unstack().to_frame().T
    match_row.columns = match_row.columns.map('{0[0]}_{0[1]}'.format)
    match_row.columns = match_row.columns.str.replace('_100', '_red')
    match_row.columns = match_row.columns.str.replace('_200', '_blue')

    # Adicionar o match_id ao DataFrame pra facilitar o controle de partidas
    match_row['gameID'] = match_id

    return match_row[[
        'gameID', 'isWinner_blue', 'totalGold_red', 'xp_red', 'nKills_red',
        'nDeaths_red', 'nAssists_red', 'minionsKilled_red',
        'jungleMinionsKilled_red', 'wardsPlaced_red', 'wardsKilled_red',
        'firstBlood_red', 'firstTower_red', 'midTowersDestroyed_red',
        'botTowersDestroyed_red', 'topTowersDestroyed_red',
        'inhibitorsDestroyed_red', 'fireDragonsDestroyed_red',
        'airDragonsDestroyed_red', 'waterDragonsDestroyed_red',
        'earthDragonsDestroyed_red', 'riftHeraldDestroyed_red', 'TOP_red',
        'JUNGLE_red', 'MIDDLE_red', 'BOTTOM_red', 'UTILITY_red',
        'totalGold_blue', 'xp_blue', 'nKills_blue', 'nDeaths_blue',
        'nAssists_blue', 'minionsKilled_blue', 'jungleMinionsKilled_blue',
        'wardsPlaced_blue', 'wardsKilled_blue', 'firstBlood_blue',
        'firstTower_blue', 'midTowersDestroyed_blue',
        'botTowersDestroyed_blue', 'topTowersDestroyed_blue',
        'inhibitorsDestroyed_blue', 'fireDragonsDestroyed_blue',
        'airDragonsDestroyed_blue', 'waterDragonsDestroyed_blue',
        'earthDragonsDestroyed_blue', 'riftHeraldDestroyed_blue', 'TOP_blue',
        'JUNGLE_blue', 'MIDDLE_blue', 'BOTTOM_blue', 'UTILITY_blue'
    ]]