def handle_state(obj): if STATE == CMD_PROFILE: PlayerDB.get_player_profile(obj) elif STATE == CMD_SEASON: PlayerDB.get_player_stat(obj) elif STATE == CMD_SEASON_ALL: PlayerDB.get_player_stat(obj, True) elif STATE == CMD_PLAYOFF: PlayerDB.get_player_stat(obj, playoff=True) elif STATE == CMD_PLAYOFF_ALL: PlayerDB.get_player_stat(obj, True, playoff=True) elif STATE == CMD_DRAFT: PlayerDB.get_player_draft(obj) elif STATE == CMD_AWARD: PlayerDB.get_player_award(obj) elif STATE == CMD_AWARD_ALL: PlayerDB.get_player_award(obj, True) elif STATE == CMD_GAME_LOG: PlayerDB.get_player_log(obj, args, "Regular Season") elif STATE == CMD_GAME_PLAYOFF_LOG: PlayerDB.get_player_log(obj, args, "Playoffs") elif STATE == CMD_GAME_ALLSTAR_LOG: PlayerDB.get_player_log(obj, args, "All Star") elif STATE == CMD_ADVANCED: PlayerDB.get_player_stat_advanced(obj) elif STATE == CMD_ADVANCED_PLAYOFF: PlayerDB.get_player_stat_advanced(obj, True) else: Log.red("unkown cmd:" + STATE)
def handle(self, cmd): if cmd == Constant.COMMAND_QUIT or cmd == Constant.COMMAND_EXIT: # quit Log.red("bye~") quit(1) elif cmd == Constant.COMMAND_VERSION: Log.red(Constant.VERSION) elif cmd == Constant.COMMAND_HELP: Constant.help()
def handle_state(obj): if STATE == CMD_PROFILE: TeamDB.get_profile(obj) elif STATE == CMD_ROSTER: TeamDB.get_roster(obj, args) elif STATE == CMD_STAT: TeamDB.get_stat(obj, "Regular Season", args) elif STATE == CMD_STAT_PLAYOFF: TeamDB.get_stat(obj, "Playoffs", args) elif STATE == CMD_GAME_LOG: TeamDB.get_game_log(obj, "Regular Season", args) elif STATE == CMD_GAME_LOG_PLAYOFF: TeamDB.get_game_log(obj, "Playoffs", args) else: Log.red("unkown cmd:" + STATE)
def get_roster(team_obj, sesson): if sesson is None: sesson = Utils.make_season() elif not Utils.validate_date(sesson): Log.red('illegal date! pattern is yyyy-yy as 2017-18.') return teamid = team_obj['teamId'] Progress.mock_wait('load team roster:' + str(teamid)) h = dict(Constant.HEADERS) resp = requests.get(__ROSTER_API.format(TeamID=teamid, Season=sesson), params=None, headers=h, timeout=6) resp.raise_for_status() resp_json = resp.json() roster_arr = resp_json['resultSets'] Progress.mock_end() Display.display_team_roster(roster_arr, sesson)
def get_game_log(team_obj, season_type, sesson): if sesson is None: sesson = Utils.make_season() elif not Utils.validate_date(sesson): Log.red('illegal date! pattern is yyyy-yy as 2017-18.') return teamid = team_obj['teamId'] Progress.mock_wait('load team game log:' + str(teamid)) h = dict(Constant.HEADERS) resp = requests.get(__GAME_LOG_API.format(TeamID=teamid, Season=sesson, SeasonType=season_type), params=None, headers=h, timeout=6) resp.raise_for_status() resp_json = resp.json() game_arr = resp_json['resultSets'][0]['rowSet'] Progress.mock_end() Display.display_team_game_log(game_arr, sesson, season_type == "Playoffs")
def display_team_profile(base_team, team_obj): table = PrettyTable([ "NAME", "TRICODE", "CITY", "CONF", "DIV", "ARENA", "COACH", "OWNER", "MANAGER", "FOUNDED" ]) if len(team_obj[0]['rowSet']) == 0: Log.red('no team profile for ' + base_team['fullName']) return profile_obj = team_obj[0]['rowSet'][0] table.add_row([ base_team['fullName'], base_team['tricode'], base_team['city'], base_team['confName'], base_team['divName'], profile_obj[5], profile_obj[9], profile_obj[7], profile_obj[8], profile_obj[3] ]) print table cham_time = len(team_obj[3]['rowSet']) conf_cham_time = len(team_obj[4]['rowSet']) retired_arr = team_obj[7]['rowSet'] table = PrettyTable(["CHAMPIONSHIP", "CONF-CHAMPIONSHIP", "TeamRetired"]) flag = True num = 0 retired_line = '' for retired_obj in retired_arr: if num % 3 > 0: retired_line += ',' jersey = str.strip(str(retired_obj[3])) retired_line += retired_obj[1] + "-" + (len(jersey) > 0 and str( retired_obj[3]) or "?") + "(" + str(retired_obj[5]) + ")" num = num + 1 if num % 3 == 0: table.add_row([ flag and cham_time or '-', flag and conf_cham_time or '-', retired_line ]) retired_line = '' flag = False if len(retired_line) > 0: table.add_row([ flag and cham_time or '-', flag and conf_cham_time or '-', retired_line ]) print table
def handle_base_profile(result, state): if result is None or len(result) == 0: Log.red("no result") elif len(result) > 1: Log.yellow("input the index to select one exact player (from 0..n)") table = PrettyTable(["name", "team", "index"]) global SELECT_PLAYER SELECT_PLAYER = result global STATE STATE = state index = 0 for obj in result: table.add_row([obj[2], obj[10], index]) index = index + 1 print table else: STATE = state handle_state(result[0]) STATE = None
def handle_base_profile(result, state): if result is None or len(result) == 0: Log.red("no result") elif len(result) > 1: Log.yellow("input the index to select one exact team (from 0..n)") table = PrettyTable(["name", "tricode", "conf", "index"]) global SELECT_TEAMS SELECT_TEAMS = result global STATE STATE = state index = 0 for obj in result: table.add_row([obj['fullName'], obj['tricode'], obj['confName'], index]) index = index + 1 print table else: global STATE STATE = state handle_state(result[0]) STATE = None
def get_player_draft(player_obj): pid = player_obj[0] json_obj = get_player_profile(player_obj, False) player_obj = json_obj["resultSets"][0]["rowSet"][0] season = player_obj[26] draft_pick = player_obj[28] if season == 'Undrafted': Log.red("un drafted") else: Progress.mock_wait('load player draft') h = dict(Constant.HEADERS) resp = requests.get( __DRAFT_API.format(PlayerId=pid, Season=season, OverallPick=draft_pick, ), params=None, headers=h, timeout=5) resp.raise_for_status() Progress.mock_end() resp_json = resp.json() draft_obj = resp_json['resultSets'][0]['rowSet'][0] Display.display_single_draft(draft_obj)
def display_team_roster(roster_arr, season): table = PrettyTable( ["SEASON", "PLAYER", "POSITION", "JERSEY", "AGE", "EXP"]) player_arr = roster_arr[0]['rowSet'] if len(player_arr) == 0: Log.red('no roster') return for player_obj in player_arr: if player_obj[9] is None: age = '' else: age = int(player_obj[9]) table.add_row([ season, player_obj[3], player_obj[5], player_obj[4], age, player_obj[10] ]) if len(roster_arr[1]['rowSet']) > 0: coach_obj = roster_arr[1]['rowSet'][0] table.add_row([season, coach_obj[5], coach_obj[8], "-", "-", "-"]) print table
def display_game_log(game_log_arr): if len(game_log_arr) == 0: Log.red("no record") return table = PrettyTable([ "DATE", "VS", "WIN", "MIN", "PTS", "REB", "AST", "OREB", "DREB", "FG_PCT", "FG3_PCT", "FT_PCT", "BLK", "STL", "TOV", "PF", "+-", "GAME_ID" ]) table.color_cols = {"GAME_ID": Log.wrap_yellow} for game_obj in game_log_arr: table.add_row([ game_obj[3], game_obj[4], game_obj[5], game_obj[6], game_obj[24], game_obj[18], game_obj[19], game_obj[16], game_obj[17], Utils.make_pct(game_obj, 7, False), Utils.make_pct(game_obj, 10, False), Utils.make_pct(game_obj, 13, False), game_obj[21], game_obj[20], game_obj[22], game_obj[23], game_obj[25], game_obj[2] ]) print table
def display_team_game_log(game_arr, season, playoff): if len(game_arr) == 0: Log.red('no record') return table = PrettyTable([ playoff and "PLAYOFF" or "SEASON", "DATE", "MATCHUP", "WL", "PTS", "FG_PCT", "FG3_PCT", "FT_PCT", "REB", "OREB", "DREB", "AST", "BLK", "STL", "TOV", "PF", "GAME_ID" ]) table.color_cols = {'GAME_ID': Log.wrap_yellow} for game_obj in game_arr: table.add_row([ season, game_obj[2], game_obj[3], game_obj[4], game_obj[26], Utils.make_pct(game_obj, 9, point=False), Utils.make_pct(game_obj, point=False), Utils.make_pct(game_obj, 15, point=False), game_obj[20], game_obj[18], game_obj[19], game_obj[21], game_obj[23], game_obj[22], game_obj[24], game_obj[25], game_obj[1] ]) print table
def get_player_log(player_obj, m_date, season_type): pid = player_obj[0] if m_date is None: m_date = Utils.make_season() elif not Utils.validate_date(m_date): Log.red('illegal date! pattern is yyyy-yy as 2017-18.') return try: Progress.mock_wait('load player game log') h = dict(Constant.HEADERS) resp = requests.get( __GAME_LOG_API.format(PlayerId=pid, Season=m_date, SeasonType=season_type), params=None, headers=h, timeout=6) resp.raise_for_status() resp_json = resp.json() log_arr = resp_json['resultSets'][0]['rowSet'] Progress.mock_end() Display.display_game_log(log_arr) except Exception, e: Progress.mock_end() print e
def display_team_stat(stat_arr, season, playoff): season_stat_arr = stat_arr[1]['rowSet'] if len(season_stat_arr) == 0: Log.red('no record') return table = PrettyTable([ playoff and "PLAYOFF" or "SEASON", "PLAYER", "GP", "MIN", "PTS", "FG_PCT", "FG3_PCT", "FT_PCT", "REB", "OREB", "DREB", "AST", "BLK", "STL", "TOV", "PF", "+-" ]) season_stat_arr = sorted(season_stat_arr, __sort_team_stat) for stat_obj in season_stat_arr: table.add_row([ season, stat_obj[2], stat_obj[3], stat_obj[7], stat_obj[27], Utils.make_pct(stat_obj, 8), Utils.make_pct(stat_obj, 11), Utils.make_pct(stat_obj, 14), stat_obj[19], stat_obj[17], stat_obj[18], stat_obj[20], stat_obj[23], stat_obj[22], stat_obj[21], stat_obj[25], stat_obj[28] ]) print table
def handle(self, cmd): Log.red("no command '" + cmd + "'. type h for help")
def handle(self, cmd): from com.magicyang import Handlers global STATE if STATE is not None: if cmd == Constant.COMMAND_QUIT: Log.magenta("player mode:") STATE = None return True elif cmd == Constant.COMMAND_EXIT: Log.red("bye~") sys.exit(1) else: obj = select_cmd(cmd) if obj is not None: handle_state(obj) STATE = None return True elif cmd == Constant.COMMAND_PLAYER: # quit Log.magenta("player mode:") Handlers.set_current(self) return True elif cmd == Constant.COMMAND_QUIT: Handlers.set_current(None) return True elif cmd == Constant.COMMAND_EXIT: Log.red("bye~") sys.exit(1) elif cmd == Constant.COMMAND_REFRESH: Log.magenta('refresh base data') DB.init(True) return True elif cmd == Constant.COMMAND_HELP: help() return True else: cmds = str.split(cmd, ' ') length = len(cmds) if length == 0: Log.red('no command!') else: player_name = cmds[0] if length >= 2: if not cmds[1].startswith('-'): lastname = cmds[1] result = DB.player(player_name, lastname) postfix = (length >= 3 and cmds[2] or CMD_PROFILE) global args args = (length >= 4 and cmds[3] or None) handle_base_profile(result, postfix) else: postfix = cmds[1] if postfix == SundryHandlers.CMD_GAME_DETAIL: SundryHandlers.game_detail(player_name) else: global args args = (length >= 3 and cmds[2] or None) result = DB.player(firstname=player_name) handle_base_profile(result, postfix) else: result = DB.player(firstname=player_name) handle_base_profile(result, CMD_PROFILE) return True
def help(): Log.magenta(" player info:") Log.magenta( " \033[33minput\033[0m player name for profile. \033[7mE.g.\033[0m lebron or lebron james" ) Log.magenta( " \033[33m-d\033[0m for draft info. \033[7mE.g.\033[0m lebron -dr") Log.magenta( " \033[33m-a\033[0m for award info. \033[7mE.g.\033[0m lebron -a") Log.magenta( " \033[33m-aa\033[0m for award detailed info. \033[7mE.g.\033[0m lebron -aa" ) Log.magenta(" stat info:") Log.magenta( " \033[33m-s\033[0m for season stat. \033[7mE.g.\033[0m lebron -s or lebron james -s" ) Log.magenta( " \033[33m-sa\033[0m for season all detailed stat. \033[7mE.g.\033[0m lebron -sa" ) Log.magenta( " \033[33m-p\033[0m for playoff stat. \033[7mE.g.\033[0m lebron -p" ) Log.magenta( " \033[33m-pa\033[0m for playoff all detailed stat. \033[7mE.g.\033[0m lebron -pa" ) Log.magenta( " \033[33m-ss\033[0m for senior season stat. \033[7mE.g.\033[0m lebron -ss" ) Log.magenta( " \033[33m-sp\033[0m for senior playoff stat. \033[7mE.g.\033[0m lebron -sp" ) Log.magenta(" game log info:") Log.magenta( " \033[33m-l\033[0m for game log. \033[7mE.g.\033[0m lebron -l") Log.magenta( " \033[33m \033[0m for 2014-15 season's game log. \033[7mE.g.\033[0m lebron -l 2014-15" ) Log.magenta( " \033[33m-lp\033[0m for playoff game log. \033[7mE.g.\033[0m lebron -lp" ) Log.magenta( " \033[33m \033[0m for 2014-15 playoff's game log. \033[7mE.g.\033[0m lebron -lp 2014-15" ) Log.magenta( " \033[33m-la\033[0m for allstar game log. \033[7mE.g.\033[0m lebron -la" ) Log.magenta( " \033[33m \033[0m for 2014-15 allstar's game log. \033[7mE.g.\033[0m lebron -la 2014-15" ) Log.red(" global:") Log.yellow( " \033[33m-d \033[0m for game detail stat,type gameid -d. \033[7mE.g.\033[0m 0041600405 -d" ) Log.magenta( "\n FOR NBA STAT TERMS,LEARN FROM https://stats.nba.com/help/glossary/" )
def help(): Log.blue(" team info:") Log.yellow( " \033[33minput\033[0m team name for team info. \033[7mE.g.\033[0m gsw or warriors" ) Log.blue(" detail info:") Log.yellow( " \033[33m-r \033[0m for team roster. \033[7mE.g.\033[0m gsw -r") Log.yellow( " \033[0m for 2014-15 season's roster. \033[7mE.g.\033[0m gsw -r 2014-15" ) Log.yellow( " \033[33m-s \033[0m for team stat. \033[7mE.g.\033[0m gsw -s") Log.yellow( " \033[0m for 2014-15 season's stat. \033[7mE.g.\033[0m gsw -s 2014-15" ) Log.yellow( " \033[33m-p \033[0m for team playoff stat. \033[7mE.g.\033[0m gsw -p" ) Log.yellow( " \033[0m for 2014-15 season's playoff stat. \033[7mE.g.\033[0m gsw -p 2014-15" ) Log.blue(" game info:") Log.yellow( " \033[33m-l \033[0m for team game log. \033[7mE.g.\033[0m gsw -l") Log.yellow( " \033[0m for 2014-15 season's team game log. \033[7mE.g.\033[0m gsw -l 2014-15" ) Log.yellow( " \033[33m-lp\033[0m for team playoff game log. \033[7mE.g.\033[0m gsw -lp" ) Log.yellow( " \033[0m for 2014-15 season's team playoff game log. \033[7mE.g.\033[0m gsw -lp 2014-15" ) Log.red(" global:") Log.yellow( " \033[33m-d\033[0m for game detail stat,type gameid -d. \033[7mE.g.\033[0m 0041600405 -d" ) Log.blue( "\n FOR NBA STAT TERMS,LEARN FROM https://stats.nba.com/help/glossary/" )
def display_game_detail(sum_arr, box_arr): line_score = sum_arr[5]['rowSet'] if len(line_score) == 0: Log.red("no record") return index = 12 titles = ['', "Q1", "Q2", "Q3", "Q4"] while index < 22 and line_score[0][index] > 0: index = index + 1 titles.append("TO" + str(index - 12)) titles.extend( ['FINAL', 'PTS_PAINT', 'PTS_2ND_CHANCE', 'PTS_OFF_TO', 'LARGEST_LEAD']) table = PrettyTable(titles) temp_index = 0 crown_index = 0 if line_score[0][22] > line_score[1][22] else 1 for score_obj in line_score: other_score = sum_arr[1]['rowSet'][temp_index] row = [ str(score_obj[4]) + (temp_index == crown_index and '' or '0041700152'), score_obj[8], score_obj[9], score_obj[10], score_obj[11] ] for i in range(12, index): row.append(score_obj[i]) row.extend([ score_obj[22], other_score[4], other_score[5], other_score[13], other_score[7] ]) temp_index = temp_index + 1 table.add_row(row) print table table = PrettyTable( ['', '', '', '', '', "", "", "", "", "", "", "", "", "", ""]) table.header = False score_arr = box_arr[0]['rowSet'] temp_team = score_arr[0][2] temp_index = 0 for box_obj in score_arr: temp_index += 1 if box_obj[2] != temp_team: table.add_row([ 'PLAYER', 'MIN', 'PTS', "FG_PCT", "FG3_PCT", "FT_PCT", "REB", "OREB", "DREB", "AST", "BLK", "STL", "TOV", "PF", "+-" ]) table.mid_head_index = temp_index temp_team = box_obj[2] dnp = box_obj[8] is None if dnp: table.add_row([ box_obj[5], 'DNP', '', '', '', '', '', '', '', '', '', '', '', '', '' ]) else: table.add_row([ box_obj[5] + (len(box_obj[6]) > 0 and " (" + box_obj[6] + ")" or ""), box_obj[8], box_obj[26], Utils.make_pct(box_obj, 9, False), Utils.make_pct(box_obj, 12, False), Utils.make_pct(box_obj, 15, False), box_obj[20], box_obj[18], box_obj[19], box_obj[21], box_obj[23], box_obj[22], box_obj[24], box_obj[25], int(box_obj[27]) ]) print table
def display_award(award_arr, cham_record, champion_detail, show_all): award_dict = {} award_detail = {} for award_obj in award_arr: award_name = award_obj[4] all_nba_team_num = award_obj[5] if all_nba_team_num is not None and len( all_nba_team_num) > 0 and 'null' not in all_nba_team_num: award_name = award_name + " " + all_nba_team_num + "th team" record = award_dict.get(award_name) if record is None: award_dict[award_name] = 1 else: award_dict[award_name] = record + 1 if show_all: detail = award_detail.get(award_name) if detail is None: detail = [] award_detail[award_name] = detail month = award_obj[7] week = award_obj[8] if month is not None and len(month) > 0 and 'null' not in month: to_append = str.replace(str(month), 'T00:00:00', '') elif week is not None and len(week) > 0 and 'null' not in week: to_append = str.replace(str(week), 'T00:00:00', '') else: to_append = award_obj[6] detail.append(to_append) for (k, v) in cham_record.items(): award_dict[k] = v if show_all: award_detail[k] = champion_detail.get(k) if len(award_dict) > 0: if show_all: table = PrettyTable(["AWARD", "TIME", "DETAIL"]) table.color_cols = {'DETAIL': Log.wrap_yellow} else: table = PrettyTable(["AWARD", "TIME"]) table.align = "c" keys = award_dict.keys() keys.sort(__sort_award) for k in keys: if show_all: init_row = True details = award_detail.get(k) write_count = 0 if details is not None: temp_detail = '' array = sorted(award_detail.get(k)) for detail in array: temp_detail = temp_detail + " " + detail write_count = write_count + 1 if write_count % 3 == 0: table.add_row([ init_row and k or '', init_row and award_dict[k] or '', temp_detail ]) init_row = False temp_detail = '' if len(temp_detail) > 0: table.add_row([ init_row and k or '', init_row and award_dict[k] or '', temp_detail ]) init_row = False if init_row is True: table.add_row([k, award_dict[k], '']) else: table.add_row([k, award_dict[k]]) print table else: Log.red("no award for this player")
def handle(self, cmd): from com.magicyang import Handlers global STATE if STATE is not None: if cmd == Constant.COMMAND_QUIT: Log.green("game mode:") STATE = None return True elif cmd == Constant.COMMAND_EXIT: Log.red("bye~") sys.exit(1) else: obj = select_cmd(cmd) if obj is not None: handle_state(obj) STATE = None return True elif cmd == Constant.COMMAND_TEAM: # quit Log.green("game mode:") Handlers.set_current(self) return True elif cmd == Constant.COMMAND_QUIT: Handlers.set_current(None) return True elif cmd == Constant.COMMAND_EXIT: Log.red("bye~") sys.exit(1) elif cmd == Constant.COMMAND_REFRESH: Log.blue('refresh base data') DB.init(True) return True elif cmd == Constant.COMMAND_HELP: help() return True else: cmds = str.split(cmd, ' ') length = len(cmds) if length == 0: Log.red('no command!') else: team_name = cmds[0] if length >= 2: postfix = cmds[1] if postfix == SundryHandlers.CMD_GAME_DETAIL: SundryHandlers.game_detail(team_name) else: global args args = (length >= 3 and cmds[2] or None) result = DB.team_by_name(team_name) handle_base_profile(result, postfix) else: result = DB.team_by_name(team_name) handle_base_profile(result, CMD_PROFILE) return True
def _stringify_row(self, row, options): for index, value in enumerate(row): row[index] = self._format_value(self.field_names[index], value) for index, field, value, width, in zip(range(0, len(row)), self._field_names, row, self._widths): # Enforce max widths max_width = self._max_width.get(field, 0) lines = _unicode(value).split("\n") new_lines = [] for line in lines: if max_width and len(line) > max_width: line = textwrap.fill(line, max_width) new_lines.append(line) lines = new_lines value = "\n".join(lines) row[index] = value # old_widths = self._widths[:] for index, field in enumerate(self._field_names): namewidth = len(field) datawidth = min(self._widths[index], self._max_width.get(field, self._widths[index])) if options["header"]: self._widths[index] = max(namewidth, datawidth) else: self._widths[index] = datawidth row_height = 0 for c in row: h = _get_size(c)[1] if h > row_height: row_height = h bits = [] lpad, rpad = self._get_padding_widths(options) for y in range(0, row_height): bits.append([]) if options["border"]: bits[y].append(self.vertical_char) for field, value, width, in zip(self._field_names, row, self._widths): lines = _unicode(value).split("\n") if len(lines) < row_height: lines = lines + ([""] * (row_height - len(lines))) y = 0 for l in lines: if options["fields"] and field not in options["fields"]: continue outter = 0 col_func = self.color_cols.get(field) if col_func is not None: l = col_func(l) outter = Log.offset() if self._align[field] == "l": bits[y].append(" " * lpad + _unicode(l).ljust(width + outter) + " " * rpad) elif self._align[field] == "r": bits[y].append(" " * lpad + _unicode(l).rjust(width + outter) + " " * rpad) else: bits[y].append(" " * lpad + _unicode(l).center(width + outter) + " " * rpad) if options["border"]: bits[y].append(self.vertical_char) y += 1 self._hrule = self._stringify_hrule(options) if options["border"] and options["hrules"] == ALL: bits[row_height - 1].append("\n") bits[row_height - 1].append(self._hrule) for y in range(0, row_height): bits[y] = "".join(bits[y]) # self._widths = old_widths return "\n".join(bits)