Irlance_Dox

LOL GameBox-Beta

Oct 6th, 2017
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.20 KB | None | 0 0
  1. import requests
  2. import json
  3. import time
  4. import re
  5.  
  6. try:
  7.     import sys
  8.     from IPython.core.ultratb import AutoFormattedTB
  9.  
  10.     sys.excepthook = AutoFormattedTB()
  11. except ImportError:
  12.     print('IPython is not installed. Colored Traceback will not be populated.')
  13. try:
  14.     import pyperclip
  15. except ImportError:
  16.     print('"pyperclip" is not installed. "Box1.copy2clipboard()" does not work in the case.')
  17.  
  18. fo = open("gameresult.txt", "w")
  19. fo.write("\n")
  20.  
  21. googleAPI = 'AIzaSyBOTinxILMHDJ2IT4Uu5_6zaLWqB2_rLLM'
  22. TOPRULE = ' ┌─────────────────────────────────────┐'
  23. MIDRULE = ' ├─────────────────────────────────────┤'
  24. BOTRULE = ' └─────────────────────────────────────┘'
  25. L = '│'
  26. D = '.'
  27. H = '─'
  28.  
  29.  
  30. def shorten_url(url, api_key=googleAPI):
  31.     post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(api_key)
  32.     payload = {'longUrl': url}
  33.     headers = {'content-type': 'application/json'}
  34.     r = requests.post(post_url, data=json.dumps(payload), headers=headers)
  35.     return r.json()
  36.  
  37.  
  38. def get_url_from_gameid(gameid, short_url=None):
  39.     ret = {}
  40.     ret['stats-url'] = 'https://acs.leagueoflegends.com/v1/stats/game/' + gameid
  41.     ret['long-url'] = 'http://matchhistory.na.leagueoflegends.com/en/#match-details/' + gameid + '&tab=stats'
  42.     if short_url is None:
  43.         ret['short-url'] = shorten_url(ret['long-url'])['id']
  44.     else:
  45.         ret['short-url'] = short_url
  46.     return ret
  47.  
  48.  
  49. class SquareDigitNumber(object):
  50.     ON = "█"
  51.     OFF = "  "
  52.     binary = {'0': (ON, ON, ON, ON, OFF, ON, ON, OFF, ON, ON, OFF, ON, ON, ON, ON),
  53.               '1': (OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON),
  54.               '2': (ON, ON, ON, OFF, OFF, ON, ON, ON, ON, ON, OFF, OFF, ON, ON, ON),
  55.               '3': (ON, ON, ON, OFF, OFF, ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
  56.               '4': (ON, OFF, ON, ON, OFF, ON, ON, ON, ON, OFF, OFF, ON, OFF, OFF, ON),
  57.               '5': (ON, ON, ON, ON, OFF, OFF, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
  58.               '6': (ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON, OFF, ON, ON, ON, ON),
  59.               '7': (ON, ON, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON),
  60.               '8': (ON, ON, ON, ON, OFF, ON, ON, ON, ON, ON, OFF, ON, ON, ON, ON),
  61.               '9': (ON, ON, ON, ON, OFF, ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
  62.               ' ': (OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF)}
  63.  
  64.     def __init__(self, d, filled='0'):
  65.         self.d = d
  66.         self.filled = filled
  67.  
  68.     @classmethod
  69.     def _display(cls, d, lineno=11):
  70.         startno = (lineno - 5) // 2
  71.         s = ''
  72.         tup = cls.binary[d]
  73.         for _ in range(startno):
  74.             yield cls.OFF * 3
  75.         for i in range(15):
  76.             s += tup[i]
  77.             if i == 0:
  78.                 continue
  79.             if i % 3 == 2:
  80.                 # s += '\n'
  81.                 yield s
  82.                 s = ''
  83.         for _ in range(startno):
  84.             yield cls.OFF * 3
  85.  
  86.     def display(self, lineno=11):
  87.         for seq in zip(*(self._display(d, lineno) for d in '{:{filled}2}'.format(self.d, filled=self.filled))):
  88.             yield ' '.join(seq)
  89.  
  90.  
  91. class Player():
  92.     def __init__(self, char, stats):
  93.         self.char = char
  94.         self.kill = stats['kills']
  95.         self.death = stats['deaths']
  96.         self.assist = stats['assists']
  97.         self.damage = stats['totalDamageDealtToChampions']
  98.         self.tank = stats['totalDamageTaken']
  99.         self.gold = stats['goldEarned']
  100.         self.cs = stats['totalMinionsKilled'] + stats['neutralMinionsKilled']
  101.         self.firstBlood = stats['firstBloodKill']
  102.         self.KP = []
  103.  
  104.  
  105. class ANSIColor(object):
  106.     ENDC = '\033[m'
  107.     START = '\033'
  108.  
  109.     def __init__(self, color_code):
  110.         self.code = color_code
  111.  
  112.     def __call__(self, text):
  113.         return self.START + self.code + text + self.ENDC
  114.  
  115.  
  116. BLUE = ANSIColor('[1;34m')
  117. RED = ANSIColor('[1;31m')
  118. CYAN = ANSIColor('[1;36m')
  119. PURPLE = ANSIColor('[;35m')
  120. GREEN = ANSIColor('[1;32m')
  121. YELLOW = ANSIColor('[1;33m')
  122. BRAZIL = ANSIColor('[1;33;42m')
  123. BLUE_TEAM = ANSIColor('[46m')
  124. PURPLE_TEAM = ANSIColor('[45m')
  125. BLUE_FRAME = ANSIColor('[0;34;44m')
  126. RED_FRAME = ANSIColor('[0;31;41m')
  127. BLUExYELLOW = ANSIColor('[1;33;44m')
  128. REDxYELLOW = ANSIColor('[1;33;41m')
  129.  
  130.  
  131. class Box1(object):
  132.     def __init__(self, team1, team2, gameid, short_url=None):
  133.         self.urls = get_url_from_gameid(gameid, short_url=short_url)
  134.         self.team1 = team1
  135.         self.team2 = team2
  136.         res = requests.get(self.urls['stats-url'])
  137.         self._database = json.loads(res.text)
  138.         self._PlayerS = [None] * 10
  139.         GameVer = self._database['gameVersion']
  140.  
  141.         reschamp = requests.get(
  142.             'http://ddragon.leagueoflegends.com/cdn/%s.1/data/en_US/champion.json' % '.'.join(GameVer.split('.')[:2]))
  143.         champions = json.loads(reschamp.text)['data']
  144.         self._champbase = {int(champions[key]['key']): key for key in champions}
  145.  
  146.     @property
  147.     def ANSIlines(self):
  148.         players = [p['player']['summonerName'] for p in self._database['participantIdentities']]
  149.         BlueBans = [None] * 5
  150.         for i in range(5):
  151.             BlueBans[i] = self._champbase[self._database['teams'][0]['bans'][i]['championId']]
  152.         RedBans = [None] * 5
  153.         for i in range(5):
  154.             RedBans[i] = self._champbase[self._database['teams'][1]['bans'][i]['championId']]
  155.  
  156.         Parc = self._database['participants']
  157.         for z in Parc:
  158.             j = int(z['participantId']) - 1
  159.             player = Player(self._champbase[z['championId']], z['stats'])
  160.             self._PlayerS[j] = player
  161.  
  162.         lines = []
  163.         ########################################### PAGE 1↓ ###################################
  164.         lines.append(TOPRULE)
  165.         for blocks in zip(self._winner_label(self._database['teams'][0]['win']),
  166.                           self._team_label(self.team1, 0),
  167.                           self._team_label(self.team2, 1),
  168.                           self._winner_label(self._database['teams'][1]['win'])):
  169.             lines.append(' ' + L + ''.join(blocks) + L)
  170.         blue_kills = SquareDigitNumber(
  171.             sum(self._database['participants'][i]['stats']['kills'] for i in range(5))).display(11)
  172.         purple_kills = SquareDigitNumber(
  173.             sum(self._database['participants'][i]['stats']['kills'] for i in range(5, 10))).display(11)
  174.         lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 19 + ' ' + PURPLE(L) + ' ' + ' ' * 19 + next(
  175.             purple_kills) + ' ' * 3 + L)
  176.         for i in range(5):
  177.             lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 4 + CYAN('{:>15}'.format(players[i])) + ' ' + \
  178.                          (PURPLE(L) if i != 2 else 'vs') + \
  179.                          ' ' + RED('{:<15}'.format(players[i + 5])) + ' ' * 3 + next(purple_kills) + ' ' * 4 + L)
  180.             lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 19 + ' ' + PURPLE(L) + ' ' + ' ' * 18 + next(
  181.                 purple_kills) + ' ' * 4 + L)
  182.         lines.append(' ' + L + ' ' * 74 + L)
  183.         for blocks in zip(self._game_time_label(), self._match_history_label(), self._game_duration_label()):
  184.             lines.append(' ' + '{F} {line} {F}'.format(F=L, line=''.join(blocks)))
  185.         lines.append(BOTRULE)
  186.         lines.append('')
  187.         ########################### ↑PAGE 1   PAGE 2↓ ###################################
  188.         lines.append('  ' + BLUE_FRAME(D * 38) + RED_FRAME(D * 38) + ' ')
  189.         lines.append('  ' + BLUE_FRAME(D) + '{:<44}'.format(BLUE_TEAM(self.team1)) + BLUE_FRAME(D) + \
  190.                      RED_FRAME(D) + '{:<44}'.format(PURPLE_TEAM(self.team2)) + RED_FRAME(D) + ' ')
  191.         lines.append(
  192.             '  ' + BLUExYELLOW(' Champion' + ' ' * 7 + 'K  D  A' + ' ' * 4 + 'CS' + ' ' * 3 + 'Gold' + ' ' * 2) + \
  193.             REDxYELLOW(' Champion' + ' ' * 7 + 'K  D  A' + ' ' * 4 + 'CS' + ' ' * 3 + 'Gold' + ' ' * 2))
  194.         lines.append('  ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
  195.         for i in range(5):
  196.             lines.append('  ' + BLUE_FRAME(D) + CYAN('{:<36}'.format(players[i])) + BLUE_FRAME(D) + \
  197.                          RED_FRAME(D) + RED('{:<36}'.format(players[i + 5])) + RED_FRAME(D) + ' ')
  198.             lines.append('  ' + BLUE_FRAME(D) +
  199.                          ('{:<14}{:2} {:2} {:2}  {:4} {:7,}'.format(''.join(self._PlayerS[i].char),
  200.                                                                     self._PlayerS[i].kill,
  201.                                                                     self._PlayerS[i].death,
  202.                                                                     self._PlayerS[i].assist,
  203.                                                                     self._PlayerS[i].cs, self._PlayerS[i].gold)) + \
  204.                          BLUE_FRAME(D) + RED_FRAME(D) + \
  205.                          ('{:<14}{:2} {:2} {:2}  {:4} {:7,}'.format(''.join(self._PlayerS[i + 5].char),
  206.                                                                     self._PlayerS[i + 5].kill,
  207.                                                                     self._PlayerS[i + 5].death,
  208.                                                                     self._PlayerS[i + 5].assist,
  209.                                                                     self._PlayerS[i + 5].cs, self._PlayerS[i + 5].gold))
  210.                          + RED_FRAME(D) + ' ')
  211.         lines.append('  ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
  212.         lines.append('  ' + BLUE_FRAME(D) + 'Towers:' + '{:<5}'.format(self._database['teams'][0]['towerKills']) +\
  213.                      'Inhibitors:' + '{:<13}'.format(self._database['teams'][0]['inhibitorKills']) + BLUE_FRAME(D) +\
  214.                      RED_FRAME(D) + 'Towers:' + '{:<5}'.format(self._database['teams'][1]['towerKills']) +\
  215.                      'Inhibitors' + ':{:<13}'.format(self._database['teams'][1]['inhibitorKills']) + RED_FRAME(D))
  216.         lines.append('  ' + BLUE_FRAME(D) + 'Dragon:' + '{:<5}'.format(self._database['teams'][0]['dragonKills']) +\
  217.                      'RiftHerald:' + '{:<4}'.format(self._database['teams'][0]['riftHeraldKills']) +\
  218.                      'Baron:' + '{:<3}'.format(self._database['teams'][0]['baronKills']) + BLUE_FRAME(D) +\
  219.                      RED_FRAME(D) + 'Dragon:' + '{:<5}'.format(self._database['teams'][1]['dragonKills']) +\
  220.                      'RiftHerald:' + '{:<4}'.format(self._database['teams'][1]['riftHeraldKills']) +\
  221.                      'Baron:' + '{:<3}'.format(self._database['teams'][1]['baronKills'])+ RED_FRAME(D))
  222.         lines.append('  ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
  223.         lines.append('  ' + BLUE_FRAME(D) + BLUExYELLOW('Bans:') + ' ' * 7 + \
  224.                      '{:<12}'.format(BlueBans[0]) + '{:<12}'.format(BlueBans[1]) + BLUE_FRAME(D) + \
  225.                      RED_FRAME(D) + REDxYELLOW('Bans:') + ' ' * 7 + \
  226.                      '{:<12}'.format(RedBans[0]) + '{:<12}'.format(RedBans[1]) + RED_FRAME(D))
  227.         lines.append('  ' + BLUE_FRAME(D) + '{:<12}'.format(BlueBans[2]) + '{:<12}'.format(BlueBans[3]) +
  228.                      '{:<12}'.format(BlueBans[4]) + BLUE_FRAME(D) + RED_FRAME(D) + '{:<12}'.format(RedBans[2]) +
  229.                      '{:<12}'.format(RedBans[3]) + '{:<12}'.format(RedBans[4]) + RED_FRAME(D))
  230.         lines.append('  ' + BLUE_FRAME(D * 38) + RED_FRAME(D * 38) + ' ')
  231.         lines.append('')
  232.         ########################### ↑PAGE 2   PAGE 3↓ ###################################
  233.         lines.append(BLUE(TOPRULE))
  234.         lines.append(' ' + BLUE(L) + '{:<82}'.format(BLUE_TEAM(self.team1)) + BLUE(L))
  235.         lines.append(' ' + BLUE(L) + BLUExYELLOW('Player' + ' ' * 11 + 'KP%    Gold    GP%   Damage   DP%   D/G%    Tank    TP%  ')+ BLUE(L))
  236.         lines.append(BLUE(MIDRULE))
  237.  
  238.         KillA = 0
  239.         KillB = 0
  240.         TotalGoldA = 0
  241.         TotalGoldB = 0
  242.         TotalDamageA = 0
  243.         TotalDamageB = 0
  244.         TotalTankA = 0
  245.         TotalTankB = 0
  246.         for k in range(5):
  247.             KillA += self._PlayerS[k].kill
  248.             KillB += self._PlayerS[k + 5].kill
  249.             TotalGoldA += self._PlayerS[k].gold
  250.             TotalGoldB += self._PlayerS[k + 5].gold
  251.             TotalDamageA += self._PlayerS[k].damage
  252.             TotalDamageB += self._PlayerS[k + 5].damage
  253.             TotalTankA += self._PlayerS[k].tank
  254.             TotalTankB += self._PlayerS[k + 5].tank
  255.  
  256.         for i in range(5):
  257.             if KillA == 0:
  258.                 self._PlayerS[i].KP = 0
  259.             else:
  260.                 self._PlayerS[i].KP = (self._PlayerS[i].kill + self._PlayerS[i].assist) / KillA
  261.             lines.append(' ' + BLUE(L) + CYAN('{:<15}'.format(players[i])) +
  262.                          ('{:6.1%} {:7,} {:6.1%} {:7,} {:6.1%} {:6.1%} {:7,} {:6.1%}'
  263.                           .format(self._PlayerS[i].KP,
  264.                                   self._PlayerS[i].gold, self._PlayerS[i].gold/TotalGoldA,self._PlayerS[i].damage,
  265.                                   self._PlayerS[i].damage / TotalDamageA, self._PlayerS[i].damage / self._PlayerS[i].gold,
  266.                                   self._PlayerS[i].tank, self._PlayerS[i].tank / TotalTankA) ) + ' ' + BLUE(L))
  267.  
  268.         lines.append(' ' + BLUE(L) + BRAZIL('Total'+' ' * 9 + 'Kills:' + '{:<2}'.format(KillA) + ' ' * 5 + 'Gold:' +
  269.                      '{:<7,}'.format(TotalGoldA) + ' ' * 4 +'Damage:' + '{:<7,}'.format(TotalDamageA) + ' '*17)+ BLUE(L))
  270.         lines.append(BLUE(MIDRULE))
  271.         lines.append(' ' + RED(L) + '{:<82}'.format(PURPLE_TEAM(self.team2)) + RED(L))
  272.         lines.append(' ' + RED(L) + REDxYELLOW(
  273.             'Player' + ' ' * 11 + 'KP%    Gold    GP%   Damage   DP%   D/G%    Tank    TP%  ') + RED(L))
  274.         lines.append(RED(MIDRULE))
  275.  
  276.         for i in range(5):
  277.             if KillB == 0:
  278.                 self._PlayerS[i+5].KP = 0
  279.             else:
  280.                 self._PlayerS[i+5].KP = (self._PlayerS[i+5].kill + self._PlayerS[i+5].assist) / KillB
  281.             lines.append(' ' + RED(L) + RED('{:<15}'.format(players[i+5])) +
  282.                          ('{:6.1%} {:7,} {:6.1%} {:7,} {:6.1%} {:6.1%} {:7,} {:6.1%}'
  283.                           .format(self._PlayerS[i+5].KP,
  284.                                   self._PlayerS[i+5].gold, self._PlayerS[i+5].gold / TotalGoldB, self._PlayerS[i+5].damage,
  285.                                   self._PlayerS[i+5].damage / TotalDamageB,
  286.                                   self._PlayerS[i+5].damage / self._PlayerS[i+5].gold,
  287.                                   self._PlayerS[i+5].tank, self._PlayerS[i+5].tank / TotalTankB)) + ' ' + RED(L))
  288.         lines.append(' ' + RED(L) + BRAZIL('Total' + ' ' * 9 + 'Kills:' + '{:<2}'.format(KillB) + ' ' * 5 + 'Gold:' +
  289.                                             '{:<7,}'.format(TotalGoldB) + ' ' * 4 + 'Damage:' + '{:<7,}'.format(
  290.             TotalDamageB) + ' ' * 17) + RED(L))
  291.         lines.append(RED(BOTRULE))
  292.         lines.append('')
  293.  
  294.         return lines
  295.  
  296.     def ANSI(self):
  297.         return "\n".join(self.ANSIlines)
  298.  
  299.     def copy2clipboard(self):
  300.         pyperclip.copy(self.ANSI())
  301.  
  302.     def _game_time_label(self):
  303.         # Width: 16
  304.         # Height: 4
  305.         yield '{:^16}'.format('Version {}'.format('.'.join(self._database['gameVersion'].split('.')[:2])))
  306.         yield ' ' * 16
  307.         yield '☆{:^12}★'.format(time.strftime('%Y %m/%d', time.gmtime(self._database['gameCreation'] / 1e3)))
  308.         yield ' ' * 16
  309.  
  310.     def _match_history_label(self):
  311.         # Width: 40
  312.         # Height: 4
  313.         yield '{:^40}'.format('Match History')
  314.         yield ' ' * 40
  315.         yield '{:^40}'.format(self.urls['short-url'])
  316.         yield ' ' * 40
  317.  
  318.     def _game_duration_label(self):
  319.         # Width: 16
  320.         # Heigth: 4
  321.         m, s = divmod(self._database['gameDuration'], 60)
  322.         yield '    ─────┐'
  323.         yield '   │Game time│'
  324.         yield '   │{:^9}│'.format('{:02}:{:02}'.format(m, s))
  325.         yield '   └───── '
  326.  
  327.     def _winner_label(self, is_winner):
  328.         # Width: 10
  329.         # Height: 3
  330.         if is_winner.upper() == 'WIN':
  331.             yield BRAZIL('┌───┐')
  332.             yield BRAZIL(L + 'WIN' + L)
  333.             yield BRAZIL('└───┘')
  334.         else:
  335.             yield ' ' * 10
  336.             yield ' ' * 10
  337.             yield ' ' * 10
  338.  
  339.     @staticmethod
  340.     def _team_label(team, side):
  341.         # Width: 27
  342.         # Height: 3
  343.         if side == 0:
  344.             colorize = BLUE_TEAM
  345.         else:
  346.             colorize = PURPLE_TEAM
  347.         yield ' ' * 27
  348.         q, r = divmod(27 - len(team), 2)
  349.         yield ' ' * q + colorize(team) + ' ' * (q + r)
  350.         yield ' ' * 27
  351.  
  352.  
  353. if __name__ == '__main__':
  354.     import argparse
  355.  
  356.     parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  357.     parser.add_argument('game_id', nargs=1,
  358.                         help='game-id of the game')
  359.     parser.add_argument('--short-url', default=None,
  360.                         help='link to the "Match History" which will display in the box. If it is not given, a "google short URL" will be automatically generated. An  API Key from google is needed for this function. See https://developers.google.com/url-shortener/v1/getting_started.')
  361.     parser.add_argument('--teams', '-t', nargs=2, default=['Blue', 'Purple'],
  362.                         help='The names of the two teams.')
  363.     parser.add_argument('--copy2clipboard', '-c', action='store_true',
  364.                         help='Copy the box to clipboard. "pyperclip" module is required for this function.')
  365.  
  366.     args = parser.parse_args()
  367.     b = Box1(team1=args.teams[0], team2=args.teams[1], gameid=args.game_id[0], short_url=args.short_url)
  368.  
  369.     if not args.copy2clipboard:
  370.         #print(b.ANSI())
  371.         fo.write(b.ANSI())
  372.         print('Text has been produced in gameresult.txt.')
  373.  
  374.     else:
  375.         b.copy2clipboard()
  376.         print('Text has been copied to clipboard.')
  377.  
  378. fo.close()
Advertisement
Add Comment
Please, Sign In to add comment