def getAvgPerformance(participant, guessedRole=""):
	champ = participant.champion
	if guessedRole != "":
		role = roleCorr[guessedRole]
		lane = laneCorr[guessedRole]
	else:
		role = participant.timeline.role.name
		lane = participant.timeline.lane.name
	matchList = riotapi.get_match_list(participant.summoner, num_matches=10, ranked_queues=QUEUES, champions=champ, seasons=["SEASON2015", 'SEASON2016'])
	if len(matchList) < 5:
		print 'Not enough matches found as %s for %s.' % (champ, participant.summoner_name)
		print 'Searching for other games as %s %s' % (role, lane)
		modList = []
		count = 0
		matchList = riotapi.get_match_list(participant.summoner, num_matches=100, ranked_queues=QUEUES, seasons=["SEASON2015", 'SEASON2016'])
		for match in matchList:
			if (match.role.name == role) and match.lane.name == lane:
				count += 1
				modList.append(match)
			if count > 20:
				break
		matchList = modList
	if len(matchList) == 0:
		print 'No ranked data found for %s' % (participant.summoner_name)
		print 'Looking at all games...'
		matchList = riotapi.get_match_list(participant.summoner, num_matches=100, ranked_queues=QUEUES, seasons=["SEASON2015", 'SEASON2016'])
		print len(matchList)
	if len(matchList) == 0:
		print len(matchList)
		return None
	#Add in match win percentages with champ/role, return that as well
	return averageMatches(participant, matchList)

# print getAvgPerformance(testFile[0].participants[1])
def getAvgPerformance(participant, guessedRole=""):
	'''
	Returns 3 things:
	1 (np.array): Average performance for last 5 games (for classification)
	2 (np.array): Average performance non-normalized (for website display)
	3 (string): Player's rank
	'''
	champ = participant.champion
	if guessedRole != "":
		role = roleCorr[guessedRole]
		lane = laneCorr[guessedRole]
	else:
		role = participant.timeline.role.name
		lane = participant.timeline.lane.name
	matchList = riotapi.get_match_list(participant.summoner, num_matches=10, ranked_queues=QUEUES, champions=champ, seasons=["SEASON2015", 'SEASON2016'])
	if len(matchList) < 5:
		print 'Not enough matches found as %s for %s.' % (champ, participant.summoner_name)
		print 'Searching for other games as %s %s' % (role, lane)
		modList = []
		count = 0
		matchList = riotapi.get_match_list(participant.summoner, num_matches=100, ranked_queues=QUEUES, seasons=["SEASON2015", 'SEASON2016'])
		for match in matchList:
			if (match.role.name == role) and match.lane.name == lane:
				count += 1
				modList.append(match)
			if count > 20:
				break
		matchList = modList
	if len(matchList) == 0:
		print 'No ranked data found for %s' % (participant.summoner_name)
		print 'Looking at all games...'
		matchList = riotapi.get_match_list(participant.summoner, num_matches=100, ranked_queues=QUEUES, seasons=["SEASON2015", 'SEASON2016'])
	if len(matchList) == 0:
		return None
	return averageMatches(participant, matchList)
def extract_participant(sum_name):
    quetype=Queue.ranked_solo
    myseason=Season.season_5
    summoner = riotapi.get_summoner_by_name(sum_name)
    mygamelist=riotapi.get_match_list(summoner, num_matches=2, ranked_queues=quetype, seasons=myseason) #matchlist objects
    mydict= dict()
    yolo=[]
#    for i in range(0, 500, 50):
    for game in mygamelist:
        #mydict[game.id]=[]
        for i in range(0,10):
            participant=game.match().participants[i]
            champstat=participant.summoner.ranked_stats(season=myseason)[participant.champion]
            participant_list=[]
            #participant_list.append(game.id)
            participant_list.append(participant.summoner_name)
            participant_list.append(participant.champion.id)
            participant_list.append(champstat.kda)
            participant_list.append(champstat.wins/champstat.games_played)
            participant_list.append(champstat.kills)
            participant_list.append(champstat.deaths)
            participant_list.append(champstat.assists)
            participant_list.append(str(participant.side)[5:])
            yolo.append(participant_list)
            #mydict[game.id]=participant_list
    return yolo
def amassSummoners(targetLeague, seedSummoner, returnDict, threshold=110):
	'''Will take a target league and a starting seed and use the seed to do a branching
	   search for summoners that have reached the target league.
	   If threshold not met, runs recursively on a random summoner already found.
	   Returns a dict of summoner objects {Summoner name : Summoner object}
	'''
	if (type(seedSummoner) == str):
		print "Searching for summoners related to %s..." % (seedSummoner)
		seed = riotapi.get_summoner_by_name(seedSummoner)
	else:
		print "Searching for summoners related to %s..." % (seedSummoner.name)
		seed = seedSummoner
	matchList = riotapi.get_match_list(seed, ranked_queues=QUEUES, seasons="SEASON2015")
	counter = 0
	summonerDict = returnDict
	for i in range(len(matchList)):	
		try:	#Had issues with get_match request failing so wrapped in a try block
			currentMatch = riotapi.get_match(matchList[i])
			for participant in currentMatch.participants:
				try:
					if (participant.previous_season_tier.name == targetLeague) & (participant.summoner_name not in summonerDict):
						summonerDict[participant.summoner_name] = participant.summoner
						counter += 1
						print "##### Target found ######"
				except ValueError:
					continue
			if counter >= 10: break  	#Break after 10 summoners grabbed to increase spread
		except:
			print "Summoner pull failed."
	if len(summonerDict.keys()) < threshold:
		print "Current no. of summoners in %s: %d" % (targetLeague, len(summonerDict.keys()))
		summonList = summonerDict.values()
		summonerDict = amassSummoners(targetLeague, summonList[counter/2], summonerDict)
	return summonerDict
Exemple #5
0
def collectMatches(targetLeague, summonerList):
    '''Given a list of summoner objects and a target league, will search through the match
	   history of each summoner for games where the majority of participants are in the 
	   target league. If found, adds to the matchDict. Will only pull 10 games per summoner
	   Returns a dict of Match objects { MatchID : Match Vector}
	'''
    matchDict = {}
    deathDict = {}
    for i in range(len(summonerList)):
        print "--------------------------------"
        counter = 0
        searched = 100
        try:
            matchList = riotapi.get_match_list(summonerList[i],
                                               num_matches=100,
                                               ranked_queues=QUEUES,
                                               seasons="SEASON2015")
        except:
            continue
        print "Looking at %s's match history..." % (summonerList[i].name)
        for i in range(len(matchList)):
            try:
                currentMatch = riotapi.get_match(matchList[i])
                majorityDict = {
                    'unranked': 0,
                    'bronze': 0,
                    'silver': 0,
                    'gold': 0,
                    'platinum': 0,
                    'diamond': 0,
                    'master': 0,
                    'challenger': 0
                }
                for participant in currentMatch.participants:
                    try:
                        majorityDict[
                            participant.previous_season_tier.name] += 1
                    except ValueError:
                        majorityDict['bronze'] += 1
                if (majorityDict[targetLeague] > 3) & (currentMatch.id
                                                       not in matchDict):
                    matchDict[currentMatch.id] = parseMatch.processMatch(
                        currentMatch)
                    deathDict[currentMatch.id] = parseMatch.getDeaths(
                        currentMatch)
                    counter += 1
                if counter == 10:  #Break after 10 games retrieved
                    searched = i + 1
                    break
            except:
                print "Match pull failed."
        print "%d found out of %d searched" % (counter, searched)
        print "Current no. of %s matches: %d" % (targetLeague,
                                                 len(matchDict.values()))
    return matchDict, deathDict
Exemple #6
0
def main():

    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.eager)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")

    match_list = riotapi.get_match_list(gigglepuss)
    sub_list = match_list[:10]
    matchid = []
    versionpatch = []
    maptype = []
    queue = []

    p1name = []
    p1side = []
    p1champ = []
    p1lane = []
    p1role = []
    p1gold = []
    p1win = []


    for i in range(len(sub_list)):
        match = riotapi.get_match(match_list[i])

        matchid.append(match.id)
        versionpatch.append(match.version)
        maptype.append(match.map)
        queue.append(match.queue)

        p1name.append(match.participants[0].summoner_name)
        p1side.append(match.participants[0].side)
        p1champ.append(match.participants[0].champion.name)
        p1lane.append(match.participants[0].timeline.lane)
        p1role.append(match.participants[0].timeline.role)
        p1gold.append(match.participants[0].stats.gold_earned)
        p1win.append(match.participants[0].stats.win)

    filename = "test_data.csv"
    columns = ['matchid', 'versionpatch', 'maptype', 'queue', 'p1name', 'p1side', 'p1champ', 'p1lane', 'p1role', 'p1gold', 'p1win']
    df = pd.DataFrame([matchid, versionpatch, maptype, queue, p1name, p1side, p1champ, p1lane, p1role, p1gold, p1win], index = columns)

    df = df.T
    df.to_csv(filename)

    print(df)
Exemple #7
0
def isSupport(summname, region):
    """Returns True if the summoner is a support main, False otherwise."""
    #initalize variables
    summoner = riotapi.get_summoner_by_name(summname)
    riotapi.set_region(region)
    match_history = riotapi.get_match_list(summoner, 5)
    counter = 0
    for match in match_history:
        if str(match.role) == 'Role.support':
            counter += 1
        if counter == 3:
            return True
    return False
Exemple #8
0
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.eager)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")

    match_list = riotapi.get_match_list(gigglepuss)
    match = riotapi.get_match(match_list[0])

    print("  Match ID: {0}".format(match.id))
    print("  Version/Patch: {0}".format(match.version))
    print("  Map: {0}".format(match.map))
    print("  Queue: {0}".format(match.queue))

    print()

    # Print participant information (not summoner information)
    for participant in match.participants:
        print("  {0}".format(participant.summoner_name))
        print("  {0}".format(participant.summoner_id))
        print("    Champion: {0}".format(participant.champion.name))
        print("    Won: {0}".format(participant.stats.win))
        print("    Side: {0}".format(participant.side))
        print("    Gold earned: {0}".format(participant.stats.gold_earned))
        print("    Lane: {0}".format(participant.timeline.lane))
        print("    Role: {0}".format(participant.timeline.role))










    matchid = []
	versionpatch = []
	maptype = []
	queue = []

	p1name = []
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    key = os.environ[
        "DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.lazy)

    dyrus = riotapi.get_summoner_by_name("Dyrus")  # SummonerID is 5908
    # dyrus = riotapi.get_summoner_by_id(5908)  # You could use this as well

    match_list = riotapi.get_match_list(dyrus)

    num_matches = 20

    kills = 0
    deaths = 0
    assists = 0

    print("Calculating K/D/A from the past {0} matches...".format(num_matches))

    for i, match_reference in enumerate(match_list[0:num_matches]):
        match = riotapi.get_match(match_reference)
        for participant in match.participants:
            if participant.summoner_id == dyrus.id:
                kills += participant.stats.kills
                deaths += participant.stats.kills
                assists += participant.stats.assists
        kda = (kills + assists) / deaths
        print(
            "Rolling K/D/A for {0}:  {1}/{2}/{3} == {4} over most recent {5} matches"
            .format(dyrus.name, kills, deaths, assists, round(kda, 3), i + 1))

    print("Final average K/D/A:  {0}/{1}/{2} == {3} over past {4} matches".
          format(kills, deaths, assists, round(kda, 3), num_matches))

    print()
    print(
        "If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information."
    )
    stats = riotapi.get_stats(dyrus)
    stats = stats[StatSummaryType.ranked_fives].stats
    print("Total ranked K/D/A for {0}:  {1}/{2}/{3} == {4}".format(
        dyrus.name, stats.kills, stats.deaths, stats.assists,
        round(stats.kda, 3)))
Exemple #10
0
def amassSummoners(targetLeague, seedSummoner, returnDict, threshold=1):
    '''Will take a target league and a starting seed and use the seed to do a branching
	   search for summoners that have reached the target league.
	   If threshold not met, runs recursively on a random summoner already found.
	   Returns a dict of summoner objects {Summoner name : Summoner object}
	'''
    if (type(seedSummoner) == str):
        print "Searching for summoners related to %s..." % (seedSummoner)
        seed = riotapi.get_summoner_by_name(seedSummoner)
    else:
        print "Searching for summoners related to %s..." % (seedSummoner.name)
        seed = seedSummoner
    matchList = riotapi.get_match_list(seed,
                                       ranked_queues=QUEUES,
                                       seasons="SEASON2015")
    counter = 0
    summonerDict = returnDict
    for i in range(len(matchList)):
        try:  #Had issues with get_match request failing so wrapped in a try block
            currentMatch = riotapi.get_match(matchList[i])
            for participant in currentMatch.participants:
                try:
                    if (participant.previous_season_tier.name
                            == targetLeague) & (participant.summoner_name
                                                not in summonerDict):
                        summonerDict[
                            participant.summoner_name] = participant.summoner
                        counter += 1
                        print "##### Target found ######"
                except ValueError:
                    continue
            if counter >= 10:
                break  #Break after 10 summoners grabbed to increase spread
        except:
            print "Summoner pull failed."
    if len(summonerDict.keys()) < threshold:
        print "Current no. of summoners in %s: %d" % (targetLeague,
                                                      len(summonerDict.keys()))
        summonList = summonerDict.values()
        summonerDict = amassSummoners(targetLeague, summonList[counter / 2],
                                      summonerDict)
    return summonerDict
Exemple #11
0
def summoner(sumName):
    # images_names = os.listdir('myapplication/static/images/planes')
    # planeswalkerNames = planeswalker_dict.keys()
    username = riotapi.get_summoner_by_name(sumName)
    # rankedstats = riotapi.get_ranked_stats(sumName)
    champions = riotapi.get_champions()
    # championIds = riotapi.get_champions()
    # mapping = {champion.id: champion.name for champion in championIds}
    #
    # runes = riotapi.get_rune_pages(sumName)
    sumId = username.id
    match1 = riotapi.get_match_list(username, 3)
    championName = riotapi.get_champion_by_name(match1)
    # match = riotapi.get_match(2034758953)
    masteryStats = riotapi.get_champion_mastery_score(username)
    return render_template('testhome.html',
                           summoner=username,
                           champions=champions,
                           match=match1,
                           championName=championName,
                           masteryscore=masteryStats)
def collectMatches(targetLeague, summonerList):
	'''Given a list of summoner objects and a target league, will search through the match
	   history of each summoner for games where the majority of participants are in the 
	   target league. If found, adds to the matchDict. Will only pull 10 games per summoner
	   Returns a dict of Match objects { MatchID : Match Vector}
	'''
	matchDict = {}
	deathDict = {}
	for i in range(len(summonerList)):
		print "--------------------------------"
		counter = 0
		searched = 100
		try:
			#Removing season requirement: , seasons="SEASON2015"
			matchList = riotapi.get_match_list(summonerList[i], num_matches=100, ranked_queues=QUEUES)
		except:
			continue
		print "Looking at %s's match history..." % (summonerList[i].name)
		for i in range(len(matchList)):
			try:
				currentMatch = riotapi.get_match(matchList[i])
				majorityDict = {'unranked':0, 'bronze':0, 'silver':0, 'gold':0, 'platinum':0, 'diamond':0, 'master':0, 'challenger':0}
				for participant in currentMatch.participants:
					try:
						majorityDict[participant.previous_season_tier.name] += 1
					except ValueError:
						majorityDict['bronze'] += 1
				if (majorityDict[targetLeague] > 3) & (currentMatch.id not in matchDict):
					matchDict[currentMatch.id] = parseMatch.processMatch(currentMatch)
					deathDict[currentMatch.id] = parseMatch.getDeaths(currentMatch)
					counter += 1
				if counter == 10:		#Break after 10 games retrieved
					searched = i+1
					break
			except:
				print "Match pull failed."
		print "%d found out of %d searched" % (counter, searched)
		print "Current no. of %s matches: %d" % (targetLeague, len(matchDict.values()))
	return matchDict, deathDict
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.lazy)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")  # SummonerID is 5908
    # dyrus = riotapi.get_summoner_by_id(5908)  # You could use this as well

    match_list = riotapi.get_match_list(gigglepuss)

    num_matches = 20

    kills = 0
    deaths = 0
    assists = 0

    print("Calculating K/D/A from the past {0} matches...".format(num_matches))

    for i, match_reference in enumerate(match_list[0:num_matches]):
        match = riotapi.get_match(match_reference)
        for participant in match.participants:
            if participant.summoner_id == gigglepuss.id:
                kills += participant.stats.kills
                deaths += participant.stats.kills
                assists += participant.stats.assists
        kda = (kills + assists) / deaths
        print("Rolling K/D/A for {0}:  {1}/{2}/{3} == {4} over most recent {5} matches".format(gigglepuss.name, kills, deaths, assists, round(kda, 3), i + 1))

    print("Final average K/D/A:  {0}/{1}/{2} == {3} over past {4} matches".format(kills, deaths, assists, round(kda, 3), num_matches))

    print()
    print("If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information.")
    stats = riotapi.get_stats(gigglepuss)
    stats = stats[StatSummaryType.ranked_fives].stats
    print("Total ranked K/D/A for {0}:  {1}/{2}/{3} == {4}".format(gigglepuss.name, stats.kills, stats.deaths, stats.assists, round(stats.kda, 3)))
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.lazy)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")  # SummonerID is 5908

    match_list = riotapi.get_match_list(gigglepuss)
    match = riotapi.get_match(match_list[0])

    print("Basic match information:")
    print("  Match ID: {0}".format(match.id))
    print("  Version/Patch: {0}".format(match.version))
    print("  Creation date: {0}  (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation))
    print("  Duration: {0}".format(match.duration))
    print("  Map: {0}".format(match.map))
    print("  Mode: {0}".format(match.mode))
    print("  Type: {0}".format(match.type))
    print("  Platform: {0}".format(match.platform))
    print("  Queue: {0}".format(match.queue))
    print("  Region: {0}".format(match.region))
    print("  Season: {0}".format(match.season))
    print("  Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans]))
    print("  Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans]))

    print()

    champion = match.participants["GigglePuss"].champion

    print("You can use special key-words/key-objects to lookup the participants in the match.")
    print("  Lookup via Summoner:        {0}".format(match.participants[gigglepuss]))
    print("  Lookup via summoner name:   {0}".format(match.participants["GigglePuss"]))
    print("  Lookup via Champion played: {0}".format(match.participants[champion]))
    print("  Lookup via champion name:   {0}".format(match.participants[champion.name]))
def main():

    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.eager)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")

    match_list = riotapi.get_match_list(gigglepuss)
    sub_list = match_list[:10]
    matchid = []
    versionpatch = []
    maptype = []
    queue = []

    p_names = []
    p_sides = []
    p_champs = []
    p_lanes = []
    p_roles = []
    p_golds = []
    p_wins= []


    for i in range(len(sub_list)):
        match = riotapi.get_match(match_list[i])

        matchid.append(match.id)
        versionpatch.append(match.version)
        maptype.append(match.map)
        queue.append(match.queue)

        p1name = []
        p1side = []
        p1champ = []
        p1lane = []
        p1role = []
        p1gold = []
        p1win = []

        for part in match.participants:
            print(part.summoner_name)
            p1name.append(part.summoner_name)
            p1side.append(part.side)
            p1champ.append(part.champion.name)
            p1lane.append(part.timeline.lane)
            p1role.append(part.timeline.role)
            p1gold.append(part.stats.gold_earned)
            p1win.append(part.stats.win)

        p_names.append(p1name)
        p_sides.append(p1side)
        p_champs.append(p1champ)
        p_lanes.append(p1lane)
        p_roles.append(p1role)
        p_golds.append(p1gold)
        p_wins.append(p1win)

    filename = "test_data.csv"
    columns = ['matchid', 'versionpatch', 'maptype', 'queue', 'p_names', 'p_sides', 'p_champs', 'p_lanes', 'p_roles', 'p_golds', 'p_wins']
    df = pd.DataFrame([matchid, versionpatch, maptype, queue, p_names, p_sides, p_champs, p_lanes, p_roles, p_golds, p_wins], index = columns)

    df = df.T
    df.to_csv(filename)

    print(df)
Exemple #16
0
def begin_crawling(seed_summoner_id, seasons, ranked_queues):
    '''
    Breadth first crawling interations, Summoner -> Match -> Summoner...
    '''
    #seed intialization
    try:
        print('Seed initializing...')
        seed_summoner = riotapi.get_summoner_by_id(seed_summoner_id)
        conn = sqlite3.connect('lola.db')
        conn.execute("INSERT INTO Summoner VALUES('{}','{}',{})".format(
            seed_summoner.id, seed_summoner.name, 0))  #watch out "" / ''
        conn.commit()
        conn.close()
        print('\nInitialization completed.')
    except Exception as e:
        print('\nInitialization failed: ',
              e)  # possibly because the seed is already in database
        pass

    # summoner queue interations
    total_summoner_processed = 0
    total_match_processed = 0
    total_match_cralwed = 0
    total_match_duplicate = 0
    total_match_none = 0
    iteration = 0
    try:
        conn = sqlite3.connect('lola.db')
        queue_summoner_ids = pd.read_sql(
            "SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn)
    except Exception as e:
        raise (e)
    finally:
        conn.close()
    while not queue_summoner_ids.empty:
        print('\nSummoner Queue Length:', len(queue_summoner_ids))
        iteration += 1  # only a relative number because of crawling restrarts
        print('Iteration', iteration, 'in the process...')
        queue_summoner_ids_list = list(queue_summoner_ids['summoner_id'])
        random.shuffle(queue_summoner_ids_list)
        for summoner_id in queue_summoner_ids_list[:]:  # pd.dataframe to list of list(queue_summoner_ids['summoner_id'])
            conn = sqlite3.connect('lola.db')
            summoner = riotapi.get_summoner_by_id(summoner_id)
            match_reference_list = riotapi.get_match_list(
                summoner=summoner,
                seasons=seasons,
                ranked_queues=ranked_queues)

            if match_reference_list is None:  # TODO: tag this summoner to be 400/404 status (or the loop may happen quite rarely)
                print("Summoner {} has None MatchList, skip..".format(
                    summoner_id))
                continue

            print('\nSummoner {} ({}) in {}, {}: '.format(
                summoner.name, summoner.id, ranked_queues, seasons))
            print('Total Match Number of the summoner: {}'.format(
                len(match_reference_list)))

            match_no = 0  # crawled + duplicate + none
            crawled_match_no = 0
            duplicate_match_no = 0
            none_match_no = 0
            for mf in match_reference_list[:]:
                if is_match_duplicate(mf, conn) == False:
                    try:
                        # TODO: urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>
                        match = riotapi.get_match(
                            mf)  # match reference -> match
                    except Exception as e:
                        raise (e)
                    # may be None even if mf is not None, see https://github.com/meraki-analytics/cassiopeia/issues/57
                    # can not use != because of Match.__eq__ use Match.id
                    if match is None:
                        none_match_no += 1
                        continue  # jump to the next interation
                    match_to_sqlite(match, summoner, conn)
                    # match is crawled
                    conn.execute(
                        "UPDATE Match SET is_crawled = 1 WHERE match_id='{}'".
                        format(mf.id))
                    crawled_match_no += 1
                else:
                    duplicate_match_no += 1
                match_no += 1
                if match_no % 10 == 0:
                    print(match_no, 'matches in', len(match_reference_list),
                          'processed.')
            # summoner has been crawled
            conn.execute(
                "UPDATE Summoner SET is_crawled = 1 WHERE summoner_id='{}'".
                format(summoner_id))
            conn.commit()  # commit after every summoner finished
            conn.close()
            # sums of different kinds of matches
            total_summoner_processed += 1
            total_match_processed += match_no
            total_match_cralwed += crawled_match_no
            total_match_duplicate += duplicate_match_no
            total_match_none += none_match_no
            print('\ntotal processed summoner:', total_summoner_processed,'\ntotal processed match:', total_match_processed, \
                  '\ntotal crawled match', total_match_cralwed, '\ntotal duplicate match:', total_match_duplicate,  \
                  '\ntotal none match:', total_match_none)

        # read new queue for next iteration
        try:
            conn = sqlite3.connect('lola.db')
            queue_summoner_ids = pd.read_sql(
                "SELECT summoner_id FROM Summoner WHERE is_crawled=0",
                conn)  #update queue
        except Exception as e:
            raise (e)
        finally:
            conn.close()
  - Timeline
    - Frames [Frame]
      - Events [Event]
  - Team
'''

riotapi.set_region("NA")
riotapi.set_api_key("") # set your key here

summoner_id='22005573'
seasons = 'PRESEASON2016'
ranked_queues = 'RANKED_SOLO_5x5'
summoner = riotapi.get_summoner_by_id(summoner_id)    

#match
match_list = riotapi.get_match_list(summoner=summoner, seasons=seasons, ranked_queues=ranked_queues)
match_reference = match_list[0]
match = riotapi.get_match(match_reference)
match_reference_1 = match_list[1]
match_1 = riotapi.get_match(match_reference_1)
version = match.version
duration = math.ceil((match.duration).total_seconds() / 60) #minute
data = match.data
#team
team = match.red_team
team_participant = team[0]
team_bans = team.bans
team_win = team.win
team_dragon_kills = team.dragon_kills
team_baron_kills = team.baron_kills
team_side = str(team.side)[5:]
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428"
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.lazy)

    gigglepuss = riotapi.get_summoner_by_name("GigglePuss")  # SummonerID is 5908

    match_list = riotapi.get_match_list(gigglepuss)
    match = riotapi.get_match(match_list[0])

    print("Basic match information:")
    print("  Match ID: {0}".format(match.id))
    print("  Version/Patch: {0}".format(match.version))
    print("  Creation date: {0}  (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation))
    print("  Duration: {0}".format(match.duration))
    print("  Map: {0}".format(match.map))
    print("  Mode: {0}".format(match.mode))
    print("  Type: {0}".format(match.type))
    print("  Platform: {0}".format(match.platform))
    print("  Queue: {0}".format(match.queue))
    print("  Region: {0}".format(match.region))
    print("  Season: {0}".format(match.season))
    print("  Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans]))
    print("  Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans]))

    print()

    champion = match.participants["GigglePuss"].champion

    print("You can use special key-words/key-objects to lookup the participants in the match.")
    print("  Lookup via Summoner:        {0}".format(match.participants[gigglepuss]))
    print("  Lookup via summoner name:   {0}".format(match.participants["GigglePuss"]))
    print("  Lookup via Champion played: {0}".format(match.participants[champion]))
    print("  Lookup via champion name:   {0}".format(match.participants[champion.name]))

    print()

    # Print some basic information about the summoners in the game that doesn't require calls to the Summoner API.
    # If you ask for participant.summoner, Casseopeia will make a call to the Summoner API to get the full summoner information.
    print("Basic summoner information:")
    for participant in match.participants:
        print("  {0} ({1}) played {2}".format(participant.summoner_name, participant.summoner_id, participant.champion.name))

    print()

    # Print participant information (not summoner information)
    print("Participant information for this match:")
    for participant in match.participants:
        print("  {0}".format(participant.summoner_name))
        print("    Champion: {0}".format(participant.champion.name))
        print("    Won: {0}".format(participant.stats.win))
        print("    Side: {0}".format(participant.side))
        print("    Kills: {0}".format(participant.stats.kills))
        print("    Deaths: {0}".format(participant.stats.deaths))
        print("    Assists: {0}".format(participant.stats.assists))
        print("    KDA: {0}".format(participant.stats.kda))
        print("    CS: {0}".format(participant.stats.cs))
        print("    Summoner spells: {0} + {1}".format(participant.summoner_spell_d, participant.summoner_spell_f))
        print("    Champion Level: {0}".format(participant.stats.champion_level))
        print("    Got first blood: {0}".format(participant.stats.first_blood))
        print("    Gold earned: {0}".format(participant.stats.gold_earned))
        print("    Gold spent: {0}".format(participant.stats.gold_spent))
        print("    Items: {0}".format([item.name if item is not None else None for item in participant.stats.items]))
        print("    Magic Damage Dealt: {0}".format(participant.stats.magic_damage_dealt))
        print("    Physical Damage Dealt: {0}".format(participant.stats.physical_damage_dealt))
        print("    Lane: {0}".format(participant.timeline.lane))
        print("    Role: {0}".format(participant.timeline.role))

    print()

    print("Timestamp of last frame: {0}".format(match.frames[-1].timestamp))
    print("Number of events in last frame: {0}".format(len(match.frames[-1].events)))

    print("What's up with the bans?")
		return avg[504:567]
	if role == "redADC":
		return avg[567:630]


riotapi.set_region("NA")
riotapi.set_api_key("bf735671-a14a-4c52-8e02-ed476b7f8434")
riotapi.set_rate_limits((10, 10), (500, 600))
global QUEUES
QUEUES = ["RANKED_TEAM_5x5", "RANKED_SOLO_5x5", "RANKED_PREMADE_5x5"]

summonerNames = ["Blazed Aldrin", "Tahola", "Smoakee", "NSCrafting", "ZSlayer93", "Shintopher"]
matchList = []
for name in summonerNames:
	summoner = riotapi.get_summoner_by_name(name)
	matchList += riotapi.get_match_list(summoner, ranked_queues=QUEUES)[:25]
correct = 0.0
total = 0.0
blueGuess = 0.0
redGuess = 0.0
model = pickle.load(open('model'))['gold']
random.shuffle(matchList)
for i in range(len(matchList)):
	try:
		testMatch = matchList[i].match(include_timeline=True)
	except:
		continue
	matchClass = parseMatch.getWinner(testMatch)
	roleMap = parseMatch.getRoles(testMatch)
	inv_map = {v: k for k, v in roleMap.items()}
	statMap = {}
Exemple #20
0
def matchlistpage(zone, name):


    # Set region and after region is set, fetch latest API version, maybe move the version to a scheduled task if it uses a call.
    riotapi.set_region(zone)

    if zone in ['na', 'kr', 'euw', 'eune']:
        cassdb = SQLAlchemyDB(connector, host, dbnames[zone]+"?charset=utf8", user, passwd)
        riotapi.set_data_store(cassdb)

    print("======================")
    print(zone)
    print(name)
    print("======================")

    patch = riotapi.get_versions()[0]


    # Used to convert numerals to/from numbers
    romans =    {
                    'I': 1,
                    'II': 2,
                    'III': 3,
                  'IV': 4,
                  'V': 5
                }


    print("==========   DB MADE Trying to get summoner by name     ===========")
    # Get summoner
    s = riotapi.get_summoner_by_name(name)
    print("Summoner object:")
    print(s)
    print("id:{} name:{} level:{}".format(s.id, s.name, s.level))
    print("==========   GOT S, trying to get league entries     ===========")
    try:
        le = riotapi.get_league_entries_by_summoner(s)[0]
        entry = le.entries[0]
        print("Got league entries for ranked")
    except:
        print("Couldnt fetch le/entry. Perhaps unranked.")
        le = None
        entry = None
    print("==========   Trying to get ranked stats     ===========")
    try:
        stats = riotapi.get_ranked_stats(s, season=None)[None]
    except:
        print("Couldnt fetch ranked stats. Maybe not lv30/never did ranked.")
        stats = None
    print("==========   Trying to get matches     ===========")
    ml = riotapi.get_match_list(s, seasons=[x.value for x in Season][-1], num_matches=10)
    if ml is not None:
        matches = [][-10:]
        for x in ml:
            try:
                m_to_add = riotapi.get_match(x)
                matches.append(m_to_add)
            except exc.IntegrityError as ie:
                print("==SQL ERROR ---> {}".format(ie))
                print("==Python traceback==")
                print(traceback.print_exc())
                cassdb.session.rollback()
    else:
        matches = []



    print("==========   Trying to render template     ===========")


    return render_template('matchlist.html',
                            s = s,
                            entry = entry,
                            le = le,
                            matches = matches,
                            patch = patch,
                            stats = stats,
                            zone = zone,
                            round = round,
                            len = len,
                            romans = romans)
Exemple #21
0
def main():
    # Setup riotapi
    riotapi.set_region("NA")
    riotapi.print_calls(False)
    key = os.environ["DEV_KEY"]  # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here.
    riotapi.set_api_key(key)
    riotapi.set_load_policy(LoadPolicy.lazy)

    dyrus = riotapi.get_summoner_by_name("Dyrus")  # SummonerID is 5908

    match_list = riotapi.get_match_list(dyrus)
    match = riotapi.get_match(match_list[0])

    print("Basic match information:")
    print("  Match ID: {0}".format(match.id))
    print("  Version/Patch: {0}".format(match.version))
    print("  Creation date: {0}  (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation))
    print("  Duration: {0}".format(match.duration))
    print("  Map: {0}".format(match.map))
    print("  Mode: {0}".format(match.mode))
    print("  Type: {0}".format(match.type))
    print("  Platform: {0}".format(match.platform))
    print("  Queue: {0}".format(match.queue))
    print("  Region: {0}".format(match.region))
    print("  Season: {0}".format(match.season))
    print("  Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans]))
    print("  Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans]))

    print()

    champion = match.participants["Dyrus"].champion

    print("You can use special key-words/key-objects to lookup the participants in the match.")
    print("  Lookup via Summoner:        {0}".format(match.participants[dyrus]))
    print("  Lookup via summoner name:   {0}".format(match.participants["Dyrus"]))
    print("  Lookup via Champion played: {0}".format(match.participants[champion]))
    print("  Lookup via champion name:   {0}".format(match.participants[champion.name]))

    print()

    # Print some basic information about the summoners in the game that doesn't require calls to the Summoner API.
    # If you ask for participant.summoner, Casseopeia will make a call to the Summoner API to get the full summoner information.
    print("Basic summoner information:")
    for participant in match.participants:
        print("  {0} ({1}) played {2}".format(participant.summoner_name, participant.summoner_id, participant.champion.name))

    print()

    # Print participant information (not summoner information)
    print("Participant information for this match:")
    for participant in match.participants:
        print("  {0}".format(participant.summoner_name))
        print("    Champion: {0}".format(participant.champion.name))
        print("    Won: {0}".format(participant.stats.win))
        print("    Side: {0}".format(participant.side))
        print("    Kills: {0}".format(participant.stats.kills))
        print("    Deaths: {0}".format(participant.stats.deaths))
        print("    Assists: {0}".format(participant.stats.assists))
        print("    KDA: {0}".format(participant.stats.kda))
        print("    CS: {0}".format(participant.stats.cs))
        print("    Summoner spells: {0} + {1}".format(participant.summoner_spell_d, participant.summoner_spell_f))
        print("    Champion Level: {0}".format(participant.stats.champion_level))
        print("    Got first blood: {0}".format(participant.stats.first_blood))
        print("    Gold earned: {0}".format(participant.stats.gold_earned))
        print("    Gold spent: {0}".format(participant.stats.gold_spent))
        print("    Items: {0}".format([item.name if item is not None else None for item in participant.stats.items]))
        print("    Magic Damage Dealt: {0}".format(participant.stats.magic_damage_dealt))
        print("    Physical Damage Dealt: {0}".format(participant.stats.physical_damage_dealt))
        print("    Lane: {0}".format(participant.timeline.lane))
        print("    Role: {0}".format(participant.timeline.role))

    print()

    print("Timestamp of last frame: {0}".format(match.frames[-1].timestamp))
    print("Number of events in last frame: {0}".format(len(match.frames[-1].events)))
def extract_participant(sum_name, gamecount):
    ##parameters
    quetype=Queue.ranked_solo
    myseason=Season.season_5
    summoner = riotapi.get_summoner_by_name(sum_name)
    #################################### 1 #################################
    #extracting list of objects games
    mygamelist=riotapi.get_match_list(summoner, num_matches=gamecount, ranked_queues=quetype, seasons=myseason)
    #################################### 2 #################################
    #need to partition list of games, to prevent data loss due to random api errors 
    for file in range(0, gamecount, 15):
        yolo_two=[]
        print("i'm starting...", file)
        a=1
        for game in mygamelist[file:file+15]:
            print("for game", a)
            a=a+1
            for i in range(0,10):
                participant=game.match().participants[i] ## +1 api call
                print("1 loop: ",i, "-", cassiopeia.riotapi.get_requests_count())
                #### Random API errors often occur for champstat
                #### This is an algo to re-request to API after an error instead of killing the entire job
                try:
                    champstat = participant.summoner.ranked_stats(season=myseason)[participant.champion] ##+2 api call
                except APIError as error:
                    # Try Again Once
                    if error.error_code in [500]:
                        try:
                            print("Got a 500. retrying after 30sec...")
                            time.sleep(30)
                            champstat=participant.summoner.ranked_stats(season=myseason)[participant.champion] ##+3 api call
                        except APIError as another_error:
                            if another_error.error_code in [500, 400, 404]:
                                try:
                                    print ("got another 500, retrying after 60sec...")
                                    time.sleep(60)
                                    champstat=participant.summoner.ranked_stats(season=myseason)[participant.champion] ##+3 api call
                                except APIError as another_another_error:
                                    if another_error.error_code in [500, 400, 404]:
                                        print("failed on THIRD attempt. just passing")
                                        pass
                                    else:
                                        print("error man...")
                                        raise another_another_error
                            else:
                                print("error man...")
                                raise another_error
                    elif error.error_code in [400, 404]:
                        print("Got a 400 or 404")
                        pass
                    # Fatal
                    else:
                        print("some random error occured")
                        raise error
                
                print("2 loop: ",i, "-", cassiopeia.riotapi.get_requests_count())
                ############################  3 #############################
                #creating a list of stats of each participant(i)
                participant_list=[]
                pergame=champstat.games_played
                participant_list.append(i)
                participant_list.append(game.id)
                participant_list.append(participant.stats.win)
                participant_list.append(participant.side.name)
                participant_list.append(participant.timeline.role)
                participant_list.append(pergame)
                participant_list.append(champstat.wins)
                participant_list.append(champstat.losses)
                participant_list.append(champstat.wins/pergame)
                participant_list.append(champstat.kda)
                participant_list.append(champstat.kills/pergame)
                participant_list.append(champstat.deaths/pergame)
                participant_list.append(champstat.assists/pergame)
                participant_list.append(champstat.gold_earned/pergame)
                participant_list.append(champstat.damage_dealt/pergame)
                participant_list.append(champstat.damage_taken/pergame)
                participant_list.append(champstat.turrets_killed/pergame)
                participant_list.append(champstat.minions_killed/pergame)
                yolo_two.append(participant_list)
                print("3 loop: ",i, "-", cassiopeia.riotapi.get_requests_count())
                #time.sleep(2)
                print("next up is participant:", i+1)
            if i < 15:
                print("waiting 5 sec for the next game")
                time.sleep(5)
        ########################## 4 ################################
        ##writing csv files of 15 games of 150 participants
        with open(str(file)+'testyolo.csv', 'w', encoding='UTF-8', newline='') as testfile:
            a = csv.writer(testfile, delimiter=',')
            a.writerows(yolo_two)
            print("i just did ",file)
            print("Here comes next round of csvfile")
        ## pause for api call limit
        print("waiting 10sec...")
        time.sleep(10)
Exemple #23
0
def begin_crawling(seed_summoner_id, seasons, ranked_queues):
    '''
    Breadth first crawling interations, Summoner -> Match -> Summoner...
    '''
    #seed intialization
    try:
        print('Seed initializing...')
        seed_summoner = riotapi.get_summoner_by_id(seed_summoner_id)    
        conn = sqlite3.connect('lola.db')
        conn.execute("INSERT INTO Summoner VALUES('{}','{}',{})".format(seed_summoner.id, seed_summoner.name, 0)) #watch out "" / ''
        conn.commit()
        conn.close()
        print('\nInitialization completed.')
    except Exception as e:
        print('\nInitialization failed: ', e) # possibly because the seed is already in database
        pass
 
    # summoner queue interations
    total_summoner_processed = 0           
    total_match_processed = 0
    total_match_cralwed = 0
    total_match_duplicate = 0
    total_match_none = 0
    iteration = 0
    try:
        conn = sqlite3.connect('lola.db')
        queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn)
    except Exception as e:
        raise(e)
    finally:
        conn.close()
    while not queue_summoner_ids.empty:
        print('\nSummoner Queue Length:', len(queue_summoner_ids))
        iteration += 1 # only a relative number because of crawling restrarts 
        print ('Iteration', iteration, 'in the process...')
        queue_summoner_ids_list = list(queue_summoner_ids['summoner_id'])
        random.shuffle(queue_summoner_ids_list)
        for summoner_id in queue_summoner_ids_list[:]: # pd.dataframe to list of list(queue_summoner_ids['summoner_id'])
            conn = sqlite3.connect('lola.db')
            summoner = riotapi.get_summoner_by_id(summoner_id)
            match_reference_list = riotapi.get_match_list(summoner=summoner, seasons=seasons, ranked_queues=ranked_queues)

            if match_reference_list is None: # TODO: tag this summoner to be 400/404 status (or the loop may happen quite rarely)
                print("Summoner {} has None MatchList, skip..".format(summoner_id))
                continue

            print('\nSummoner {} ({}) in {}, {}: '.format(summoner.name, summoner.id, ranked_queues, seasons))
            print('Total Match Number of the summoner: {}'.format(len(match_reference_list)))

            match_no = 0 # crawled + duplicate + none
            crawled_match_no = 0
            duplicate_match_no = 0
            none_match_no = 0
            for  mf in match_reference_list[:]:
                if is_match_duplicate(mf, conn) == False:                    
                    try:
                        # TODO: urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>
                        match = riotapi.get_match(mf) # match reference -> match
                    except Exception as e:
                        raise(e)
                    # may be None even if mf is not None, see https://github.com/meraki-analytics/cassiopeia/issues/57 
                    # can not use != because of Match.__eq__ use Match.id 
                    if match is None: 
                        none_match_no += 1
                        continue # jump to the next interation
                    match_to_sqlite(match, summoner, conn)
                    # match is crawled
                    conn.execute("UPDATE Match SET is_crawled = 1 WHERE match_id='{}'".format(mf.id))
                    crawled_match_no += 1
                else :
                    duplicate_match_no += 1
                match_no += 1
                if match_no % 10 == 0:                
                    print (match_no, 'matches in', len(match_reference_list), 'processed.')
            # summoner has been crawled
            conn.execute("UPDATE Summoner SET is_crawled = 1 WHERE summoner_id='{}'".format(summoner_id))
            conn.commit() # commit after every summoner finished
            conn.close()
            # sums of different kinds of matches
            total_summoner_processed += 1            
            total_match_processed += match_no
            total_match_cralwed += crawled_match_no
            total_match_duplicate += duplicate_match_no
            total_match_none += none_match_no
            print('\ntotal processed summoner:', total_summoner_processed,'\ntotal processed match:', total_match_processed, \
                  '\ntotal crawled match', total_match_cralwed, '\ntotal duplicate match:', total_match_duplicate,  \
                  '\ntotal none match:', total_match_none)

        # read new queue for next iteration
        try:
            conn = sqlite3.connect('lola.db')
            queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) #update queue
        except Exception as e:
            raise(e)
        finally:
            conn.close()
Exemple #24
0
def test_match_list():
    int_test_handler.test_result(
        riotapi.get_match_list(
            riotapi.get_summoner_by_id(int_test_handler.summoner_id)))
Exemple #25
0
def cards(request):
	if request.GET:
		riotapi.set_api_key("3ca655bb-959d-4ed3-ab2c-287da159aa59")
		riotapi.set_rate_limits((1500, 10), (90000, 600))
		getted = request.GET
		summoner = getted.get('summ')
		region = getted.get('region')
		riotapi.set_region(region)
		riotapi.print_calls(True)
		try:
			summ = riotapi.get_summoner_by_name(summoner)
		except APIError:
			return HttpResponseRedirect('/dorans/')
		masteries = riotapi.get_champion_masteries(summ)
		trophyChampions = {}
		count = 0
		#this sets up so that champions with lvl 4 or higher mastery but if less than 4 are found add more from lower lvls

		for champion, mastery in masteries.items():
			if mastery.level >= 4 :
				trophyChampions[champion] = mastery
				count = count + 1
		if count < 4:
			for champion, mastery in masteries.items():
				if mastery.level == 3 :
					trophyChampions[champion] = mastery
		displayChampions = []
		summid = riotapi.get_summoner_by_name(summoner).id
		for c in trophyChampions:
			print(c)
			topKDA = 0
			kills = 0
			deaths = 0
			assists = 0
			wins = 0
			losses = 0
			MVP = 0
			try:
				matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016")
			except APIError:
				matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016")
			if not matches:
				continue
			for m in matches:
				try:
					data = riotapi.get_match(m, include_timeline = False)
				except APIError:
					continue
				teamtotal = 0
				tgold = 0
				tdamagedlt = 0
				tdamagetkn = 0
				twards = 0
				twardkls = 0
				for player in data.participants:
					if player.summoner_id == summid: #Build stats from this players participant object
						i = 0
						if player.side.name == 'blue':
							for p in data.participants:
								i +=1
								if i < 5:
									teamtotal += p.stats.kills
									tgold += p.stats.gold_earned
									tdamagedlt +=  p.stats.damage_dealt_to_champions
									tdamagetkn +=  p.stats.damage_taken
									twards +=  p.stats.wards_placed
						else:
							for p in data.participants:
								i += 1
								if i >= 5:
									teamtotal += p.stats.kills
									tgold += p.stats.gold_earned
									tdamagedlt +=  p.stats.damage_dealt_to_champions
									tdamagetkn +=  p.stats.damage_taken
									twards +=  p.stats.wards_placed
						if teamtotal == 0 :
							teamtotal = 1;
						if twards == 0:
							twards == 1;
						topKDA = player.stats.kda if player.stats.kda > topKDA else topKDA
						kills += player.stats.kills
						deaths += player.stats.deaths
						assists += player.stats.assists
						trip = player.stats.triple_kills
						quad = player.stats.quadra_kills
						penta = player.stats.penta_kills
						kp = player.stats.kills/teamtotal
						g = player.stats.gold_earned/tgold
						cs = player.stats.cs/data.duration.seconds
						dmgdlt = player.stats.damage_dealt_to_champions/tdamagedlt
						dmgtkn = player.stats.damage_taken/tdamagetkn
						wards = player.stats.wards_placed/twards
						kda = player.stats.kda
						if kda == 1:
							kda = 1.1
						if kda == 0:
							try:
								kda = .01/p.stats.deaths
							except ZeroDivisionError:
								kda = .1
						if p.timeline.role.name ==  'solo':
							if p.timeline.lane.name == 'mid_lane': #mid
								MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
							else:
								#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  ))
								MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
						elif p.timeline.role.name == 'carry':# carry
							#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 6)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * 1) + (wards *1)  ))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4)  )+ trip * .25 + quad * .5 + penta * 1
						elif p.timeline.role.name == 'support': #supp
							#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *6)  ))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * 1.0)+ (dmgdlt * 6) + (dmgtkn * 7) + (wards *5)  )+ trip * .25 + quad * .5 + penta * 1

						elif p.timeline.role.name == 'none': #jungle
							#print(math.log(kda)/math.log(6))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  )+ trip * .25 + quad * .5 + penta * 1

						else: #unknown duo setup
							#print(math.log(kda)/math.log(6))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 10) + (dmgtkn * 2) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
						
						if player.stats.win:
							wins = wins + 1
						else:
							losses = losses + 1

			championStats = {}
			championStats['level'] = masteries[c].level
			championStats['topGrade'] = masteries[c].highest_grade
			championStats['points'] = masteries[c].points
			championStats['topKDA'] = round(topKDA, 2)
			if deaths == 0:
				deaths = 1
			championStats['KDA'] = round((kills + assists) / deaths , 2)
			championStats['avgkills'] = round(kills / (wins+ losses), 2)
			championStats['avgdeaths'] = round(deaths / (wins+ losses), 2)
			championStats['avgassists'] = round(assists / (wins+ losses), 2)
			championStats['avgMVP'] = round(MVP / (wins + losses), 2)
			championStats['wins'] = wins
			championStats['losses'] = losses
			imagep = c.image.link
			imagep = imagep.split('.')
			image = 'http://ddragon.leagueoflegends.com/cdn/img/champion/loading/' + imagep[0] + '_0.jpg'
			displayChampions.append({'name':str(c), 'stats':championStats, 'mastery': masteries[c], 'masterypoint':masteries[c].points, 'image': image })
		displayChampions = sorted(displayChampions, key=itemgetter('masterypoint'), reverse=True)


		return HttpResponse(render(request, 'doranscards.html', {'champions' : displayChampions}))
	else:
		return HttpResponseRedirect('/dorans/')
Exemple #26
0
def test_match_list():
    int_test_handler.test_result(riotapi.get_match_list(riotapi.get_summoner_by_id(int_test_handler.summoner_id)))