]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/player.py
Add a JSON Elo view to support autobalance.
[xonotic/xonstat.git] / xonstat / views / player.py
1 import datetime
2 import json
3 import logging
4 import pyramid.httpexceptions
5 import re
6 import sqlalchemy as sa
7 import sqlalchemy.sql.functions as func
8 import time
9 from calendar import timegm
10 from collections import namedtuple
11 from pyramid.response import Response
12 from pyramid.url import current_route_url
13 from sqlalchemy import desc, distinct
14 from webhelpers.paginate import Page, PageURL
15 from xonstat.models import *
16 from xonstat.util import page_url, to_json, pretty_date
17
18 log = logging.getLogger(__name__)
19
20
21 def player_index_data(request):
22     if request.params.has_key('page'):
23         current_page = request.params['page']
24     else:
25         current_page = 1
26
27     try:
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())
33
34         players = Page(player_q, current_page, items_per_page=10, url=page_url)
35
36     except Exception as e:
37         players = None
38         raise e
39
40     return {'players':players
41            }
42
43
44 def player_index(request):
45     """
46     Provides a list of all the current players.
47     """
48     return player_index_data(request)
49
50
51 def player_index_json(request):
52     """
53     Provides a list of all the current players. JSON.
54     """
55     return [{'status':'not implemented'}]
56
57
58 def get_games_played(player_id):
59     """
60     Provides a breakdown by gametype of the games played by player_id.
61
62     Returns a list of namedtuples with the following members:
63         - game_type_cd
64         - games
65         - wins
66         - losses
67         - win_pct
68
69     The list itself is ordered by the number of games played
70     """
71     GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
72         'losses', 'win_pct'])
73
74     raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
75             from_statement(
76                 "SELECT game_type_cd, "
77                        "SUM(win) wins, "
78                        "SUM(loss) losses "
79                 "FROM   (SELECT g.game_id, "
80                                "g.game_type_cd, "
81                                "CASE "
82                                  "WHEN g.winner = pgs.team THEN 1 "
83                                  "WHEN pgs.rank = 1 THEN 1 "
84                                  "ELSE 0 "
85                                "END win, "
86                                "CASE "
87                                  "WHEN g.winner = pgs.team THEN 0 "
88                                  "WHEN pgs.rank = 1 THEN 0 "
89                                  "ELSE 1 "
90                                "END loss "
91                         "FROM   games g, "
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()
97
98     games_played = []
99     overall_games = 0
100     overall_wins = 0
101     overall_losses = 0
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
108
109         games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
110             row.losses, win_pct))
111
112     try:
113         overall_win_pct = float(overall_wins)/overall_games * 100
114     except:
115         overall_win_pct = 0.0
116
117     games_played.append(GamesPlayed('overall', overall_games, overall_wins,
118         overall_losses, overall_win_pct))
119
120     # sort the resulting list by # of games played
121     games_played = sorted(games_played, key=lambda x:x.games)
122     games_played.reverse()
123     return games_played
124
125
126 def get_overall_stats(player_id):
127     """
128     Provides a breakdown of stats by gametype played by player_id.
129
130     Returns a dictionary of namedtuples with the following members:
131         - total_kills
132         - total_deaths
133         - k_d_ratio
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)
142         - game_type_cd
143
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.
146     """
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'])
151
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').\
155             from_statement(
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 "
164                 "FROM   games g, "
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()
170
171     # to be indexed by game_type_cd
172     overall_stats = {}
173
174     # sums for the "overall" game type (which is fake)
175     overall_kills = 0
176     overall_deaths = 0
177     overall_last_played = None
178     overall_playing_time = datetime.timedelta(seconds=0)
179     overall_carrier_frags = 0
180
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
185
186         if overall_last_played is None or row.last_played > overall_last_played:
187             overall_last_played = row.last_played
188
189         overall_playing_time += row.total_playing_time
190
191         # individual gametype ratio calculations
192         try:
193             k_d_ratio = float(row.total_kills)/row.total_deaths
194         except:
195             k_d_ratio = None
196
197         try:
198             cap_ratio = float(row.total_captures)/row.total_pickups
199         except:
200             cap_ratio = None
201
202         overall_carrier_frags += row.total_carrier_frags or 0
203
204         # everything else is untouched or "raw"
205         os = OverallStats(total_kills=row.total_kills,
206                 total_deaths=row.total_deaths,
207                 k_d_ratio=k_d_ratio,
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,
214                 cap_ratio=cap_ratio,
215                 total_carrier_frags=row.total_carrier_frags,
216                 game_type_cd=row.game_type_cd)
217
218         overall_stats[row.game_type_cd] = os
219
220     # and lastly, the overall stuff
221     try:
222         overall_k_d_ratio = float(overall_kills)/overall_deaths
223     except:
224         overall_k_d_ratio = None
225
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,
233             total_pickups=None,
234             total_captures=None,
235             cap_ratio=None,
236             total_carrier_frags=overall_carrier_frags,
237             game_type_cd='overall')
238
239     overall_stats['overall'] = os
240
241     return overall_stats
242
243
244 def get_fav_maps(player_id, game_type_cd=None):
245     """
246     Provides a breakdown of favorite maps by gametype.
247
248     Returns a dictionary of namedtuples with the following members:
249         - game_type_cd
250         - map_name (map name)
251         - map_id
252         - times_played
253
254     The favorite map is defined as the map you've played the most
255     for the given game_type_cd.
256
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.
261     """
262     FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
263
264     raw_favs = DBSession.query('game_type_cd', 'map_name',
265             'map_id', 'times_played').\
266             from_statement(
267                 "SELECT game_type_cd, "
268                        "name map_name, "
269                        "map_id, "
270                        "times_played "
271                 "FROM   (SELECT g.game_type_cd, "
272                                "m.name, "
273                                "m.map_id, "
274                                "Count(*) times_played, "
275                                "Row_number() "
276                                  "OVER ( "
277                                    "partition BY g.game_type_cd "
278                                    "ORDER BY Count(*) DESC, m.map_id ASC) rank "
279                         "FROM   games g, "
280                                "player_game_stats pgs, "
281                                "maps m "
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, "
286                                   "m.map_id, "
287                                   "m.name) most_played "
288                 "WHERE  rank = 1 "
289                 "ORDER BY  times_played desc "
290             ).params(player_id=player_id).all()
291
292     fav_maps = {}
293     overall_fav = None
294     for row in raw_favs:
295         fv = FavMap(map_name=row.map_name,
296             map_id=row.map_id,
297             times_played=row.times_played,
298             game_type_cd=row.game_type_cd)
299     
300         # if we aren't given a favorite game_type_cd
301         # then the overall favorite is the one we've
302         # played the most
303         if overall_fav is None:
304             fav_maps['overall'] = fv
305             overall_fav = fv.game_type_cd
306
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
312
313         fav_maps[row.game_type_cd] = fv
314
315     return fav_maps
316
317
318 def get_ranks(player_id):
319     """
320     Provides a breakdown of the player's ranks by game type.
321
322     Returns a dictionary of namedtuples with the following members:
323         - game_type_cd
324         - rank
325         - max_rank
326
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.
329     """    
330     Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
331
332     raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
333             from_statement(
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 "
337                     "from player_ranks  "
338                     "group by game_type_cd) overall "
339                 "where pr.game_type_cd = overall.game_type_cd  "
340                 "and player_id = :player_id "
341                 "order by rank").\
342             params(player_id=player_id).all()
343
344     ranks = {}
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)
351
352
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
358
359         ranks[row.game_type_cd] = rank
360
361     return ranks;
362
363
364 def get_elos(player_id):
365     """
366     Provides a breakdown of the player's elos by game type.
367
368     Returns a dictionary of namedtuples with the following members:
369         - player_id
370         - game_type_cd
371         - games
372         - elo
373
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.
376     """
377     raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
378             order_by(PlayerElo.elo.desc()).all()
379
380     elos = {}
381     found_max_elo = False
382     for row in raw_elos:
383         if not found_max_elo:
384             elos['overall'] = row
385             found_max_elo = True
386
387         elos[row.game_type_cd] = row
388
389     return elos
390
391
392 def get_recent_games(player_id):
393     """
394     Provides a list of recent games.
395
396     Returns the full PlayerGameStat, Game, Server, Map
397     objects for all recent games.
398     """
399     RecentGame = namedtuple('RecentGame', ['player_stats', 'game', 'server', 'map'])
400
401     # recent games table, all data
402     recent_games = DBSession.query(PlayerGameStat, Game, Server, Map).\
403             filter(PlayerGameStat.player_id == player_id).\
404             filter(PlayerGameStat.game_id == Game.game_id).\
405             filter(Game.server_id == Server.server_id).\
406             filter(Game.map_id == Map.map_id).\
407             order_by(Game.game_id.desc())[0:10]
408
409     return [
410         RecentGame(player_stats=row.PlayerGameStat,
411             game=row.Game,
412             server=row.Server,
413             map=row.Map)
414         for row in recent_games ]
415
416
417 def get_recent_weapons(player_id):
418     """
419     Returns the weapons that have been used in the past 90 days
420     and also used in 5 games or more.
421     """
422     cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
423     recent_weapons = []
424     for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
425             filter(PlayerWeaponStat.player_id == player_id).\
426             filter(PlayerWeaponStat.create_dt > cutoff).\
427             group_by(PlayerWeaponStat.weapon_cd).\
428             having(func.count() > 4).\
429             all():
430                 recent_weapons.append(weapon[0])
431
432     return recent_weapons
433
434
435 def get_accuracy_stats(player_id, weapon_cd, games):
436     """
437     Provides accuracy for weapon_cd by player_id for the past N games.
438     """
439     # Reaching back 90 days should give us an accurate enough average
440     # We then multiply this out for the number of data points (games) to
441     # create parameters for a flot graph
442     try:
443         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
444                 func.sum(PlayerWeaponStat.fired)).\
445                 filter(PlayerWeaponStat.player_id == player_id).\
446                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
447                 one()
448
449         avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
450
451         # Determine the raw accuracy (hit, fired) numbers for $games games
452         # This is then enumerated to create parameters for a flot graph
453         raw_accs = DBSession.query(PlayerWeaponStat.game_id, 
454             PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
455                 filter(PlayerWeaponStat.player_id == player_id).\
456                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
457                 order_by(PlayerWeaponStat.game_id.desc()).\
458                 limit(games).\
459                 all()
460
461         # they come out in opposite order, so flip them in the right direction
462         raw_accs.reverse()
463
464         accs = []
465         for i in range(len(raw_accs)):
466             accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
467     except:
468         accs = []
469         avg = 0.0
470
471     return (avg, accs)
472
473
474 def get_damage_stats(player_id, weapon_cd, games):
475     """
476     Provides damage info for weapon_cd by player_id for the past N games.
477     """
478     try:
479         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
480                 func.sum(PlayerWeaponStat.hit)).\
481                 filter(PlayerWeaponStat.player_id == player_id).\
482                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
483                 one()
484
485         avg = round(float(raw_avg[0])/raw_avg[1], 2)
486
487         # Determine the damage efficiency (hit, fired) numbers for $games games
488         # This is then enumerated to create parameters for a flot graph
489         raw_dmgs = DBSession.query(PlayerWeaponStat.game_id, 
490             PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
491                 filter(PlayerWeaponStat.player_id == player_id).\
492                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
493                 order_by(PlayerWeaponStat.game_id.desc()).\
494                 limit(games).\
495                 all()
496
497         # they come out in opposite order, so flip them in the right direction
498         raw_dmgs.reverse()
499
500         dmgs = []
501         for i in range(len(raw_dmgs)):
502             # try to derive, unless we've hit nothing then set to 0!
503             try:
504                 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
505             except:
506                 dmg = 0.0
507
508             dmgs.append((raw_dmgs[i][0], dmg))
509     except Exception as e:
510         dmgs = []
511         avg = 0.0
512
513     return (avg, dmgs)
514
515
516 def player_info_data(request):
517     player_id = int(request.matchdict['id'])
518     if player_id <= 2:
519         player_id = -1;
520
521     try:
522         player = DBSession.query(Player).filter_by(player_id=player_id).\
523                 filter(Player.active_ind == True).one()
524
525         games_played   = get_games_played(player_id)
526         overall_stats  = get_overall_stats(player_id)
527         fav_maps       = get_fav_maps(player_id)
528         elos           = get_elos(player_id)
529         ranks          = get_ranks(player_id)
530         recent_games   = get_recent_games(player_id)
531         recent_weapons = get_recent_weapons(player_id)
532
533     except Exception as e:
534         player         = None
535         games_played   = None
536         overall_stats  = None
537         fav_maps       = None
538         elos           = None
539         ranks          = None
540         recent_games   = None
541         recent_weapons = []
542
543     return {'player':player,
544             'games_played':games_played,
545             'overall_stats':overall_stats,
546             'fav_maps':fav_maps,
547             'elos':elos,
548             'ranks':ranks,
549             'recent_games':recent_games,
550             'recent_weapons':recent_weapons
551             }
552
553
554 def player_info(request):
555     """
556     Provides detailed information on a specific player
557     """
558     return player_info_data(request)
559
560
561 def player_info_json(request):
562     """
563     Provides detailed information on a specific player. JSON.
564     """
565
566     # All player_info fields are converted into JSON-formattable dictionaries
567     player_info = player_info_data(request)    
568
569     player = player_info['player'].to_dict()
570
571     games_played = {}
572     for game in player_info['games_played']:
573         games_played[game.game_type_cd] = to_json(game)
574
575     overall_stats = {}
576     for gt,stats in player_info['overall_stats'].items():
577         overall_stats[gt] = to_json(stats)
578
579     elos = {}
580     for gt,elo in player_info['elos'].items():
581         elos[gt] = to_json(elo.to_dict())
582
583     ranks = {}
584     for gt,rank in player_info['ranks'].items():
585         ranks[gt] = to_json(rank)
586
587     fav_maps = {}
588     for gt,mapinfo in player_info['fav_maps'].items():
589         fav_maps[gt] = to_json(mapinfo)
590
591     recent_games = []
592     for game in player_info['recent_games']:
593         recent_games.append(to_json(game))
594
595     #recent_weapons = player_info['recent_weapons']
596
597     return [{
598         'player':           player,
599         'games_played':     games_played,
600         'overall_stats':    overall_stats,
601         'fav_maps':         fav_maps,
602         'elos':             elos,
603         'ranks':            ranks,
604         'recent_games':     recent_games,
605     #    'recent_weapons':   recent_weapons,
606         'recent_weapons':   ['not implemented'],
607     }]
608     #return [{'status':'not implemented'}]
609
610
611 def player_game_index_data(request):
612     RecentGame = namedtuple('RecentGame', ['game_id', 'game_type_cd', 'winner',
613         'game_create_dt', 'game_epoch', 'game_fuzzy', 'server_id',
614         'server_name', 'map_id', 'map_name', 'team', 'rank', 'elo_delta'])
615
616     player_id = request.matchdict['player_id']
617
618     if request.params.has_key('page'):
619         current_page = request.params['page']
620     else:
621         current_page = 1
622
623     try:
624         player = DBSession.query(Player).filter_by(player_id=player_id).\
625                 filter(Player.active_ind == True).one()
626
627         games_q = DBSession.query(Game.game_id, Game.game_type_cd, Game.winner,
628                 Game.create_dt, Server.server_id,
629                 Server.name.label('server_name'), Map.map_id,
630                 Map.name.label('map_name'), PlayerGameStat.team,
631                 PlayerGameStat.rank, PlayerGameStat.elo_delta).\
632             filter(PlayerGameStat.game_id == Game.game_id).\
633             filter(PlayerGameStat.player_id == player_id).\
634             filter(Game.server_id == Server.server_id).\
635             filter(Game.map_id == Map.map_id).\
636             order_by(Game.game_id.desc())
637
638         games = Page(games_q, current_page, items_per_page=10, url=page_url)
639
640         # replace the items in the canned pagination class with more rich ones
641         games.items = [RecentGame(
642             game_id        = row.game_id,
643             game_type_cd   = row.game_type_cd,
644             winner         = row.winner,
645             game_create_dt = row.create_dt,
646             game_epoch     = timegm(row.create_dt.timetuple()),
647             game_fuzzy     = pretty_date(row.create_dt),
648             server_id      = row.server_id,
649             server_name    = row.server_name,
650             map_id         = row.map_id,
651             map_name       = row.map_name,
652             team           = row.team,
653             rank           = row.rank,
654             elo_delta      = row.elo_delta
655         ) for row in games.items]
656
657     except Exception as e:
658         player = None
659         games = None
660
661     return {
662             'player_id':player.player_id,
663             'player':player,
664             'games':games,
665            }
666
667
668 def player_game_index(request):
669     """
670     Provides an index of the games in which a particular
671     player was involved. This is ordered by game_id, with
672     the most recent game_ids first. Paginated.
673     """
674     return player_game_index_data(request)
675
676
677 def player_game_index_json(request):
678     """
679     Provides an index of the games in which a particular
680     player was involved. This is ordered by game_id, with
681     the most recent game_ids first. Paginated. JSON.
682     """
683     return [{'status':'not implemented'}]
684
685
686 def player_accuracy_data(request):
687     player_id = request.matchdict['id']
688     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
689     weapon_cd = 'nex'
690     games = 20
691
692     if request.params.has_key('weapon'):
693         if request.params['weapon'] in allowed_weapons:
694             weapon_cd = request.params['weapon']
695
696     if request.params.has_key('games'):
697         try:
698             games = request.params['games']
699
700             if games < 0:
701                 games = 20
702             if games > 50:
703                 games = 50
704         except:
705             games = 20
706
707     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
708
709     # if we don't have enough data for the given weapon
710     if len(accs) < games:
711         games = len(accs)
712
713     return {
714             'player_id':player_id, 
715             'player_url':request.route_url('player_info', id=player_id), 
716             'weapon':weapon_cd, 
717             'games':games, 
718             'avg':avg, 
719             'accs':accs
720             }
721
722
723 def player_accuracy(request):
724     """
725     Provides the accuracy for the given weapon. (JSON only)
726     """
727     return player_accuracy_data(request)
728
729
730 def player_accuracy_json(request):
731     """
732     Provides a JSON response representing the accuracy for the given weapon.
733
734     Parameters:
735        weapon = which weapon to display accuracy for. Valid values are 'nex',
736                 'shotgun', 'uzi', and 'minstanex'.
737        games = over how many games to display accuracy. Can be up to 50.
738     """
739     return player_accuracy_data(request)
740
741
742 def player_damage_data(request):
743     player_id = request.matchdict['id']
744     allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
745             'rocketlauncher', 'laser']
746     weapon_cd = 'rocketlauncher'
747     games = 20
748
749     if request.params.has_key('weapon'):
750         if request.params['weapon'] in allowed_weapons:
751             weapon_cd = request.params['weapon']
752
753     if request.params.has_key('games'):
754         try:
755             games = request.params['games']
756
757             if games < 0:
758                 games = 20
759             if games > 50:
760                 games = 50
761         except:
762             games = 20
763
764     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
765
766     # if we don't have enough data for the given weapon
767     if len(dmgs) < games:
768         games = len(dmgs)
769
770     return {
771             'player_id':player_id, 
772             'player_url':request.route_url('player_info', id=player_id), 
773             'weapon':weapon_cd, 
774             'games':games, 
775             'avg':avg, 
776             'dmgs':dmgs
777             }
778
779
780 def player_damage_json(request):
781     """
782     Provides a JSON response representing the damage for the given weapon.
783
784     Parameters:
785        weapon = which weapon to display damage for. Valid values are
786          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
787          'laser'.
788        games = over how many games to display damage. Can be up to 50.
789     """
790     return player_damage_data(request)
791
792
793 def player_hashkey_info_data(request):
794     hashkey = request.matchdict['hashkey']
795     try:
796         player = DBSession.query(Player).\
797                 filter(Player.player_id == Hashkey.player_id).\
798                 filter(Player.active_ind == True).\
799                 filter(Hashkey.hashkey == hashkey).one()
800
801         games_played   = get_games_played(player.player_id)
802         overall_stats  = get_overall_stats(player.player_id)
803         fav_maps       = get_fav_maps(player.player_id)
804         elos           = get_elos(player.player_id)
805         ranks          = get_ranks(player.player_id)
806
807     except Exception as e:
808         raise e
809         player         = None
810         games_played   = None
811         overall_stats  = None
812         fav_maps       = None
813         elos           = None
814         ranks          = None
815
816     return {'player':player,
817             'games_played':games_played,
818             'overall_stats':overall_stats,
819             'fav_maps':fav_maps,
820             'elos':elos,
821             'ranks':ranks,
822             }
823
824
825 def player_hashkey_info_json(request):
826     """
827     Provides detailed information on a specific player. JSON.
828     """
829
830     # All player_info fields are converted into JSON-formattable dictionaries
831     player_info = player_hashkey_info_data(request)
832
833     player = player_info['player'].to_dict()
834
835     games_played = {}
836     for game in player_info['games_played']:
837         games_played[game.game_type_cd] = to_json(game)
838
839     overall_stats = {}
840     for gt,stats in player_info['overall_stats'].items():
841         overall_stats[gt] = to_json(stats)
842
843     elos = {}
844     for gt,elo in player_info['elos'].items():
845         elos[gt] = to_json(elo.to_dict())
846
847     ranks = {}
848     for gt,rank in player_info['ranks'].items():
849         ranks[gt] = to_json(rank)
850
851     fav_maps = {}
852     for gt,mapinfo in player_info['fav_maps'].items():
853         fav_maps[gt] = to_json(mapinfo)
854
855     return [{
856         'version':          1,
857         'player':           player,
858         'games_played':     games_played,
859         'overall_stats':    overall_stats,
860         'fav_maps':         fav_maps,
861         'elos':             elos,
862         'ranks':            ranks,
863     }]
864
865
866 def player_elo_info_data(request):
867     """
868     Provides elo information on a specific player. Raw data is returned.
869     """
870     hashkey = request.matchdict['hashkey']
871     try:
872         player = DBSession.query(Player).\
873                 filter(Player.player_id == Hashkey.player_id).\
874                 filter(Player.active_ind == True).\
875                 filter(Hashkey.hashkey == hashkey).one()
876
877         elos = get_elos(player.player_id)
878
879     except Exception as e:
880         log.debug(e)
881         raise pyramid.httpexceptions.HTTPNotFound
882
883     return {'elos':elos}
884
885
886 def player_elo_info_json(request):
887     """
888     Provides elo information on a specific player. JSON.
889     """
890     elo_info = player_elo_info_data(request)
891
892     elos = {}
893     for gt, elo in elo_info['elos'].items():
894         elos[gt] = to_json(elo.to_dict())
895
896     return [{
897         'version':          1,
898         'elos':             elos,
899     }]