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
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
21
22 rawData = _get_json_data(eid)
23 if rawData is None or rawData.strip() == '{}':
24 return None
25 game = object.__new__(cls, eid)
26 game.rawData = rawData
27 return game
28
30 """
31 Creates a new Game instance given a game identifier.
32
33 The game identifier is used by NFL.com's GameCenter live update web
34 pages. It is used to construct a URL to download JSON data for the
35 game.
36
37 If the game has been completed, the JSON data will be cached to disk
38 so that subsequent accesses will not re-download the data but instead
39 read it from disk.
40
41 When the JSON data is written to disk, it is compressed using gzip.
42 """
43
44 self.eid = eid
45 self.data = json.loads(self.rawData)[self.eid]
46
47 self.__load_all_players(self.data)
48 self.players = player.Players(self.__players)
49
50
51 self.qtr = self.data['qtr']
52 self.clock = self.data['clock']
53 self.home = self.data['home']['abbr']
54 self.away = self.data['away']['abbr']
55 self.score_home = int(self.data['home']['score']['T'])
56 self.score_away = int(self.data['away']['score']['T'])
57 for q in (1, 2, 3, 4, 5):
58 for team in ('home', 'away'):
59 score = self.data[team]['score'][str(q)]
60 self.__dict__['score_%s_q%d' % (team, q)] = int(score)
61 if self.score_home > self.score_away:
62 self.winner = self.home
63 elif self.score_away > self.score_home:
64 self.winner = self.away
65 else:
66 self.winner = 'TIE'
67
68
69 self.scores = []
70 for k in sorted(map(int, self.data['scrsummary'])):
71 play = self.data['scrsummary'][str(k)]
72 s = '%s - Q%d - %s - %s' \
73 % (play['team'], play['qtr'], play['type'], play['desc'])
74 self.scores.append(s)
75
76 fpath = _jsonf % eid
77 if self.game_over() and not os.access(fpath, os.R_OK):
78 print >> gzip.open(fpath, 'w+'), self.rawData,
79
81 """game_over returns true if the game is no longer being played."""
82 return self.qtr == 'Final'
83
85 """playing returns true if the game is currently being played."""
86 return self.qtr != 'Pregame' and self.qtr != 'Final'
87
89 self.__players = OrderedDict()
90 for team in ("home", "away"):
91 for category in player.categories:
92 if category not in gameData[team]["stats"]:
93 continue
94 catplayers = gameData[team]["stats"][category]
95 for playerid, stats in catplayers.iteritems():
96 p = self.__get_or_add_player(playerid, stats["name"],
97 team == "home")
98 p._add_stats(category, stats)
99
106
108 """
109 Returns the JSON data corresponding to the game represented by eid.
110
111 If the JSON data is already on disk, it is read, decompressed and returned.
112
113 Otherwise, the JSON data is downloaded from the NFL web site. If the data
114 doesn't exist yet or there was an error, _get_json_data returns None.
115 """
116 fpath = _jsonf % eid
117 if os.access(fpath, os.R_OK):
118 return gzip.open(fpath).read()
119 try:
120 return urllib2.urlopen(_json_base_url % (eid, eid)).read()
121 except urllib2.HTTPError:
122 pass
123 return None
124