Exemplo n.º 1
0
def Footer():
    return List(
        br(), link('home', PlayerMenu), ' ', link('logout', logout), br(),
        'Switch: ',
        ListJoin(
            Map(lambda player: link(player['name'], loginAs, player['name']),
                player), ' '))
Exemplo n.º 2
0
def multi(request, db):
    gs = dbselectors.get('game', db)
    gs.flags_none()
    gs.weakflags(["server"], True)
    games = gs.multi()
    pager = web.Pager(request, onpagecount, reversed(list(games.keys())))
    table = web.Table(
        ["ID", "Mode", "Mutators", "Server",
            "Map", "Duration", "Played"])
    for gid in pager.list():
        game = games[gid]
        with table.tr as tr:
            tr(web.link('/game/', gid, "Game #%d" % gid))
            tr(web.link('/mode/', game["mode"],
                redeclipse(game).modeimg(game["mode"])))
            tr(redeclipse(game).mutslist(game, True) or '-')
            row = db.execute(
                "SELECT version FROM game_servers WHERE game = %d" % gid
                ).fetchone()
            version = row[0]
            tr("%s [%s]" % (
                web.link('/server/', game["server"], game["server"]),
                version))
            tr(web.link('/map/', game["map"], game["map"], True))
            tr(timeutils.durstr(round(game["timeplayed"])))
            tr(timeutils.agohtml(game["time"]))
    ret = """
    <div class="center display-table">
        <h2>Games</h2>
        <h3>{gamenum} Recorded</h3>
        {table}
        {pages}
    </div>
    """.format(table=table.html(), pages=pager.html(), gamenum=len(games))
    return web.page(ret, title="Games")
Exemplo n.º 3
0
    def mutslist(self, game, html=False, short=False):
        muts = []

        def chunks(l, n):
            for i in range(0, len(l), n):
                yield l[i:i + n]

        for m in self.basemuts:
            if (game["mutators"] & self.basemuts[m]):
                muts.append(m)

        if game['mode'] in self.gspmuts:
            for m in self.gspmuts[game['mode']]:
                if (game["mutators"] & self.gspmuts[game['mode']][m]):
                    muts.append(m)
        if html:
            if short:
                out = []
                for m in muts:
                    out.append(web.link('/mut/', m, m))
                return '-'.join(out)
            outl = chunks([web.link('/mut/', m, m) for m in muts], 5)
            htmll = []
            for chunk in outl:
                htmll.append(" ".join(chunk))
            return "<br>".join(htmll)
        return muts
Exemplo n.º 4
0
def multi(request, db):
    mapselector = dbselectors.get('map', db)
    mapselector.flags_none()
    mapselector.weakflags(["race"], True)

    gameselector = dbselectors.get('game', db)
    gameselector.flags_none()

    maps = mapselector.multi()
    pager = web.Pager(request, onpagecount,
        sorted(maps, key=lambda x: -maps[x]["games"][-1]))
    maptable = web.Table(["Name", "Games",
        "First Game", "Latest Game", '<a href="/racemaps">Best Race Time</a>'])
    for mapname in pager.list():
        gmap = maps[mapname]
        firstgame = gameselector.single(gmap["games"][0])
        latestgame = gameselector.single(gmap["games"][-1])
        with maptable.tr as tr:
            tr(web.link('/map/', gmap["name"], gmap["name"], True))
            tr(len(gmap["games"]))
            tr("%s: %s" % (
                web.link('/game/', firstgame['id'], "#%d" % firstgame["id"]),
                timeutils.agohtml(firstgame["time"])
                ))
            tr("%s: %s" % (
                web.link('/game/', latestgame['id'], "#%d" % latestgame["id"]),
                timeutils.agohtml(latestgame["time"])
                ))
            if gmap["toprace"]["time"]:
                tr("%s by %s" % (timeutils.durstr(
                    gmap["toprace"]["time"] / 1000, dec=True, full=True),
                    web.linkif("/player/",
                        gmap["toprace"]["gameplayer"]["handle"],
                        gmap["toprace"]["gameplayer"]["handle"]
                        or gmap["toprace"]["gameplayer"]["name"])
                        )
                    )
            else:
                tr()
    ret = """
    <div class="center">
        <h2>Maps</h2>
        <div class='display-table'>
            {maptable}
            {pages}
        </div>
    </div>
    """.format(maptable=maptable.html(), pages=pager.html())
    return web.page(ret, title="Maps")
Exemplo n.º 5
0
def single(request, db, specific):
    ret = ""
    serverselector = dbselectors.get('server', db)
    serverselector.flags_none()
    serverselector.weakflags(["games"], True)
    server = serverselector.single(specific)
    if utils.sok(server):
        # Game List
        pager = web.Pager(request, onpagecount, reversed(server["games"]))
        recentgames = web.Table(
            ["ID", "Mode", "Mutators", "Map", "Duration", "Played"])
        gs = dbselectors.get('game', db)
        gs.flags_none()
        firstgame = gs.single(server["games"][0])
        for gid in pager.list():
            game = gs.single(gid)
            with recentgames.tr as tr:
                tr(web.link("/game/", gid, "Game #%d" % gid))
                tr(web.link("/mode/", game["mode"],
                    redeclipse(game).modeimg(game["mode"])))
                tr(redeclipse(game).mutslist(game, True) or '-')
                tr(web.link("/map/", game["map"], game["map"], True))
                tr(timeutils.durstr(round(game["timeplayed"])))
                tr(timeutils.agohtml(game["time"]))

        ret += """
        <div class="center">
            <h2>{server[desc]}</h2>
            <h3>{server[handle]} <i>[{server[authflags]}]</i>:
                Version {server[version]}</h3>
            <a href="redeclipse://{server[host]}:{server[port]}">
            {server[host]}:{server[port]}</a><br>
            {servergames} games recorded.<br>
            First Recorded: {fgtime} with
            <a href="/game/{fgid}">Game #{fgid}</a>.<br>
            <div class='display-table'>
                <h3>Recent Games</h3>
                {recentgames}
                {pages}
            </div>
        </div>
        """.format(server=server, recentgames=recentgames.html(),
            servergames=len(server["games"]),
            fgtime=timeutils.agohtml(firstgame["time"]), fgid=firstgame["id"],
            pages=pager.html())
    else:
        ret = "<div class='center'><h2>No such server.</h2></div>"
    return web.page(ret, title="Server %s" % specific)
Exemplo n.º 6
0
def inProgressGamesList(player_id):
    #games_ready_to_go = Difference(games_invited_to(player_id), games_with_unaccepted_invitations)

    # This does not check if the game is done
    games_ready_to_go = games_of_player(player_id)
    return List(
        'Games in progress: ',
        ListJoin(
            Map(lambda game_id: link(game_id, goToGame, game_id, player_id),
                games_ready_to_go), ' '))
Exemplo n.º 7
0
def invitationList(player_id):
    return List(
        'Pending invitations: ',
        ListJoin(
            Map(
                lambda invitation: link(invitation['game_id'],
                                        askToAcceptInvitation, invitation),
                Where(
                    invitation,
                    Pand(Feq('player_id', player_id), Feq('accepted',
                                                          False)))), ''))
Exemplo n.º 8
0
def single(request, db, specific):
    ps = dbselectors.get('player', db)
    ps.flags_none()
    ps.weakflags(['games'], True)
    gs = dbselectors.get('game', db)
    gs.flags_none()
    gs.weakflags(['players'], True)
    player = ps.single(specific)
    if utils.sok(player):
        table = web.Table(["Game", "Mode", "Mutators",
            "Map", "Time", "Played As", "Score", "Frags", "Deaths"])
        pager = web.Pager(request, onpagecount, reversed(player["games"]))
        for gid in pager.list():
            game = gs.single(gid)
            entry = [p for p in list(game["players"].values())
            if p["handle"] == player["handle"]][0]
            with table.tr as tr:
                tr(web.link('/game/', gid, "Game #%d" % gid))
                tr(web.link('/mode/', game["mode"],
                    redeclipse(game).modeimg(game["mode"])))
                tr(redeclipse(game).mutslist(game, True) or '-')
                tr(web.link("/map/", game["map"], game["map"], True))
                tr(timeutils.agohtml(game["time"]))
                tr(cgi.escape(entry["name"]))
                tr(redeclipse(game).scorestr(game, entry["score"]))
                tr(entry["frags"])
                tr(entry["deaths"])

        ret = """
        <div class="center">
            <h2><a href="/player/{player[handle]}">
            {player[handle]}</a>: Games</h2>
            <div class='display-table'>
                {table}
                {pages}
            </div>
        </div>
        """.format(player=player, table=table.html(), pages=pager.html())
    else:
        ret = "<div class='center'><h2>No such player.</h2></div>"
    return web.page(ret, title="%s: Games" % specific)
Exemplo n.º 9
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(list(self.tabletitle))
     if pager is not None:
         indexes = pager.list()
     else:
         indexes = data[:limit]
     for p in indexes:
         with table.tr as tr:
             tr(web.link('/player/', p[0], p[0]))
             tr(p[1])
     return table
Exemplo n.º 10
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(list(self.tabletitle))
     if pager is not None:
         indexes = pager.list()
     else:
         indexes = data[:limit]
     for p in indexes:
         with table.tr as tr:
             tr(web.link("/player/", p[0], p[0]))
             tr("%d [%d/%d]" % (p[1][0] / max(1, p[1][1]), p[1][0], p[1][1]))
     return table
Exemplo n.º 11
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(["Name", "Games"])
     if pager is not None:
         indexes = pager.list()
     else:
         indexes = sorted(data, key=lambda x: -data[x])[:limit]
     for m in indexes:
         with table.tr as tr:
             tr(web.link("/map/", m, m))
             tr(data[m])
     return table
Exemplo n.º 12
0
def multi(request, db):
    playerselector = dbselectors.get('player', db)
    playerselector.flags_none()
    playerselector.weakflags(['games'], True)

    gameselector = dbselectors.get('game', db)
    gameselector.flags_none()

    players = playerselector.multi()
    pager = web.Pager(request, onpagecount,
        sorted(players, key=lambda x: -players[x]["games"][-1]))
    playertable = web.Table(
        ["Name", "Handle", "Games", "First Game", "Latest Game"])
    for handle in pager.list():
        player = players[handle]
        firstgame = gameselector.single(player["games"][0])
        latestgame = gameselector.single(player["games"][-1])
        with playertable.tr as tr:
            tr(web.linkif('/player/', player["handle"], player["name"], True))
            tr(web.linkif('/player/', player["handle"], player["handle"], True))
            tr(len(player["games"]))
            tr("%s: %s" % (
                web.link('/game/', firstgame['id'], "#%d" % firstgame["id"]),
                timeutils.agohtml(firstgame["time"])
                ))
            tr("%s: %s" % (
                web.link('/game/', latestgame['id'], "#%d" % latestgame["id"]),
                timeutils.agohtml(latestgame["time"])
                ))
    ret = """
    <div class="center">
        <h2>Players</h2>
        <div class='display-table'>
            {playertable}
            {pages}
        </div>
    </div>
    """.format(playertable=playertable.html(), pages=pager.html())
    return web.page(ret, title="Players")
Exemplo n.º 13
0
def single(request, db, specific):
    ret = ""
    mutselector = dbselectors.get('mut', db)
    mutselector.flags_none()
    mut = mutselector.single(specific)
    if utils.sok(mut):
        # Game List
        pager = web.Pager(request, onpagecount, reversed(mut["games"]))
        recentgames = web.Table(
            ["ID", "Mode", "Mutators", "Map", "Duration", "Played"])
        gs = dbselectors.get('game', db)
        gs.flags_none()
        for gid in pager.list():
            game = gs.single(gid)
            with recentgames.tr as tr:
                tr(web.link("/game/", gid, "Game #%d" % gid))
                tr(web.link("/mode/", game["mode"],
                    redeclipse(game).modeimg(game["mode"])))
                tr(redeclipse(game).mutslist(game, True) or '-')
                tr(web.link("/map/", game["map"], game["map"], True))
                tr(timeutils.durstr(round(game["timeplayed"])))
                tr(timeutils.agohtml(game["time"]))

        ret += """
        <div class="center">
            <h2>{mut[id]}</h2>
            <div class='display-table'>
                <h3>Recent Games</h3>
                {recentgames}
                {pages}
            </div>
        </div>
        """.format(mut=mut,
            recentgames=recentgames.html(),
            pages=pager.html())
    else:
        ret = "<div class='center'><h2>No such mutator.</h2></div>"
    return web.page(ret, title="Mutator %s" % specific)
Exemplo n.º 14
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(["Name", "Games"])
     if pager is not None:
         indexes = pager.list()
     else:
         indexes = sorted(data, key=lambda x: -data[x])[:limit]
     ss = dbselectors.get('server', self.db)
     ss.flags_none()
     for s in indexes:
         with table.tr as tr:
             tr(web.link('/server/', s, ss.single(s)["desc"]))
             tr(data[s])
     return table
Exemplo n.º 15
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(["Mode", "Games"])
     if pager is not None:
         indexes = pager.list()
     else:
         if limit is not None:
             indexes = sorted(data, key=lambda x: -data[x])[:limit]
         else:
             indexes = sorted(data, key=lambda x: -data[x])
     for m in indexes:
         with table.tr as tr:
             tr(web.link('/mode/', m, redeclipse().modeimg(m)))
             tr(data[m])
     return table
Exemplo n.º 16
0
def weaponstable(weapons, totalwielded, order, games=None, version=None):
    title = "Weapons"
    if len(order) == 1:
        title = weapons[order[0]]["name"].capitalize()
    if games is not None:
        title = "%s: Last %d games" % (title, games)
    table = web.Table(
        ["Weapon", "Loadout", "Wielded",
            '<abbr title="Damage Per Minute Wielded">DPM</abbr>',
            '<abbr title="Frags Per Minute Wielded">FPM</abbr>'],
                title, 'display-table small-table')
    for weapon in order:
        with table.tr as tr:
            weapon = weapons[weapon]
            if weapon["timeloadout"] is None:
                continue
            weap = weapon["name"]
            tr(web.link("/weapon/", weap,
                '%s %s' % (redeclipse().weaponimg(weap), weap)))
            tr("%d%%" % (
                weapon["timeloadout"] / max(1, totalwielded) * 100))
            nw = redeclipse(version).notwielded
            if (weap + '1') in nw and (weap + '2') in nw:
                tr("-")
            else:
                tr("%d%%" % (
                    weapon["timewielded"] / max(1, totalwielded) * 100))
            psdiv = max(weapon["timeloadout"]
                if (weap + '1') in nw else weapon["timewielded"], 1) / 60
            psdiv2 = max(weapon["timeloadout"]
                if (weap + '2') in nw else weapon["timewielded"], 1) / 60
            tr("<span class='explain' title='%d %d'>%d</span>" % (
                weapon["damage1"] / psdiv,
                weapon["damage2"] / psdiv2,
                weapon["damage1"] / psdiv + weapon["damage2"] / psdiv2))
            tr("<span class='explain' title='%.1f %.1f'>%.1f</span></td>" % (
                round(weapon["frags1"] / psdiv, 1),
                round(weapon["frags2"] / psdiv2, 1),
                round(weapon["frags1"] / psdiv + weapon["frags2"] / psdiv2, 1)
                ))
    return table
Exemplo n.º 17
0
 def table(self, limit=5, pager=None):
     data = self.get()
     table = web.Table(['<a href="/ranks/modes/%d">Mode</a>' % self.days,
         '<a href="/ranks/muts/%d">Mutators</a>' % self.days, "Games"])
     if pager is not None:
         indexes = pager.list()
     else:
         if limit is not None:
             indexes = sorted(data, key=lambda x: -data[x])[:limit]
         else:
             indexes = sorted(data, key=lambda x: -data[x])
     for m in indexes:
         with table.tr as tr:
             fakegame = {
                 "mode": m[0],
                 "mutators": m[1],
                 "version": m[2],
             }
             tr(web.link('/mode/', m[0],
                 redeclipse(fakegame).modeimg(m[0])))
             tr(redeclipse(fakegame).mutslist(
                 fakegame, True, True) or '-')
             tr(data[m])
     return table
Exemplo n.º 18
0
def AddPlayersToGame(game_id):
    return List(
        'Add players to game ', game_id, br(), 'Already added:', br(),
        ListJoin(players_invited_to_game(game_id), br()),
        mkform(AddPlayersToGameRcv, {'player_name': ''}, {'game_id': game_id}),
        link('done', DoneAddingPlayersToGame, game_id), Footer())
Exemplo n.º 19
0
def PlayerMenu():
    return List(Header(), link('create game', CreateGame), br(),
                invitationList(currentPlayerId()), br(),
                inProgressGamesList(currentPlayerId()), br(), Footer())
Exemplo n.º 20
0
def offerDrawCard(game_id, player_id):
    return List('Time to draw a card. ',
                link('Draw Card', drawCard, game_id, player_id), br())
Exemplo n.º 21
0
def single(request, db, specific):
    ret = ""
    mapselector = dbselectors.get('map', db)
    mapselector.flags_none()
    mapselector.weakflags(["race"], True)
    gmap = mapselector.single(specific)
    if utils.sok(gmap):
        # Game List
        pager = web.Pager(request, onpagecount, reversed(gmap["games"]))
        recentgames = web.Table(
            ["ID", "Mode", "Mutators", "Duration", "Played"])
        gs = dbselectors.get('game', db)
        gs.flags_none()
        for gid in pager.list():
            game = gs.single(gid)
            with recentgames.tr as tr:
                tr(web.link("/game/", gid, "Game #%d" % gid))
                tr(web.link("/mode/", game["mode"],
                    redeclipse(game).modeimg(game["mode"])))
                tr(redeclipse(game).mutslist(game, True) or '-')
                tr(timeutils.durstr(round(game["timeplayed"])))
                tr(timeutils.agohtml(game["time"]))

        # Race Times
        racetable = web.Table(["Time", "Player", "Handle", "Game", "When"])
        for race in gmap["topraces"][:3]:
            with racetable.tr as tr:
                tr(timeutils.durstr(race["time"] / 1000, dec=True, full=True))
                tr(web.linkif('/player/',
                    race["gameplayer"]["handle"], race["gameplayer"]["name"]))
                tr(web.linkif('/player/',
                    race["gameplayer"]["handle"],
                    race["gameplayer"]["handle"] or '-'))
                tr(web.link('/game/', race["game"]["id"],
                    "Game #%d" % race["game"]["id"]))
                tr(timeutils.agohtml(race["game"]["time"]))
        racetimes = """
        <div class='display-table small-table'>
            <h3>Top Race Times</h3>
            %s
        </div>
        """ % racetable.html()

        eracetable = web.Table(["Time", "Player", "Handle", "Game", "When"])
        for race in gmap["toperaces"][:3]:
            with eracetable.tr as tr:
                tr(timeutils.durstr(race["time"] / 1000, dec=True, full=True))
                tr(web.linkif('/player/',
                    race["gameplayer"]["handle"], race["gameplayer"]["name"]))
                tr(web.linkif('/player/',
                    race["gameplayer"]["handle"],
                    race["gameplayer"]["handle"] or '-'))
                tr(web.link('/game/', race["game"]["id"],
                    "Game #%d" % race["game"]["id"]))
                tr(timeutils.agohtml(race["game"]["time"]))
        eracetimes = """
        <div class='display-table small-table'>
            <h3>Top Endurance Race Times</h3>
            %s
        </div>
        """ % eracetable.html()

        ret += """
        <div class="center">
            <h2>{map[name]}</h2>
            {racetimes}
            {eracetimes}
            <div class='display-table'>
                <h3>Recent Games</h3>
                {recentgames}
                {pages}
            </div>
        </div>
        """.format(map=gmap,
            recentgames=recentgames.html(),
            racetimes=racetimes if gmap["toprace"]["time"] else '',
            eracetimes=eracetimes if gmap["toperace"]["time"] else '',
            pages=pager.html())
    else:
        ret = "<div class='center'><h2>No such map.</h2></div>"
    return web.page(ret, title="Map %s" % specific)
Exemplo n.º 22
0
def single(request, db, specific):
    playerselector = dbselectors.get('player', db, {'recentsums': [-1]})
    playerselector.flags_none()
    playerselector.weakflags(
        ['games', 'damage', 'recentgames', 'recentsums', 'weapons'], True)

    recentplayerselector = dbselectors.get('player', db,
        {'recentsums': [recentlimit]})
    recentplayerselector.flags_none()
    recentplayerselector.weakflags(
        ['games', 'damage', 'recentsums', 'weapons'], True)

    gameselector = dbselectors.get('game', db)
    gameselector.flags_none()

    player = playerselector.single(specific)
    recentplayer = recentplayerselector.single(specific)
    if utils.sok(player) and utils.sok(recentplayer):
        #Top map
        topmap = "-"
        maps = {}
        for row in db.execute('''SELECT map FROM games
            WHERE id IN (SELECT game
            FROM game_players WHERE handle = ?
            ORDER by ROWID DESC LIMIT %d)''' % recentlimit,
                (player["handle"],)):
                    if row[0] not in maps:
                        maps[row[0]] = 0
                    maps[row[0]] += 1
        if maps:
            t = sorted(maps, key=lambda x: -maps[x])[0]
            topmap = web.link('/map/', t, t)
        # Play time
        timeplayed = timeutils.durstr(player["recent"]["timeactive"],
            skip="s", skiplow=False, full=True)
        #DPM
        try:
            dpm = "%d" % (round(player["recent"]["damage"]
                / (player["recent"]["timealive"] / 60)))
        except TypeError:
            dpm = "-"
        #Frag ratio
        try:
            fratio = "%.2f [%d / %d]" % ((player["recent"]["frags"] /
                max(1, player["recent"]["deaths"])),
                    player["recent"]["frags"],
                    player["recent"]["deaths"])
        except TypeError:
            fratio = "-"
        #Recent Games
        gamestable = web.Table(["Game", "Mode", "Mutators",
            "Map", "Time", "Played As", "Score", "Frags", "Deaths"])
        for gid in sorted(
            list(player["recentgames"].keys()), reverse=True)[:5]:
                game = player["recentgames"][gid]
                entry = game["player"]
                with gamestable.tr as tr:
                    tr(web.link('/game/', gid, "Game #%d" % gid))
                    tr(web.link('/mode/', game["mode"],
                        redeclipse(game).modeimg(game["mode"])))
                    tr(redeclipse(game).mutslist(game, True) or '-')
                    tr(web.link("/map/", game["map"], game["map"], True))
                    tr(timeutils.agohtml(game["time"]))
                    tr(cgi.escape(entry["name"]))
                    tr(redeclipse(game).scorestr(game, entry["score"]))
                    tr(entry["frags"])
                    tr(entry["deaths"])
        #Weapons
        totalwielded = sum([w['timewielded']
            for w in list(recentplayer['recent']['weapons'].values())
            if w['timewielded'] is not None])
        weaponstable = web.displays.weaponstable(
            recentplayer['recent']['weapons'],
            totalwielded, redeclipse().weaponlist)
        ret = """
        <div class="center">
            <h2>{player[name]}</h2>
            <h3>{player[handle]}</h3>
            <div class="colcontainer">
                <div class="leftcol">
                    First appeared: {firstago}<br>
                    Last appeared: {lastago}<br>
                </div>
                <div class="rightcol">
                    Most played map: {topmap}<br>
                    Playing time: {timeplayed}<br>
                </div>
            </div>
            <div style="clear: both;"></div>
            <h3>Last {recentnum} Games</h3>
            Frag Ratio: {fratio}<br>
            DPM: {dpm}<br>
            <div class='display-table'>
                {games}
                <h5 style="text-align: left;">
                <a href="/playergames/{player[handle]}">
                All Games...</a></h5>
            </div>
            <div class='display-table small-table'>
                <h3>Weapon Statistics</h3>
                {weapons}
            </div>
        </div>
        """.format(
            player=player,
            firstago=web.link("/game/", player["games"][0],
                timeutils.agohtml(
                    gameselector.single(player["games"][0])["time"])),
            lastago=web.link("/game/", player["games"][-1],
                timeutils.agohtml(
                    gameselector.single(player["games"][-1])["time"])),
            topmap=topmap,
            timeplayed=timeplayed,
            dpm=dpm,
            fratio=fratio,
            games=gamestable.html(),
            weapons=weaponstable.html(),
            recentnum=recentlimit,
            )
    else:
        ret = "<div class='center'><h2>No such player.</h2></div>"
    return web.page(ret, title="Player %s" % specific)
Exemplo n.º 23
0
def askToAcceptInvitation(invitation):
    return List(Header(), 'Accept invitation from ',
                playerName(Deref(invitation, 'inviter')), ' to game ',
                Deref(invitation, 'game_id'), '? ',
                link('Yes', acceptInvitation, invitation), ' ',
                link('No', PlayerMenu), br(), Footer())
Exemplo n.º 24
0
def single(request, db, specific):
    gs = dbselectors.get('game', db)
    gs.flags_none()
    gs.weakflags(["server", "teams",
        "affinities", "rounds", "players", "playerdamage", "weapons"], True)
    ss = dbselectors.get('server', db)
    ss.flags_none()

    game = gs.single(specific)
    ret = ""
    if utils.sok(game):
        server = ss.single(game["server"])
        # Display the server's desc & version from this game.
        serverrow = db.execute(
            """SELECT version,desc,host,port
            FROM game_servers WHERE game = %d""" % game["id"]
            ).fetchone()
        server["version"] = serverrow[0]
        server["desc"] = cgi.escape(serverrow[1]) or cgi.escape(
            "%s:%d" % (serverrow[2], serverrow[3]))

        playerstable = web.Table(
            ["Name", "Score", "Handle", "Alive", "Frags", "Deaths"],
            "Players", "display-table")
        for player in sorted(
            list(game["players"].values()), key=lambda x: (
                redeclipse(game).scorenum(game, x["score"]))):
                with playerstable.tr as tr:
                    tr(web.linkif('/player/', player["handle"], player["name"]))
                    tr(redeclipse(game).scorestr(game, player["score"]))
                    tr(web.linkif('/player/',
                        player["handle"], player["handle"]))
                    tr(timeutils.durstr(player["timealive"]))
                    tr(player["frags"])
                    tr(player["deaths"])

        teamstable = None
        teamlist = {}
        if len(game["teams"]) > 1:
            teamstable = web.Table(
                ["Name", "Score"],
                "Teams", "display-table small-table")
            # Sort depending on score, counting race times
            for team in sorted(sorted(game["teams"],
                key=lambda x: game["teams"][x]["score"] * (
                    1 if
                    game["mode"] == redeclipse(game).modes["race"]
                    and (game["mutators"] & redeclipse(game).mutators["timed"])
                    else -1
                    )), key=lambda x: game["teams"][x]["score"] == 0):
                        team = game["teams"][team]
                        teamlist[team["team"]] = team
                        with teamstable.tr as tr:
                            tr("%s %s" % (
                                redeclipse(game).teamimg(team["team"]),
                                cgi.escape(team["name"])
                                ))
                            tr(redeclipse(game).scorestr(game, team["score"]))

        ffarounds = web.Table(["Round", "Winner", "Versus"],
            "Rounds", "display-table small-table")
        if "ffarounds" in game:
            donerounds = []
            for ffaround in sorted(game["ffarounds"], key=lambda x: x["round"]):
                if ffaround["round"] in donerounds:
                    continue
                haswinner = False
                for ffaround_s in game["ffarounds"]:
                    if (ffaround_s["round"] == ffaround["round"]
                    and ffaround_s["winner"]):
                        haswinner = True
                        break
                versuslist = []
                for ffaround_s in game["ffarounds"]:
                    if (ffaround_s["round"] == ffaround["round"]
                    and not ffaround_s["winner"]):
                        versuslist.append(web.linkif(
                            "/player/", ffaround_s["playerhandle"],
                            game["players"][ffaround_s["player"]]["name"]))
                with ffarounds.tr as tr:
                    if haswinner and ffaround["winner"]:
                            tr(ffaround["round"])
                            tr(web.linkif(
                                "/player/", ffaround["playerhandle"],
                                game["players"][ffaround["player"]]["name"]))
                            if versuslist:
                                tr(", ".join(versuslist))
                            else:
                                tr("<i>AI</i>")
                    elif not haswinner:
                        donerounds.append(ffaround["round"])
                        if len(versuslist) == 1:
                            tr(ffaround["round"])
                            tr('<i>AI</i>')
                            tr(", ".join(versuslist))
                        else:
                            tr(ffaround["round"])
                            tr('<i>Epic fail!</i>')
                            tr(", ".join(versuslist))

        affinitiestable = None
        if "captures" in game:
            affinitiestable = web.Table(
                ["Player", "Capturing Team", "Captured Flag"],
                "Flag Captures", "display-table"
                )
            for capture in game["captures"]:
                with affinitiestable.tr as tr:
                    tr(web.linkif('/player/', capture["playerhandle"],
                        game["players"][capture["player"]]["name"]))
                    tr(cgi.escape(teamlist[capture["capturing"]]["name"]))
                    tr(cgi.escape(teamlist[capture["captured"]]["name"]))
        elif "bombings" in game:
            affinitiestable = web.Table(
                ["Player", "Bombing Team", "Bombed Base"],
                "Base Bombings", "display-table"
                )
            for bombing in game["bombings"]:
                with affinitiestable.tr as tr:
                    tr(web.linkif('/player/', bombing["playerhandle"],
                        game["players"][bombing["player"]]["name"]))
                    tr(cgi.escape(teamlist[bombing["bombing"]]["name"]))
                    tr(cgi.escape(teamlist[bombing["bombed"]]["name"]))

        totalwielded = sum([w['timewielded']
            for w in list(game['weapons'].values())
            if w['timewielded'] is not None])
        weaponstable = web.displays.weaponstable(game['weapons'],
            totalwielded, redeclipse(game).weaponlist, version=game)
        if game["mode"] == redeclipse(game).modes['race']:
            weaponstable = None

        ret = """
        <div class="center">
            <h2>Game #{game[id]}: {modestr} on {mapstr}</h2>
            {mutsstr}
            Duration: {duration}<br>
            Played: {agohtml}<br>
            Server: <a
                href="/server/{server[handle]}">{server[desc]}
                [{server[version]}] [{server[handle]}]</a>
            {teams}
            {players}
            {affinities}
            {ffarounds}
            {weapons}
        </div>
        """.format(
            game=game,
            modestr=web.link('/mode/', game["mode"],
                redeclipse(game).modeimg(game["mode"], 32)),
            mutsstr=("Mutators: %s<br>" % redeclipse(game).mutslist(
                game, True, True)) if game['mutators'] else '',
            mapstr=web.link('/map/', game["map"], game["map"]),
            server=server,
            agohtml=timeutils.agohtml(game["time"]),
            duration=timeutils.durstr(game["timeplayed"]),
            players=playerstable.html(True),
            teams=teamstable.html(True) if teamstable is not None else "",
            affinities=affinitiestable.html(True)
                if affinitiestable is not None else "",
            ffarounds=ffarounds.html(True) if "ffarounds" in game else "",
            weapons=weaponstable.html(True)
                if weaponstable is not None else "",
            )
    else:
        ret = "<div class='center'><h2>No such game.</h2></div>"
    return web.page(ret, title="Game %s" % specific)
Exemplo n.º 25
0
def multi(request, db):
    gs = dbselectors.get('games', db)
    gs.flags_none()
    gs.weakflags(['server'], True)

    #Top Weapons
    ws = dbselectors.get('weapons', db, {'recentsums': [5000]})
    weapons = {}
    for name in redeclipse().loadoutweaponlist:
        weapon = ws.single(name)
        weapons[name] = weapon

    topweapons = {
        'wield': (redeclipse().weaponlist[0], 0),
        'dpm': (redeclipse().weaponlist[0], 0),
        'totalwielded': 0,
        }
    if weapons:
        best = sorted(list(weapons.items()), key=lambda weapon: -(
            weapon[1]["damage1"]
            / (max(weapon[1]["timewielded"], 1) / 60) +
            weapon[1]["damage2"]
            / (max(weapon[1]["timewielded"], 1) / 60)))[0]
        topweapons['dpm'] = (best[0], (best[1]["damage1"]
            / (max(best[1]["timewielded"], 1) / 60) +
            best[1]["damage2"]
            / (max(best[1]["timewielded"], 1) / 60)))
        topweapons['totalwielded'] = sum([w['timewielded']
            for w in list(weapons.values())])
        best = sorted(list(weapons.items()), key=lambda weapon: -(
            max(weapon[1]["timewielded"], 1)))[0]
        topweapons['wield'] = (best[0], best[1]["timewielded"])

    # Recent Games
    gamestable = web.Table(
        ["ID", "Mode", "Mutators", "Server", "Map", "Duration", "Played"])
    games = gs.multi()
    for gid in sorted(list(games.keys()), reverse=True)[:10]:
        game = games[gid]
        with gamestable.tr as tr:
            tr(web.link('/game/', gid, "Game #%d" % gid))
            tr(web.link('/mode/', game["mode"],
                redeclipse(game).modeimg(game["mode"])))
            tr(redeclipse(game).mutslist(game, True) or '-')
            tr("%s [%s]" % (
                web.link('/server/', game["server"], game["server"]),
                game["version"]))
            tr(web.link('/map/', game["map"], game["map"], True))
            tr(timeutils.durstr(round(game["timeplayed"])))
            tr(timeutils.agohtml(game["time"]))

    ranks = {
        "spf": rankselectors.get('spf', db, 7).table().html(),
        "captures": rankselectors.get('captures', db, 7).table().html(),
        "bombings": rankselectors.get('bombings', db, 7).table().html(),
        "affmvp": rankselectors.get('mvp', db, 7, "affmvp").table().html(),
        "dmmvp": rankselectors.get('mvp', db, 7, "dmmvp").table().html(),
        "sword": rankselectors.get('weapon', db, 7,
            {"weapon": ('sword', 0)}).best(),
        "sniper": rankselectors.get('weapon', db, 7,
            {"weapon": ('rifle', 2)}).best(),

        "spm": rankselectors.get('spm', db, 30).table().html(),
        "dpm": rankselectors.get('dpm', db, 30).table().html(),
        "fpm": rankselectors.get('fpm', db, 30).table().html(),
        "games": rankselectors.get('games', db, 30).table().html(),

        "maps": rankselectors.get('maps', db, 90).table().html(),
        "servers": rankselectors.get('servers', db, 90).table().html(),
        "ffa": rankselectors.get(
            'winners', db, 90, 'ffa').table().html(),
        "ffasurv": rankselectors.get(
            'winners', db, 90, 'ffasurv').table().html(),
    }

    ret = """
    <h2>Recent Overview</h2>

    <h5><a href="/players">Players</a></h5>
    <h3>Last 7 Days</h3>
    <div class='display-table float-table'>
        <h5>Score/Frags</h5>
        {ranks[spf]}
    </div>
    <div class='display-table float-table'>
        <h5>
        <span class="explain" title="Most Flag Captures">Captures</span></h5>
        {ranks[captures]}
    </div>
    <div class='display-table float-table'>
        <h5>
        <span class="explain" title="Most Base Bombings">Bombings</span></h5>
        {ranks[bombings]}
    </div>
    <div class='display-table float-table'>
        <h5><span class="explain"
        title="Scores from CTF and BB">CTF/BB Team Scores</span></h5>
        {ranks[affmvp]}
    </div>
    <div class='display-table float-table'>
        <h5><span class="explain"
        title="Scores from DM">DM Team Scores</span></h5>
        {ranks[dmmvp]}
    </div>
    <div class='display-table float-table'>
        <h5>Best</h5>
        <table>
            <tr>
                <td><span class="explain"
title="Best Damage and Frags with the Sword">Knight</span></td>
                <td>{ranks[sword]}</td>
            </tr>
            <tr>
                <td><span class="explain"
title="Best Damage and Frags with the Rifle Secondary">
Sniper</span></td>
                <td>{ranks[sniper]}</td>
            </tr>
        </table>
    </div>

    <div style="clear: both;"></div>
    <h3>Last 30 Days</h3>
    <div class='display-table float-table'>
        <h5><a href="/ranks/spm/180"
            class="explain" title="Score per Minute">SPM</a></h5>
        {ranks[spm]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/ranks/dpm/180"
            class="explain" title="Damage per Minute">DPM</a></h5>
        {ranks[dpm]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/ranks/fpm/180"
            class="explain" title="Frags per Minute">FPM</a></h5>
        {ranks[fpm]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/ranks/games/365">Games</a></h5>
        {ranks[games]}
    </div>

    <div style="clear: both;"></div>
    <h3>Last 90 Days</h3>
    <div class='display-table float-table'>
        <h5><a href="/maps">Maps</a></h5>
        {ranks[maps]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/servers">Servers</a></h5>
        {ranks[servers]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/weapons">Weapons</a></h5>
        <table>
            <tr>
                <td>Best DPM</td>
                <td>{weapdpm}</td>
            </tr>
            <tr>
                <td>Most Wielded</td>
                <td>{weapwield}</td>
            </tr>
        </table>
    </div>
    <div class='display-table float-table'>
        <h5><a href="/ranks/winners/180?opts=ffa">
        FFA Win Ratio</a></h5>
        {ranks[ffa]}
    </div>
    <div class='display-table float-table'>
        <h5><a href="/ranks/winners/180?&opts=ffasurv">
        FFA Survivor Win Ratio</a></h5>
        {ranks[ffasurv]}
    </div>

    <div style="clear: both;"></div>
    <div class='display-table'>
        <h5><a href="/games">Latest Games</a></h5>
        {games}
    </div>
    <div style="clear: both;"></div>
    """.format(
        weapdpm="%s %s [%d DPM]" % (
            redeclipse().weaponimg(topweapons['dpm'][0]),
            web.link('/weapon/', topweapons['dpm'][0], topweapons['dpm'][0]),
            topweapons['dpm'][1]),
        weapwield="%s %s [%d%%]" % (
            redeclipse().weaponimg(topweapons['wield'][0]),
            web.link('/weapon/', topweapons['wield'][0],
                topweapons['wield'][0]),
            topweapons['wield'][1]
                / max(topweapons['totalwielded'], 1) * 100),
        games=gamestable.html(),
        ranks=ranks,
        )
    return web.page(ret, title="Overview")
Exemplo n.º 26
0
 def best(self):
     data = self.get()
     if not data:
         return "<i>Nobody</i>"
     return web.link('/player/', data[0][0], data[0][0])