Guest User

Untitled

a guest
Nov 20th, 2026
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.44 KB | None | 0 0
  1. import csv
  2. import time
  3. from collections import defaultdict
  4. from datetime import datetime, timezone
  5. import requests
  6.  
  7. # --- CONFIGURATION ---
  8. API_KEY = "RGAPI-662ba993-f7f2-41f8-8d03-595f5c83b879"
  9. GAME_NAME = "cordeeana" # without #
  10. TAG_LINE = "EUNE" # what comes after #
  11. REGION = "europe" # "europe" for EUNE/EUW
  12. START_DATE = "2026-11-14" # <-- PUT THE DATE YOU REACHED GOLD 1 HERE (YYYY-MM-DD)
  13. QUEUE_ID = 420 # 420 = Ranked Solo/Duo
  14. DIFF_THRESHOLD = 1.5 # threshold for "Even"
  15. # ---------------------
  16.  
  17. HEADERS = {"X-Riot-Token": API_KEY}
  18. BASE_URL = f"https://{REGION}.api.riotgames.com"
  19.  
  20.  
  21. def date_to_epoch(date_str: str) -> int:
  22. dt = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
  23. return int(dt.timestamp())
  24.  
  25.  
  26. def request_with_retry(url: str, params: dict | None = None) -> dict | list:
  27. while True:
  28. r = requests.get(url, headers=HEADERS, params=params)
  29. if r.status_code == 429:
  30. wait = int(r.headers.get("Retry-After", 5)) + 1
  31. print(f" [Rate limit] Waiting {wait}s...")
  32. time.sleep(wait)
  33. continue
  34. r.raise_for_status()
  35. return r.json()
  36.  
  37.  
  38. def get_puuid(game_name: str, tag_line: str) -> str:
  39. url = f"{BASE_URL}/riot/account/v1/accounts/by-riot-id/{game_name}/{tag_line}"
  40. return request_with_retry(url)["puuid"]
  41.  
  42.  
  43. def get_all_match_ids_since(puuid: str, start_time: int, queue: int | None) -> list[str]:
  44. """Fetches all matches from start_time up to the present."""
  45. url = f"{BASE_URL}/lol/match/v5/matches/by-puuid/{puuid}/ids"
  46. all_ids = []
  47. start = 0
  48.  
  49. while True:
  50. params = {"start": start, "count": 100, "startTime": start_time}
  51. if queue:
  52. params["queue"] = queue
  53.  
  54. batch = request_with_retry(url, params=params)
  55. if not batch:
  56. break
  57.  
  58. all_ids.extend(batch)
  59. start += len(batch)
  60. if len(batch) < 100:
  61. break
  62. time.sleep(0.5)
  63.  
  64. return all_ids
  65.  
  66.  
  67. def get_match_details(match_id: str) -> dict:
  68. url = f"{BASE_URL}/lol/match/v5/matches/{match_id}"
  69. data = request_with_retry(url)
  70. time.sleep(1.3)
  71. return data
  72.  
  73.  
  74. def calc_kda(p: dict) -> float:
  75. return (p["kills"] + p["assists"]) / max(1, p["deaths"])
  76.  
  77.  
  78. def compute_opgg_like_ranks(participants: list[dict]) -> dict[str, int]:
  79. """Calculates a 1..10 rank (OP.GG style) for the 10 players in the match."""
  80. team_kills = {100: 0, 200: 0}
  81. for p in participants:
  82. team_kills[p["teamId"]] += p["kills"]
  83.  
  84. max_dmg = max((p["totalDamageDealtToChampions"] for p in participants), default=1) or 1
  85. max_gold = max((p["goldEarned"] for p in participants), default=1) or 1
  86. max_vis = max((p["visionScore"] for p in participants), default=1) or 1
  87.  
  88. scores = []
  89. for p in participants:
  90. kda_norm = min(calc_kda(p), 10.0) / 10.0
  91. kp = (p["kills"] + p["assists"]) / max(1, team_kills[p["teamId"]])
  92. dmg_norm = p["totalDamageDealtToChampions"] / max_dmg
  93. gold_norm = p["goldEarned"] / max_gold
  94. vis_norm = p["visionScore"] / max_vis
  95. win_bonus = 0.15 if p["win"] else 0.0
  96.  
  97. if p["teamPosition"] == "UTILITY":
  98. op_score = 0.25 * kda_norm + 0.30 * kp + 0.25 * vis_norm + 0.10 * dmg_norm + 0.10 * gold_norm + win_bonus
  99. else:
  100. op_score = 0.25 * kda_norm + 0.20 * kp + 0.25 * dmg_norm + 0.20 * gold_norm + 0.10 * vis_norm + win_bonus
  101.  
  102. scores.append((p["puuid"], op_score))
  103.  
  104. scores.sort(key=lambda x: x[1], reverse=True)
  105. return {puuid: rank for rank, (puuid, _) in enumerate(scores, start=1)}
  106.  
  107.  
  108. def calc_player_score(p: dict, rank: int) -> float:
  109. rank_score = 11 - rank
  110. kda_capped = min(calc_kda(p), 10.0)
  111. return round(0.6 * rank_score + 0.4 * kda_capped, 2)
  112.  
  113.  
  114. def main():
  115. start_ts = date_to_epoch(START_DATE)
  116. print(f"Looking up PUUID for {GAME_NAME}#{TAG_LINE}...")
  117. puuid = get_puuid(GAME_NAME, TAG_LINE)
  118.  
  119. print(f"Fetching all Ranked Solo/Duo matches since {START_DATE}...")
  120. match_ids = get_all_match_ids_since(puuid, start_ts, QUEUE_ID)
  121. total_scanned = len(match_ids)
  122. print(f"Found {total_scanned} matches to scan. Starting download...\n")
  123.  
  124. rows = []
  125. skipped = {"remake": 0, "autofill_bot": 0, "incomplete": 0}
  126.  
  127. # Total botlane scores and K/D/A
  128. total_my_bot_score = 0.0
  129. total_en_bot_score = 0.0
  130. my_bot_kda = {"k": 0, "d": 0, "a": 0}
  131. en_bot_kda = {"k": 0, "d": 0, "a": 0}
  132.  
  133. verdict_stats = {
  134. "MY_BOT": {"games": 0, "wins": 0, "losses": 0},
  135. "ENEMY_BOT": {"games": 0, "wins": 0, "losses": 0},
  136. "EVEN": {"games": 0, "wins": 0, "losses": 0},
  137. }
  138.  
  139. # Personal stats (overall)
  140. me_totals = {
  141. "wins": 0, "kills": 0, "deaths": 0, "assists": 0,
  142. "cs": 0, "gold": 0, "dmg": 0, "vision": 0,
  143. "duration_min": 0.0, "rank_sum": 0, "score_sum": 0.0,
  144. "kp_sum": 0.0, "mvp_count": 0, "top3_count": 0,
  145. }
  146. champ_stats = defaultdict(lambda: {"games": 0, "wins": 0, "k": 0, "d": 0, "a": 0, "score_sum": 0.0})
  147. role_counts = defaultdict(int)
  148.  
  149. for idx, match_id in enumerate(match_ids, 1):
  150. data = get_match_details(match_id)
  151. info = data["info"]
  152. participants = info["participants"]
  153. me = next(p for p in participants if p["puuid"] == puuid)
  154.  
  155. # 1. Skip remakes
  156. if info["gameDuration"] < 300 or me.get("gameEndedInEarlySurrender", False):
  157. skipped["remake"] += 1
  158. print(f"[{idx}/{total_scanned}] Skip {match_id} (remake)")
  159. continue
  160.  
  161. # 2. Skip matches where you were autofilled ADC or Support
  162. if me["teamPosition"] in ("BOTTOM", "UTILITY"):
  163. skipped["autofill_bot"] += 1
  164. print(f"[{idx}/{total_scanned}] Skip {match_id} (autofill {me['teamPosition']})")
  165. continue
  166.  
  167. my_team_id = me["teamId"]
  168. roles = {
  169. "my_adc": next((p for p in participants if p["teamId"] == my_team_id and p["teamPosition"] == "BOTTOM"), None),
  170. "my_sup": next((p for p in participants if p["teamId"] == my_team_id and p["teamPosition"] == "UTILITY"), None),
  171. "en_adc": next((p for p in participants if p["teamId"] != my_team_id and p["teamPosition"] == "BOTTOM"), None),
  172. "en_sup": next((p for p in participants if p["teamId"] != my_team_id and p["teamPosition"] == "UTILITY"), None),
  173. }
  174.  
  175. if any(v is None for v in roles.values()):
  176. skipped["incomplete"] += 1
  177. print(f"[{idx}/{total_scanned}] Skip {match_id} (incomplete roles)")
  178. continue
  179.  
  180. ranks = compute_opgg_like_ranks(participants)
  181.  
  182. my_adc_score = calc_player_score(roles["my_adc"], ranks[roles["my_adc"]["puuid"]])
  183. my_sup_score = calc_player_score(roles["my_sup"], ranks[roles["my_sup"]["puuid"]])
  184. en_adc_score = calc_player_score(roles["en_adc"], ranks[roles["en_adc"]["puuid"]])
  185. en_sup_score = calc_player_score(roles["en_sup"], ranks[roles["en_sup"]["puuid"]])
  186.  
  187. my_bot_score = round(my_adc_score + my_sup_score, 2)
  188. en_bot_score = round(en_adc_score + en_sup_score, 2)
  189. diff = round(my_bot_score - en_bot_score, 2)
  190.  
  191. if diff >= DIFF_THRESHOLD:
  192. verdict = "MY_BOT"
  193. elif diff <= -DIFF_THRESHOLD:
  194. verdict = "ENEMY_BOT"
  195. else:
  196. verdict = "EVEN"
  197.  
  198. # Accumulate total scores and K/D/A for both botlanes
  199. total_my_bot_score += my_bot_score
  200. total_en_bot_score += en_bot_score
  201.  
  202. my_bot_kda["k"] += roles["my_adc"]["kills"] + roles["my_sup"]["kills"]
  203. my_bot_kda["d"] += roles["my_adc"]["deaths"] + roles["my_sup"]["deaths"]
  204. my_bot_kda["a"] += roles["my_adc"]["assists"] + roles["my_sup"]["assists"]
  205.  
  206. en_bot_kda["k"] += roles["en_adc"]["kills"] + roles["en_sup"]["kills"]
  207. en_bot_kda["d"] += roles["en_adc"]["deaths"] + roles["en_sup"]["deaths"]
  208. en_bot_kda["a"] += roles["en_adc"]["assists"] + roles["en_sup"]["assists"]
  209.  
  210. verdict_stats[verdict]["games"] += 1
  211. if me["win"]:
  212. verdict_stats[verdict]["wins"] += 1
  213. else:
  214. verdict_stats[verdict]["losses"] += 1
  215.  
  216. # Accumulate personal stats
  217. dur_min = info["gameDuration"] / 60.0
  218. my_rank = ranks[puuid]
  219. my_score = calc_player_score(me, my_rank)
  220. my_team_kills = sum(p["kills"] for p in participants if p["teamId"] == my_team_id)
  221. my_kp = (me["kills"] + me["assists"]) / max(1, my_team_kills)
  222.  
  223. me_totals["wins"] += int(me["win"])
  224. me_totals["kills"] += me["kills"]
  225. me_totals["deaths"] += me["deaths"]
  226. me_totals["assists"] += me["assists"]
  227. me_totals["cs"] += me["totalMinionsKilled"] + me["neutralMinionsKilled"]
  228. me_totals["gold"] += me["goldEarned"]
  229. me_totals["dmg"] += me["totalDamageDealtToChampions"]
  230. me_totals["vision"] += me["visionScore"]
  231. me_totals["duration_min"] += dur_min
  232. me_totals["rank_sum"] += my_rank
  233. me_totals["score_sum"] += my_score
  234. me_totals["kp_sum"] += my_kp
  235. if my_rank == 1:
  236. me_totals["mvp_count"] += 1
  237. if my_rank <= 3:
  238. me_totals["top3_count"] += 1
  239.  
  240. role_counts[me["teamPosition"]] += 1
  241. cs = champ_stats[me["championName"]]
  242. cs["games"] += 1
  243. cs["wins"] += int(me["win"])
  244. cs["k"] += me["kills"]
  245. cs["d"] += me["deaths"]
  246. cs["a"] += me["assists"]
  247. cs["score_sum"] += my_score
  248.  
  249. row = {
  250. "match_id": match_id,
  251. "win": me["win"],
  252. "my_role": me["teamPosition"],
  253. "my_champ": me["championName"],
  254. "my_rank": my_rank,
  255. "my_score": my_score,
  256. "my_bot_score": my_bot_score,
  257. "en_bot_score": en_bot_score,
  258. "diff": diff,
  259. "verdict": verdict,
  260. "my_adc": f"{roles['my_adc']['championName']} (#{ranks[roles['my_adc']['puuid']]}, {roles['my_adc']['kills']}/{roles['my_adc']['deaths']}/{roles['my_adc']['assists']})",
  261. "my_sup": f"{roles['my_sup']['championName']} (#{ranks[roles['my_sup']['puuid']]}, {roles['my_sup']['kills']}/{roles['my_sup']['deaths']}/{roles['my_sup']['assists']})",
  262. "en_adc": f"{roles['en_adc']['championName']} (#{ranks[roles['en_adc']['puuid']]}, {roles['en_adc']['kills']}/{roles['en_adc']['deaths']}/{roles['en_adc']['assists']})",
  263. "en_sup": f"{roles['en_sup']['championName']} (#{ranks[roles['en_sup']['puuid']]}, {roles['en_sup']['kills']}/{roles['en_sup']['deaths']}/{roles['en_sup']['assists']})",
  264. }
  265. rows.append(row)
  266. print(f"[{idx}/{total_scanned}] {verdict:<9} | Diff: {diff:+6.2f} | {'WIN ' if me['win'] else 'LOSS'} | Me: {me['championName']} ({me['teamPosition']}, #{my_rank})")
  267.  
  268. if not rows:
  269. print("No valid matches found after filtering.")
  270. return
  271.  
  272. output_file = "botlane_stats.csv"
  273. with open(output_file, "w", newline="", encoding="utf-8") as f:
  274. writer = csv.DictWriter(f, fieldnames=rows[0].keys())
  275. writer.writeheader()
  276. writer.writerows(rows)
  277.  
  278. total = len(rows)
  279. total_diff = total_my_bot_score - total_en_bot_score
  280. my_bot_ratio = (my_bot_kda["k"] + my_bot_kda["a"]) / max(1, my_bot_kda["d"])
  281. en_bot_ratio = (en_bot_kda["k"] + en_bot_kda["a"]) / max(1, en_bot_kda["d"])
  282. overall_kda = (me_totals["kills"] + me_totals["assists"]) / max(1, me_totals["deaths"])
  283.  
  284. my_b = verdict_stats["MY_BOT"]
  285. en_b = verdict_stats["ENEMY_BOT"]
  286. ev_b = verdict_stats["EVEN"]
  287.  
  288. print("\n" + "=" * 72)
  289. print(f"FULL REPORT — {GAME_NAME}#{TAG_LINE} (since {START_DATE})")
  290. print("=" * 72)
  291.  
  292. print("\n1. MATCHES SCANNED AND FILTERED")
  293. print(f" • Scanned a total of {total_scanned} Ranked Solo/Duo matches since {START_DATE}.")
  294. print(f" • Out of these, {total} valid matches remained for analysis.")
  295. print(f" • Excluded {skipped['remake']} remakes, {skipped['autofill_bot']} matches where you were autofilled ADC/Support, and {skipped['incomplete']} matches with incomplete roles.")
  296.  
  297. print("\n2. TOTAL BOTLANE COMPARISON (YOURS VS. ENEMY)")
  298. 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).")
  299. 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).")
  300. 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).")
  301. 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}).")
  302. 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}).")
  303.  
  304. print("\n3. WHO HAD THE BETTER BOTLANE AND WHO WON THE MATCHES")
  305. print(f" • YOUR botlane was better in {my_b['games']} out of {total} matches ({my_b['games']/total*100:.1f}%).")
  306. if my_b["games"]:
  307. 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}%).")
  308.  
  309. print(f" • The ENEMY botlane was better in {en_b['games']} out of {total} matches ({en_b['games']/total*100:.1f}%).")
  310. if en_b["games"]:
  311. 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}%).")
  312.  
  313. print(f" • Both botlanes were even (difference under {DIFF_THRESHOLD} pts) in {ev_b['games']} matches ({ev_b['games']/total*100:.1f}%).")
  314. if ev_b["games"]:
  315. 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}%).")
  316.  
  317. print(f"\n4. YOUR OVERALL PERFORMANCE ({GAME_NAME}#{TAG_LINE})")
  318. print(f" • You won {me_totals['wins']} matches and lost {total - me_totals['wins']} matches, for a {me_totals['wins']/total*100:.1f}% winrate.")
  319. print(f" • Personal TOTAL K / D / A: {me_totals['kills']} kills / {me_totals['deaths']} deaths / {me_totals['assists']} assists (overall KDA: {overall_kda:.2f}).")
  320. 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.")
  321. 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.")
  322. 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}%).")
  323. print(f" • You participated in {me_totals['kp_sum']/total*100:.1f}% of your team's kills (Kill Participation).")
  324. 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.")
  325. 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.")
  326. print(f" • Roles played in the analyzed matches: {dict(role_counts)}.")
  327.  
  328. print("\n Top 5 champions you played during this period:")
  329. top_champs = sorted(champ_stats.items(), key=lambda x: x[1]["games"], reverse=True)[:5]
  330. for champ, c in top_champs:
  331. c_wr = c["wins"] / c["games"] * 100
  332. c_kda = (c["k"] + c["a"]) / max(1, c["d"])
  333. c_score = c["score_sum"] / c["games"]
  334. 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}")
  335.  
  336. print("\n" + "=" * 72)
  337. print(f"All match-by-match data has been saved to {output_file}.")
  338.  
  339.  
  340. if __name__ == "__main__":
  341. main()
Advertisement
Add Comment
Please, Sign In to add comment