4 import pyramid.httpexceptions
6 import sqlalchemy as sa
7 import sqlalchemy.sql.functions as func
9 from calendar import timegm
10 from collections import namedtuple
11 from pyramid.url import current_route_url
12 from sqlalchemy import desc, distinct
13 from webhelpers.paginate import Page, PageURL
14 from xonstat.models import *
15 from xonstat.util import page_url, to_json, pretty_date
16 from xonstat.views.helpers import RecentGame, recent_games_q
18 log = logging.getLogger(__name__)
21 def player_index_data(request):
22 if request.params.has_key('page'):
23 current_page = request.params['page']
28 player_q = DBSession.query(Player).\
29 filter(Player.player_id > 2).\
30 filter(Player.active_ind == True).\
31 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
32 order_by(Player.player_id.desc())
34 players = Page(player_q, current_page, items_per_page=10, url=page_url)
36 except Exception as e:
40 return {'players':players
44 def player_index(request):
46 Provides a list of all the current players.
48 return player_index_data(request)
51 def player_index_json(request):
53 Provides a list of all the current players. JSON.
55 return [{'status':'not implemented'}]
58 def get_games_played(player_id):
60 Provides a breakdown by gametype of the games played by player_id.
62 Returns a list of namedtuples with the following members:
69 The list itself is ordered by the number of games played
71 GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
74 raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
76 "SELECT game_type_cd, "
79 "FROM (SELECT g.game_id, "
82 "WHEN g.winner = pgs.team THEN 1 "
83 "WHEN pgs.rank = 1 THEN 1 "
87 "WHEN g.winner = pgs.team THEN 0 "
88 "WHEN pgs.rank = 1 THEN 0 "
92 "player_game_stats pgs "
93 "WHERE g.game_id = pgs.game_id "
94 "AND pgs.player_id = :player_id) win_loss "
95 "GROUP BY game_type_cd "
96 ).params(player_id=player_id).all()
102 for row in raw_games_played:
103 games = row.wins + row.losses
104 overall_games += games
105 overall_wins += row.wins
106 overall_losses += row.losses
107 win_pct = float(row.wins)/games * 100
109 games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
110 row.losses, win_pct))
113 overall_win_pct = float(overall_wins)/overall_games * 100
115 overall_win_pct = 0.0
117 games_played.append(GamesPlayed('overall', overall_games, overall_wins,
118 overall_losses, overall_win_pct))
120 # sort the resulting list by # of games played
121 games_played = sorted(games_played, key=lambda x:x.games)
122 games_played.reverse()
126 def get_overall_stats(player_id):
128 Provides a breakdown of stats by gametype played by player_id.
130 Returns a dictionary of namedtuples with the following members:
134 - last_played (last time the player played the game type)
135 - last_played_epoch (same as above, but in seconds since epoch)
136 - last_played_fuzzy (same as above, but in relative date)
137 - total_playing_time (total amount of time played the game type)
138 - total_pickups (ctf only)
139 - total_captures (ctf only)
140 - cap_ratio (ctf only)
141 - total_carrier_frags (ctf only)
144 The key to the dictionary is the game type code. There is also an
145 "overall" game_type_cd which sums the totals and computes the total ratios.
147 OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
148 'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
149 'total_playing_time', 'total_pickups', 'total_captures', 'cap_ratio',
150 'total_carrier_frags', 'game_type_cd'])
152 raw_stats = DBSession.query('game_type_cd', 'total_kills',
153 'total_deaths', 'last_played', 'total_playing_time',
154 'total_pickups', 'total_captures', 'total_carrier_frags').\
156 "SELECT g.game_type_cd, "
157 "Sum(pgs.kills) total_kills, "
158 "Sum(pgs.deaths) total_deaths, "
159 "Max(pgs.create_dt) last_played, "
160 "Sum(pgs.alivetime) total_playing_time, "
161 "Sum(pgs.pickups) total_pickups, "
162 "Sum(pgs.captures) total_captures, "
163 "Sum(pgs.carrier_frags) total_carrier_frags "
165 "player_game_stats pgs "
166 "WHERE g.game_id = pgs.game_id "
167 "AND pgs.player_id = :player_id "
168 "GROUP BY g.game_type_cd "
169 ).params(player_id=player_id).all()
171 # to be indexed by game_type_cd
174 # sums for the "overall" game type (which is fake)
177 overall_last_played = None
178 overall_playing_time = datetime.timedelta(seconds=0)
179 overall_carrier_frags = 0
181 for row in raw_stats:
182 # running totals or mins
183 overall_kills += row.total_kills or 0
184 overall_deaths += row.total_deaths or 0
186 if overall_last_played is None or row.last_played > overall_last_played:
187 overall_last_played = row.last_played
189 overall_playing_time += row.total_playing_time
191 # individual gametype ratio calculations
193 k_d_ratio = float(row.total_kills)/row.total_deaths
198 cap_ratio = float(row.total_captures)/row.total_pickups
202 overall_carrier_frags += row.total_carrier_frags or 0
204 # everything else is untouched or "raw"
205 os = OverallStats(total_kills=row.total_kills,
206 total_deaths=row.total_deaths,
208 last_played=row.last_played,
209 last_played_epoch=timegm(row.last_played.timetuple()),
210 last_played_fuzzy=pretty_date(row.last_played),
211 total_playing_time=row.total_playing_time,
212 total_pickups=row.total_pickups,
213 total_captures=row.total_captures,
215 total_carrier_frags=row.total_carrier_frags,
216 game_type_cd=row.game_type_cd)
218 overall_stats[row.game_type_cd] = os
220 # and lastly, the overall stuff
222 overall_k_d_ratio = float(overall_kills)/overall_deaths
224 overall_k_d_ratio = None
226 os = OverallStats(total_kills=overall_kills,
227 total_deaths=overall_deaths,
228 k_d_ratio=overall_k_d_ratio,
229 last_played=overall_last_played,
230 last_played_epoch=timegm(overall_last_played.timetuple()),
231 last_played_fuzzy=pretty_date(overall_last_played),
232 total_playing_time=overall_playing_time,
236 total_carrier_frags=overall_carrier_frags,
237 game_type_cd='overall')
239 overall_stats['overall'] = os
244 def get_fav_maps(player_id, game_type_cd=None):
246 Provides a breakdown of favorite maps by gametype.
248 Returns a dictionary of namedtuples with the following members:
250 - map_name (map name)
254 The favorite map is defined as the map you've played the most
255 for the given game_type_cd.
257 The key to the dictionary is the game type code. There is also an
258 "overall" game_type_cd which is the overall favorite map. This is
259 defined as the favorite map of the game type you've played the
260 most. The input parameter game_type_cd is for this.
262 FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
264 raw_favs = DBSession.query('game_type_cd', 'map_name',
265 'map_id', 'times_played').\
267 "SELECT game_type_cd, "
271 "FROM (SELECT g.game_type_cd, "
274 "Count(*) times_played, "
277 "partition BY g.game_type_cd "
278 "ORDER BY Count(*) DESC, m.map_id ASC) rank "
280 "player_game_stats pgs, "
282 "WHERE g.game_id = pgs.game_id "
283 "AND g.map_id = m.map_id "
284 "AND pgs.player_id = :player_id "
285 "GROUP BY g.game_type_cd, "
287 "m.name) most_played "
289 "ORDER BY times_played desc "
290 ).params(player_id=player_id).all()
295 fv = FavMap(map_name=row.map_name,
297 times_played=row.times_played,
298 game_type_cd=row.game_type_cd)
300 # if we aren't given a favorite game_type_cd
301 # then the overall favorite is the one we've
303 if overall_fav is None:
304 fav_maps['overall'] = fv
305 overall_fav = fv.game_type_cd
307 # otherwise it is the favorite map from the
308 # favorite game_type_cd (provided as a param)
309 # and we'll overwrite the first dict entry
310 if game_type_cd == fv.game_type_cd:
311 fav_maps['overall'] = fv
313 fav_maps[row.game_type_cd] = fv
318 def get_ranks(player_id):
320 Provides a breakdown of the player's ranks by game type.
322 Returns a dictionary of namedtuples with the following members:
327 The key to the dictionary is the game type code. There is also an
328 "overall" game_type_cd which is the overall best rank.
330 Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
332 raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
334 "select pr.game_type_cd, pr.rank, overall.max_rank "
335 "from player_ranks pr, "
336 "(select game_type_cd, max(rank) max_rank "
338 "group by game_type_cd) overall "
339 "where pr.game_type_cd = overall.game_type_cd "
340 "and player_id = :player_id "
342 params(player_id=player_id).all()
345 found_top_rank = False
346 for row in raw_ranks:
347 rank = Rank(rank=row.rank,
348 max_rank=row.max_rank,
349 percentile=100 - 100*float(row.rank)/row.max_rank,
350 game_type_cd=row.game_type_cd)
353 if not found_top_rank:
354 ranks['overall'] = rank
355 found_top_rank = True
356 elif rank.percentile > ranks['overall'].percentile:
357 ranks['overall'] = rank
359 ranks[row.game_type_cd] = rank
364 def get_elos(player_id):
366 Provides a breakdown of the player's elos by game type.
368 Returns a dictionary of namedtuples with the following members:
374 The key to the dictionary is the game type code. There is also an
375 "overall" game_type_cd which is the overall best rank.
377 raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
378 order_by(PlayerElo.elo.desc()).all()
381 found_max_elo = False
383 if not found_max_elo:
384 elos['overall'] = row
387 elos[row.game_type_cd] = row
392 def get_recent_games(player_id):
394 Provides a list of recent games for a player. Uses the recent_games_q helper.
396 # recent games played in descending order
397 rgs = recent_games_q(player_id=player_id).limit(10).all()
398 recent_games = [RecentGame(row) for row in rgs]
403 def get_recent_weapons(player_id):
405 Returns the weapons that have been used in the past 90 days
406 and also used in 5 games or more.
408 cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
410 for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
411 filter(PlayerWeaponStat.player_id == player_id).\
412 filter(PlayerWeaponStat.create_dt > cutoff).\
413 group_by(PlayerWeaponStat.weapon_cd).\
414 having(func.count() > 4).\
416 recent_weapons.append(weapon[0])
418 return recent_weapons
421 def get_accuracy_stats(player_id, weapon_cd, games):
423 Provides accuracy for weapon_cd by player_id for the past N games.
425 # Reaching back 90 days should give us an accurate enough average
426 # We then multiply this out for the number of data points (games) to
427 # create parameters for a flot graph
429 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
430 func.sum(PlayerWeaponStat.fired)).\
431 filter(PlayerWeaponStat.player_id == player_id).\
432 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
435 avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
437 # Determine the raw accuracy (hit, fired) numbers for $games games
438 # This is then enumerated to create parameters for a flot graph
439 raw_accs = DBSession.query(PlayerWeaponStat.game_id,
440 PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
441 filter(PlayerWeaponStat.player_id == player_id).\
442 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
443 order_by(PlayerWeaponStat.game_id.desc()).\
447 # they come out in opposite order, so flip them in the right direction
451 for i in range(len(raw_accs)):
452 accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
460 def get_damage_stats(player_id, weapon_cd, games):
462 Provides damage info for weapon_cd by player_id for the past N games.
465 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
466 func.sum(PlayerWeaponStat.hit)).\
467 filter(PlayerWeaponStat.player_id == player_id).\
468 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
471 avg = round(float(raw_avg[0])/raw_avg[1], 2)
473 # Determine the damage efficiency (hit, fired) numbers for $games games
474 # This is then enumerated to create parameters for a flot graph
475 raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
476 PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
477 filter(PlayerWeaponStat.player_id == player_id).\
478 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
479 order_by(PlayerWeaponStat.game_id.desc()).\
483 # they come out in opposite order, so flip them in the right direction
487 for i in range(len(raw_dmgs)):
488 # try to derive, unless we've hit nothing then set to 0!
490 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
494 dmgs.append((raw_dmgs[i][0], dmg))
495 except Exception as e:
502 def player_info_data(request):
503 player_id = int(request.matchdict['id'])
508 player = DBSession.query(Player).filter_by(player_id=player_id).\
509 filter(Player.active_ind == True).one()
511 games_played = get_games_played(player_id)
512 overall_stats = get_overall_stats(player_id)
513 fav_maps = get_fav_maps(player_id)
514 elos = get_elos(player_id)
515 ranks = get_ranks(player_id)
516 recent_games = get_recent_games(player_id)
517 recent_weapons = get_recent_weapons(player_id)
519 except Exception as e:
529 return {'player':player,
530 'games_played':games_played,
531 'overall_stats':overall_stats,
535 'recent_games':recent_games,
536 'recent_weapons':recent_weapons
540 def player_info(request):
542 Provides detailed information on a specific player
544 return player_info_data(request)
547 def player_info_json(request):
549 Provides detailed information on a specific player. JSON.
552 # All player_info fields are converted into JSON-formattable dictionaries
553 player_info = player_info_data(request)
555 player = player_info['player'].to_dict()
558 for game in player_info['games_played']:
559 games_played[game.game_type_cd] = to_json(game)
562 for gt,stats in player_info['overall_stats'].items():
563 overall_stats[gt] = to_json(stats)
566 for gt,elo in player_info['elos'].items():
567 elos[gt] = to_json(elo.to_dict())
570 for gt,rank in player_info['ranks'].items():
571 ranks[gt] = to_json(rank)
574 for gt,mapinfo in player_info['fav_maps'].items():
575 fav_maps[gt] = to_json(mapinfo)
578 for game in player_info['recent_games']:
579 recent_games.append(to_json(game))
581 #recent_weapons = player_info['recent_weapons']
585 'games_played': games_played,
586 'overall_stats': overall_stats,
587 'fav_maps': fav_maps,
590 'recent_games': recent_games,
591 # 'recent_weapons': recent_weapons,
592 'recent_weapons': ['not implemented'],
594 #return [{'status':'not implemented'}]
597 def player_game_index_data(request):
598 player_id = request.matchdict['player_id']
600 if request.params.has_key('page'):
601 current_page = request.params['page']
606 player = DBSession.query(Player).filter_by(player_id=player_id).\
607 filter(Player.active_ind == True).one()
609 rgs_q = recent_games_q(player_id=player.player_id)
611 games = Page(rgs_q, current_page, items_per_page=10, url=page_url)
613 # replace the items in the canned pagination class with more rich ones
614 games.items = [RecentGame(row) for row in games.items]
616 except Exception as e:
621 'player_id':player.player_id,
627 def player_game_index(request):
629 Provides an index of the games in which a particular
630 player was involved. This is ordered by game_id, with
631 the most recent game_ids first. Paginated.
633 return player_game_index_data(request)
636 def player_game_index_json(request):
638 Provides an index of the games in which a particular
639 player was involved. This is ordered by game_id, with
640 the most recent game_ids first. Paginated. JSON.
642 return [{'status':'not implemented'}]
645 def player_accuracy_data(request):
646 player_id = request.matchdict['id']
647 allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
651 if request.params.has_key('weapon'):
652 if request.params['weapon'] in allowed_weapons:
653 weapon_cd = request.params['weapon']
655 if request.params.has_key('games'):
657 games = request.params['games']
666 (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
668 # if we don't have enough data for the given weapon
669 if len(accs) < games:
673 'player_id':player_id,
674 'player_url':request.route_url('player_info', id=player_id),
682 def player_accuracy(request):
684 Provides the accuracy for the given weapon. (JSON only)
686 return player_accuracy_data(request)
689 def player_accuracy_json(request):
691 Provides a JSON response representing the accuracy for the given weapon.
694 weapon = which weapon to display accuracy for. Valid values are 'nex',
695 'shotgun', 'uzi', and 'minstanex'.
696 games = over how many games to display accuracy. Can be up to 50.
698 return player_accuracy_data(request)
701 def player_damage_data(request):
702 player_id = request.matchdict['id']
703 allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
704 'rocketlauncher', 'laser']
705 weapon_cd = 'rocketlauncher'
708 if request.params.has_key('weapon'):
709 if request.params['weapon'] in allowed_weapons:
710 weapon_cd = request.params['weapon']
712 if request.params.has_key('games'):
714 games = request.params['games']
723 (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
725 # if we don't have enough data for the given weapon
726 if len(dmgs) < games:
730 'player_id':player_id,
731 'player_url':request.route_url('player_info', id=player_id),
739 def player_damage_json(request):
741 Provides a JSON response representing the damage for the given weapon.
744 weapon = which weapon to display damage for. Valid values are
745 'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
747 games = over how many games to display damage. Can be up to 50.
749 return player_damage_data(request)
752 def player_hashkey_info_data(request):
753 hashkey = request.matchdict['hashkey']
755 player = DBSession.query(Player).\
756 filter(Player.player_id == Hashkey.player_id).\
757 filter(Player.active_ind == True).\
758 filter(Hashkey.hashkey == hashkey).one()
760 games_played = get_games_played(player.player_id)
761 overall_stats = get_overall_stats(player.player_id)
762 fav_maps = get_fav_maps(player.player_id)
763 elos = get_elos(player.player_id)
764 ranks = get_ranks(player.player_id)
766 except Exception as e:
775 return {'player':player,
776 'games_played':games_played,
777 'overall_stats':overall_stats,
784 def player_hashkey_info_json(request):
786 Provides detailed information on a specific player. JSON.
789 # All player_info fields are converted into JSON-formattable dictionaries
790 player_info = player_hashkey_info_data(request)
792 player = player_info['player'].to_dict()
795 for game in player_info['games_played']:
796 games_played[game.game_type_cd] = to_json(game)
799 for gt,stats in player_info['overall_stats'].items():
800 overall_stats[gt] = to_json(stats)
803 for gt,elo in player_info['elos'].items():
804 elos[gt] = to_json(elo.to_dict())
807 for gt,rank in player_info['ranks'].items():
808 ranks[gt] = to_json(rank)
811 for gt,mapinfo in player_info['fav_maps'].items():
812 fav_maps[gt] = to_json(mapinfo)
817 'games_played': games_played,
818 'overall_stats': overall_stats,
819 'fav_maps': fav_maps,
825 def player_elo_info_data(request):
827 Provides elo information on a specific player. Raw data is returned.
829 hashkey = request.matchdict['hashkey']
831 player = DBSession.query(Player).\
832 filter(Player.player_id == Hashkey.player_id).\
833 filter(Player.active_ind == True).\
834 filter(Hashkey.hashkey == hashkey).one()
836 elos = get_elos(player.player_id)
838 except Exception as e:
840 raise pyramid.httpexceptions.HTTPNotFound
845 def player_elo_info_json(request):
847 Provides elo information on a specific player. JSON.
849 elo_info = player_elo_info_data(request)
852 for gt, elo in elo_info['elos'].items():
853 elos[gt] = to_json(elo.to_dict())