Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import time
- from collections import defaultdict
- from datetime import datetime, timezone
- import requests
- # --- CONFIGURATION ---
- API_KEY = "RGAPI-662ba993-f7f2-41f8-8d03-595f5c83b879"
- GAME_NAME = "cordeeana" # without #
- TAG_LINE = "EUNE" # what comes after #
- REGION = "europe" # "europe" for EUNE/EUW
- START_DATE = "2026-11-14" # <-- PUT THE DATE YOU REACHED GOLD 1 HERE (YYYY-MM-DD)
- QUEUE_ID = 420 # 420 = Ranked Solo/Duo
- DIFF_THRESHOLD = 1.5 # threshold for "Even"
- # ---------------------
- HEADERS = {"X-Riot-Token": API_KEY}
- BASE_URL = f"https://{REGION}.api.riotgames.com"
- def date_to_epoch(date_str: str) -> int:
- dt = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
- return int(dt.timestamp())
- def request_with_retry(url: str, params: dict | None = None) -> dict | list:
- while True:
- r = requests.get(url, headers=HEADERS, params=params)
- if r.status_code == 429:
- wait = int(r.headers.get("Retry-After", 5)) + 1
- print(f" [Rate limit] Waiting {wait}s...")
- time.sleep(wait)
- continue
- r.raise_for_status()
- return r.json()
- def get_puuid(game_name: str, tag_line: str) -> str:
- url = f"{BASE_URL}/riot/account/v1/accounts/by-riot-id/{game_name}/{tag_line}"
- return request_with_retry(url)["puuid"]
- def get_all_match_ids_since(puuid: str, start_time: int, queue: int | None) -> list[str]:
- """Fetches all matches from start_time up to the present."""
- url = f"{BASE_URL}/lol/match/v5/matches/by-puuid/{puuid}/ids"
- all_ids = []
- start = 0
- while True:
- params = {"start": start, "count": 100, "startTime": start_time}
- if queue:
- params["queue"] = queue
- batch = request_with_retry(url, params=params)
- if not batch:
- break
- all_ids.extend(batch)
- start += len(batch)
- if len(batch) < 100:
- break
- time.sleep(0.5)
- return all_ids
- def get_match_details(match_id: str) -> dict:
- url = f"{BASE_URL}/lol/match/v5/matches/{match_id}"
- data = request_with_retry(url)
- time.sleep(1.3)
- return data
- def calc_kda(p: dict) -> float:
- return (p["kills"] + p["assists"]) / max(1, p["deaths"])
- def compute_opgg_like_ranks(participants: list[dict]) -> dict[str, int]:
- """Calculates a 1..10 rank (OP.GG style) for the 10 players in the match."""
- team_kills = {100: 0, 200: 0}
- for p in participants:
- team_kills[p["teamId"]] += p["kills"]
- max_dmg = max((p["totalDamageDealtToChampions"] for p in participants), default=1) or 1
- max_gold = max((p["goldEarned"] for p in participants), default=1) or 1
- max_vis = max((p["visionScore"] for p in participants), default=1) or 1
- scores = []
- for p in participants:
- kda_norm = min(calc_kda(p), 10.0) / 10.0
- kp = (p["kills"] + p["assists"]) / max(1, team_kills[p["teamId"]])
- dmg_norm = p["totalDamageDealtToChampions"] / max_dmg
- gold_norm = p["goldEarned"] / max_gold
- vis_norm = p["visionScore"] / max_vis
- win_bonus = 0.15 if p["win"] else 0.0
- if p["teamPosition"] == "UTILITY":
- op_score = 0.25 * kda_norm + 0.30 * kp + 0.25 * vis_norm + 0.10 * dmg_norm + 0.10 * gold_norm + win_bonus
- else:
- op_score = 0.25 * kda_norm + 0.20 * kp + 0.25 * dmg_norm + 0.20 * gold_norm + 0.10 * vis_norm + win_bonus
- scores.append((p["puuid"], op_score))
- scores.sort(key=lambda x: x[1], reverse=True)
- return {puuid: rank for rank, (puuid, _) in enumerate(scores, start=1)}
- def calc_player_score(p: dict, rank: int) -> float:
- rank_score = 11 - rank
- kda_capped = min(calc_kda(p), 10.0)
- return round(0.6 * rank_score + 0.4 * kda_capped, 2)
- def main():
- start_ts = date_to_epoch(START_DATE)
- print(f"Looking up PUUID for {GAME_NAME}#{TAG_LINE}...")
- puuid = get_puuid(GAME_NAME, TAG_LINE)
- print(f"Fetching all Ranked Solo/Duo matches since {START_DATE}...")
- match_ids = get_all_match_ids_since(puuid, start_ts, QUEUE_ID)
- total_scanned = len(match_ids)
- print(f"Found {total_scanned} matches to scan. Starting download...\n")
- rows = []
- skipped = {"remake": 0, "autofill_bot": 0, "incomplete": 0}
- # Total botlane scores and K/D/A
- total_my_bot_score = 0.0
- total_en_bot_score = 0.0
- my_bot_kda = {"k": 0, "d": 0, "a": 0}
- en_bot_kda = {"k": 0, "d": 0, "a": 0}
- verdict_stats = {
- "MY_BOT": {"games": 0, "wins": 0, "losses": 0},
- "ENEMY_BOT": {"games": 0, "wins": 0, "losses": 0},
- "EVEN": {"games": 0, "wins": 0, "losses": 0},
- }
- # Personal stats (overall)
- me_totals = {
- "wins": 0, "kills": 0, "deaths": 0, "assists": 0,
- "cs": 0, "gold": 0, "dmg": 0, "vision": 0,
- "duration_min": 0.0, "rank_sum": 0, "score_sum": 0.0,
- "kp_sum": 0.0, "mvp_count": 0, "top3_count": 0,
- }
- champ_stats = defaultdict(lambda: {"games": 0, "wins": 0, "k": 0, "d": 0, "a": 0, "score_sum": 0.0})
- role_counts = defaultdict(int)
- for idx, match_id in enumerate(match_ids, 1):
- data = get_match_details(match_id)
- info = data["info"]
- participants = info["participants"]
- me = next(p for p in participants if p["puuid"] == puuid)
- # 1. Skip remakes
- if info["gameDuration"] < 300 or me.get("gameEndedInEarlySurrender", False):
- skipped["remake"] += 1
- print(f"[{idx}/{total_scanned}] Skip {match_id} (remake)")
- continue
- # 2. Skip matches where you were autofilled ADC or Support
- if me["teamPosition"] in ("BOTTOM", "UTILITY"):
- skipped["autofill_bot"] += 1
- print(f"[{idx}/{total_scanned}] Skip {match_id} (autofill {me['teamPosition']})")
- continue
- my_team_id = me["teamId"]
- roles = {
- "my_adc": next((p for p in participants if p["teamId"] == my_team_id and p["teamPosition"] == "BOTTOM"), None),
- "my_sup": next((p for p in participants if p["teamId"] == my_team_id and p["teamPosition"] == "UTILITY"), None),
- "en_adc": next((p for p in participants if p["teamId"] != my_team_id and p["teamPosition"] == "BOTTOM"), None),
- "en_sup": next((p for p in participants if p["teamId"] != my_team_id and p["teamPosition"] == "UTILITY"), None),
- }
- if any(v is None for v in roles.values()):
- skipped["incomplete"] += 1
- print(f"[{idx}/{total_scanned}] Skip {match_id} (incomplete roles)")
- continue
- ranks = compute_opgg_like_ranks(participants)
- my_adc_score = calc_player_score(roles["my_adc"], ranks[roles["my_adc"]["puuid"]])
- my_sup_score = calc_player_score(roles["my_sup"], ranks[roles["my_sup"]["puuid"]])
- en_adc_score = calc_player_score(roles["en_adc"], ranks[roles["en_adc"]["puuid"]])
- en_sup_score = calc_player_score(roles["en_sup"], ranks[roles["en_sup"]["puuid"]])
- my_bot_score = round(my_adc_score + my_sup_score, 2)
- en_bot_score = round(en_adc_score + en_sup_score, 2)
- diff = round(my_bot_score - en_bot_score, 2)
- if diff >= DIFF_THRESHOLD:
- verdict = "MY_BOT"
- elif diff <= -DIFF_THRESHOLD:
- verdict = "ENEMY_BOT"
- else:
- verdict = "EVEN"
- # Accumulate total scores and K/D/A for both botlanes
- total_my_bot_score += my_bot_score
- total_en_bot_score += en_bot_score
- my_bot_kda["k"] += roles["my_adc"]["kills"] + roles["my_sup"]["kills"]
- my_bot_kda["d"] += roles["my_adc"]["deaths"] + roles["my_sup"]["deaths"]
- my_bot_kda["a"] += roles["my_adc"]["assists"] + roles["my_sup"]["assists"]
- en_bot_kda["k"] += roles["en_adc"]["kills"] + roles["en_sup"]["kills"]
- en_bot_kda["d"] += roles["en_adc"]["deaths"] + roles["en_sup"]["deaths"]
- en_bot_kda["a"] += roles["en_adc"]["assists"] + roles["en_sup"]["assists"]
- verdict_stats[verdict]["games"] += 1
- if me["win"]:
- verdict_stats[verdict]["wins"] += 1
- else:
- verdict_stats[verdict]["losses"] += 1
- # Accumulate personal stats
- dur_min = info["gameDuration"] / 60.0
- my_rank = ranks[puuid]
- my_score = calc_player_score(me, my_rank)
- my_team_kills = sum(p["kills"] for p in participants if p["teamId"] == my_team_id)
- my_kp = (me["kills"] + me["assists"]) / max(1, my_team_kills)
- me_totals["wins"] += int(me["win"])
- me_totals["kills"] += me["kills"]
- me_totals["deaths"] += me["deaths"]
- me_totals["assists"] += me["assists"]
- me_totals["cs"] += me["totalMinionsKilled"] + me["neutralMinionsKilled"]
- me_totals["gold"] += me["goldEarned"]
- me_totals["dmg"] += me["totalDamageDealtToChampions"]
- me_totals["vision"] += me["visionScore"]
- me_totals["duration_min"] += dur_min
- me_totals["rank_sum"] += my_rank
- me_totals["score_sum"] += my_score
- me_totals["kp_sum"] += my_kp
- if my_rank == 1:
- me_totals["mvp_count"] += 1
- if my_rank <= 3:
- me_totals["top3_count"] += 1
- role_counts[me["teamPosition"]] += 1
- cs = champ_stats[me["championName"]]
- cs["games"] += 1
- cs["wins"] += int(me["win"])
- cs["k"] += me["kills"]
- cs["d"] += me["deaths"]
- cs["a"] += me["assists"]
- cs["score_sum"] += my_score
- row = {
- "match_id": match_id,
- "win": me["win"],
- "my_role": me["teamPosition"],
- "my_champ": me["championName"],
- "my_rank": my_rank,
- "my_score": my_score,
- "my_bot_score": my_bot_score,
- "en_bot_score": en_bot_score,
- "diff": diff,
- "verdict": verdict,
- "my_adc": f"{roles['my_adc']['championName']} (#{ranks[roles['my_adc']['puuid']]}, {roles['my_adc']['kills']}/{roles['my_adc']['deaths']}/{roles['my_adc']['assists']})",
- "my_sup": f"{roles['my_sup']['championName']} (#{ranks[roles['my_sup']['puuid']]}, {roles['my_sup']['kills']}/{roles['my_sup']['deaths']}/{roles['my_sup']['assists']})",
- "en_adc": f"{roles['en_adc']['championName']} (#{ranks[roles['en_adc']['puuid']]}, {roles['en_adc']['kills']}/{roles['en_adc']['deaths']}/{roles['en_adc']['assists']})",
- "en_sup": f"{roles['en_sup']['championName']} (#{ranks[roles['en_sup']['puuid']]}, {roles['en_sup']['kills']}/{roles['en_sup']['deaths']}/{roles['en_sup']['assists']})",
- }
- rows.append(row)
- print(f"[{idx}/{total_scanned}] {verdict:<9} | Diff: {diff:+6.2f} | {'WIN ' if me['win'] else 'LOSS'} | Me: {me['championName']} ({me['teamPosition']}, #{my_rank})")
- if not rows:
- print("No valid matches found after filtering.")
- return
- output_file = "botlane_stats.csv"
- with open(output_file, "w", newline="", encoding="utf-8") as f:
- writer = csv.DictWriter(f, fieldnames=rows[0].keys())
- writer.writeheader()
- writer.writerows(rows)
- total = len(rows)
- total_diff = total_my_bot_score - total_en_bot_score
- my_bot_ratio = (my_bot_kda["k"] + my_bot_kda["a"]) / max(1, my_bot_kda["d"])
- en_bot_ratio = (en_bot_kda["k"] + en_bot_kda["a"]) / max(1, en_bot_kda["d"])
- overall_kda = (me_totals["kills"] + me_totals["assists"]) / max(1, me_totals["deaths"])
- my_b = verdict_stats["MY_BOT"]
- en_b = verdict_stats["ENEMY_BOT"]
- ev_b = verdict_stats["EVEN"]
- print("\n" + "=" * 72)
- print(f"FULL REPORT — {GAME_NAME}#{TAG_LINE} (since {START_DATE})")
- print("=" * 72)
- print("\n1. MATCHES SCANNED AND FILTERED")
- print(f" • Scanned a total of {total_scanned} Ranked Solo/Duo matches since {START_DATE}.")
- print(f" • Out of these, {total} valid matches remained for analysis.")
- print(f" • Excluded {skipped['remake']} remakes, {skipped['autofill_bot']} matches where you were autofilled ADC/Support, and {skipped['incomplete']} matches with incomplete roles.")
- print("\n2. TOTAL BOTLANE COMPARISON (YOURS VS. ENEMY)")
- print(f" • YOUR botlane (ADC + Support) accumulated a total score of {total_my_bot_score:.2f} points (avg {total_my_bot_score/total:.2f} pts/game).")
- print(f" • ENEMY botlane (ADC + Support) accumulated a total score of {total_en_bot_score:.2f} points (avg {total_en_bot_score/total:.2f} pts/game).")
- print(f" • Cumulative total difference is {total_diff:+.2f} points in favor of {'YOUR botlane' if total_diff >= 0 else 'the ENEMY botlane'} (avg: {total_diff/total:+.2f}/game).")
- print(f" • YOUR botlane TOTAL K / D / A: {my_bot_kda['k']} kills / {my_bot_kda['d']} deaths / {my_bot_kda['a']} assists (combined KDA: {my_bot_ratio:.2f}).")
- print(f" • ENEMY botlane TOTAL K / D / A: {en_bot_kda['k']} kills / {en_bot_kda['d']} deaths / {en_bot_kda['a']} assists (combined KDA: {en_bot_ratio:.2f}).")
- print("\n3. WHO HAD THE BETTER BOTLANE AND WHO WON THE MATCHES")
- print(f" • YOUR botlane was better in {my_b['games']} out of {total} matches ({my_b['games']/total*100:.1f}%).")
- if my_b["games"]:
- print(f" -> In these {my_b['games']} matches, YOUR team won {my_b['wins']} ({my_b['wins']/my_b['games']*100:.1f}%), and the ENEMY team won {my_b['losses']} ({my_b['losses']/my_b['games']*100:.1f}%).")
- print(f" • The ENEMY botlane was better in {en_b['games']} out of {total} matches ({en_b['games']/total*100:.1f}%).")
- if en_b["games"]:
- print(f" -> In these {en_b['games']} matches where the enemy botlane was better, YOUR team managed to win {en_b['wins']} matches ({en_b['wins']/en_b['games']*100:.1f}%), and the ENEMY team won {en_b['losses']} matches ({en_b['losses']/en_b['games']*100:.1f}%).")
- print(f" • Both botlanes were even (difference under {DIFF_THRESHOLD} pts) in {ev_b['games']} matches ({ev_b['games']/total*100:.1f}%).")
- if ev_b["games"]:
- print(f" -> In these even matches, YOUR team won {ev_b['wins']} and lost {ev_b['losses']} (WR: {ev_b['wins']/ev_b['games']*100:.1f}%).")
- print(f"\n4. YOUR OVERALL PERFORMANCE ({GAME_NAME}#{TAG_LINE})")
- print(f" • You won {me_totals['wins']} matches and lost {total - me_totals['wins']} matches, for a {me_totals['wins']/total*100:.1f}% winrate.")
- print(f" • Personal TOTAL K / D / A: {me_totals['kills']} kills / {me_totals['deaths']} deaths / {me_totals['assists']} assists (overall KDA: {overall_kda:.2f}).")
- print(f" • On average per game, you had {me_totals['kills']/total:.1f} kills, {me_totals['deaths']/total:.1f} deaths, and {me_totals['assists']/total:.1f} assists.")
- print(f" • Your average match rank (from #1 to #10) was #{me_totals['rank_sum']/total:.2f}, with an average score of {me_totals['score_sum']/total:.2f}/10.")
- print(f" • You were MVP (#1 in the match) in {me_totals['mvp_count']} matches ({me_totals['mvp_count']/total*100:.1f}%) and Top 3 in {me_totals['top3_count']} matches ({me_totals['top3_count']/total*100:.1f}%).")
- print(f" • You participated in {me_totals['kp_sum']/total*100:.1f}% of your team's kills (Kill Participation).")
- print(f" • You farmed an average of {me_totals['cs']/me_totals['duration_min']:.2f} CS/min ({me_totals['cs']/total:.1f} CS/game), generated {me_totals['gold']/me_totals['duration_min']:.0f} gold/min, and dealt {me_totals['dmg']/me_totals['duration_min']:.0f} damage/min to champions.")
- print(f" • Your average vision score was {me_totals['vision']/total:.1f}, and the average match duration was {me_totals['duration_min']/total:.1f} minutes.")
- print(f" • Roles played in the analyzed matches: {dict(role_counts)}.")
- print("\n Top 5 champions you played during this period:")
- top_champs = sorted(champ_stats.items(), key=lambda x: x[1]["games"], reverse=True)[:5]
- for champ, c in top_champs:
- c_wr = c["wins"] / c["games"] * 100
- c_kda = (c["k"] + c["a"]) / max(1, c["d"])
- c_score = c["score_sum"] / c["games"]
- print(f" - {champ}: {c['games']} games ({c['wins']}W - {c['games']-c['wins']}L, WR {c_wr:.1f}%) | Total K/D/A: {c['k']}/{c['d']}/{c['a']} (KDA {c_kda:.2f}) | Avg score: {c_score:.2f}")
- print("\n" + "=" * 72)
- print(f"All match-by-match data has been saved to {output_file}.")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment