Package nflgame :: Module game
[frames] | no frames]

Source Code for Module nflgame.game

  1  from collections import OrderedDict 
  2  import os 
  3  import os.path as path 
  4  import gzip 
  5  import json 
  6  import urllib2 
  7   
  8  import nflgame.player as player 
  9   
 10  _jsonf = path.join(path.split(__file__)[0], 'gamecenter-json', '%s.json.gz') 
 11  _json_base_url = "http://www.nfl.com/liveupdate/game-center/%s/%s_gtd.json" 
 12   
13 -class Game (object):
14 """ 15 Game represents a single pre- or regular-season game. It provides a window 16 into the statistics of every player that played into the game, along with 17 the winner of the game, the score and a list of all the scoring plays. 18 """ 19 20 eid = 0 21 """The identifier of the player used by NFL's GameCenter live update.""" 22 23 players = None 24 """A sequence of all players that can be searched, sorted and filtered.""" 25 26 data = None 27 """The raw decoded JSON.""" 28 29 home = "" 30 """Abbreviation for the home team.""" 31 32 away = "" 33 """Abbreviation for the away team.""" 34 35 score_home_final = 0 36 """Final score for the home team.""" 37 38 score_away_final = 0 39 """Final score for the away team.""" 40 41 winner = "" 42 """Abbreviated team name of the winner of the game.""" 43 44 scores = [] 45 """A list of scoring plays in the order in which they occurred.""" 46
47 - def __init__(self, eid):
48 """ 49 Creates a new Game instance given a game identifier. 50 51 The game identifier is used by NFL.com's GameCenter live update web 52 pages. It is used to construct a URL to download JSON data for the 53 game. 54 55 If the game has been completed, the JSON data will be cached to disk 56 so that subsequent accesses will not re-download the data but instead 57 read it from disk. 58 59 When the JSON data is written to disk, it is compressed using gzip. 60 """ 61 rawData = _get_json_data(eid) 62 if rawData is None: 63 return 64 65 self.eid = eid 66 self.data = json.loads(rawData)[self.eid] 67 68 self.__load_all_players(self.data) 69 self.players = player.Players(self.__players) 70 71 fpath = _jsonf % eid 72 if self.game_over() and not os.access(fpath, os.R_OK): 73 print >> gzip.open(fpath, 'w+'), rawData, 74 75 # Load up some simple static values. 76 self.home = self.data['home']['abbr'] 77 self.away = self.data['away']['abbr'] 78 self.score_home_final = int(self.data['home']['score']['T']) 79 self.score_away_final = int(self.data['away']['score']['T']) 80 for q in (1, 2, 3, 4, 5): 81 for team in ('home', 'away'): 82 score = self.data[team]['score'][str(q)] 83 self.__dict__['score_%s_q%d' % (team, q)] = int(score) 84 if self.score_home_final > self.score_away_final: 85 self.winner = self.home 86 elif self.score_away_final > self.score_home_final: 87 self.winner = self.away 88 else: 89 self.winner = 'TIE' 90 91 # Load the scoring summary into a simple list of strings. 92 for k in sorted(map(int, self.data['scrsummary'])): 93 play = self.data['scrsummary'][str(k)] 94 s = '%s - Q%d - %s - %s' \ 95 % (play['team'], play['qtr'], play['type'], play['desc']) 96 self.scores.append(s)
97
98 - def game_over(self):
99 """game_over returns true if the game is no longer being played.""" 100 return self.data['qtr'] == 'Final'
101
102 - def __load_all_players(self, gameData):
103 self.__players = OrderedDict() 104 for team in ("home", "away"): 105 for category in player.categories: 106 if category not in gameData[team]["stats"]: 107 continue 108 catplayers = gameData[team]["stats"][category] 109 for playerid, stats in catplayers.iteritems(): 110 p = self.__get_or_add_player(playerid, stats["name"], 111 team == "home") 112 p._add_stats(category, stats)
113
114 - def __get_or_add_player(self, playerid, name, home):
115 if playerid in self.__players: 116 return self.__players[playerid] 117 p = player.Player(playerid, name, home) 118 self.__players[playerid] = p 119 return p
120
121 -def _get_json_data(eid):
122 """ 123 Returns the JSON data corresponding to the game represented by eid. 124 125 If the JSON data is already on disk, it is read, decompressed and returned. 126 127 Otherwise, the JSON data is downloaded from the NFL web site. If the data 128 doesn't exist yet or there was an error, _get_json_data returns None. 129 """ 130 fpath = _jsonf % eid 131 if os.access(fpath, os.R_OK): 132 return gzip.open(fpath).read() 133 try: 134 return urllib2.urlopen(_json_base_url % (eid, eid)).read() 135 except urllib2.HTTPError: 136 pass 137 return None
138