Beispiel #1
0
    def getMatchDetails(self, *args, **kwargs):
        if "dm_output" in kwargs:
            match = kwargs.pop("dm_output")
        else:
            match = Match(client=self)

        params = self._prepare_dict(kwargs)
        url = self._getUrl("IDOTA2Match_570/GetMatchDetails/V001", params)
        f = urllib.urlopen(url)
        d = json.load(f)

        match.detailsFromJSON(d["result"])

        return match
Beispiel #2
0
 def matchinfo(self, ids):
     matches = self.dp.fetchmatchdata(ids)
     output = ''
     for mid in ids:
         match = Match.creatematch(mid, matches[mid])
         output += match.matchstr(self.dp) + '\n'
     return output
Beispiel #3
0
    def matchinfo(self, ids):
        matches = self.dp.fetchmatchdata(ids)
        tmpl_h, tmpl_f = Html.loadtemplates()

        output = tmpl_h.substitute()

        for mid in ids:
            match = Match.creatematch(mid, matches[mid])
            legionplayers = match.players(team="legion")
            hellbourneplayers = match.players(team='hellbourne')

            output += '<h2>{mid}</h2>'.format(mid=mid)
            output += match.gamedatestr() + ' GD: ' + str(match.gameduration()) + '<br />\n'
            output += '<table cellspacing="0" cellpadding="2">'
            output += '<tr>'
            output += Html.list2cols(['Legion', 'Hero', 'LVL', 'K', 'D', 'A', 'CK', 'CD', 'W', 'GPM', 'GL2D',
                                      'Hellbourne', 'Hero', 'LVL', 'K', 'D', 'A', 'CK', 'CD', 'W', 'GPM', 'GL2D'], 'th')

            legioncols = []
            for id_ in legionplayers.keys():
                legioncols.append([LinkItem('/player/{nick}'.format(nick=self.dp.id2nick(id_)), self.dp.id2nick(id_)),
                                  self.dp.heroid2name(match.playerstat(id_, 'hero_id')),
                                  match.playerstat(id_, 'level'),
                                  match.playerstat(id_, 'herokills'),
                                  match.playerstat(id_, 'deaths'),
                                  match.playerstat(id_, 'heroassists'),
                                  match.playerstat(id_, 'teamcreepkills') + match.playerstat(id_, 'neutralcreepkills'),
                                  match.playerstat(id_, 'denies'),
                                  match.playerstat(id_, 'wards'),
                                  int(match.playerstat(id_, 'gold') / (match.gameduration().total_seconds() / 60)),
                                  match.playerstat(id_, 'goldlost2death')])

            hellcols = []
            for id_ in hellbourneplayers.keys():
                hellcols.append([LinkItem('/player/{nick}'.format(nick=self.dp.id2nick(id_)), self.dp.id2nick(id_)),
                                self.dp.heroid2name(match.playerstat(id_, 'hero_id')),
                                match.playerstat(id_, 'level'),
                                match.playerstat(id_, 'herokills'),
                                match.playerstat(id_, 'deaths'),
                                match.playerstat(id_, 'heroassists'),
                                match.playerstat(id_, 'teamcreepkills') + match.playerstat(id_, 'neutralcreepkills'),
                                match.playerstat(id_, 'denies'),
                                match.playerstat(id_, 'wards'),
                                int(match.playerstat(id_, 'gold') / (match.gameduration().total_seconds() / 60)),
                                match.playerstat(id_, 'goldlost2death')])

            size = max(len(hellcols), len(legioncols))
            for i in range(0, size):
                if i < len(legioncols):
                    output += '<tr>' + Html.list2cols(legioncols[i] + hellcols[i]) + '</tr>'
                else:
                    output += '<tr><td colspan="11">&nbsp;</td>' + Html.list2cols(hellcols[i]) + '</tr>'

            output += '</tr>'
            output += '</table>'
        return output + tmpl_f.substitute()
Beispiel #4
0
def act_init_match(session, name, team_a, team_b, sched_begin, sched_end):
    match = Match()
    match.sched_begin = sched_begin
    match.sched_end = sched_end
    match.begin = None
    match.end = None
    match.name = name
    match.team_a = team_a
    match.team_b = team_b
    session.add(match)
    session.commit()
    return match.id
Beispiel #5
0
    def matchesinfo(self, ids, statstype, limit):
        output = ''
        for id_ in ids:
            matchids = self.dp.matches(id_, statstype)
            avgdata = Text.initavgdata()
            limit = min(limit, len(matchids)) if limit else len(matchids)
            output += self.dp.id2nick(id_) + '\n'
            output += Match.headermatches() + '\n'
            for i in range(limit):
                matches = self.dp.fetchmatchdata([matchids[i]])
                match = Match.creatematch(matchids[i], matches[matchids[i]])

                # count average
                if isinstance(match, Match):
                    matchdata = match.matchesdata(self.dp.nick2id(id_), self.dp)
                    avgdata = Text.fillavgdata(avgdata, matchdata)
                output += match.matchesstr(self.dp.nick2id(id_), self.dp) + '\n'
            avgdata = Text.finalizeavgdata(avgdata, limit)
            output += "average   " + Match.MatchesFormat.format(**avgdata)[10:] + '\n'
            #print(json.dumps(history))
        return output
Beispiel #6
0
    def lastmatchesinfo(self, ids, statstype, hero, arglimit, count):
        output = ''
        for id_ in ids:
            id_hero = (id_, hero) if hero else None
            matchids = self.dp.matches(id_, statstype)
            limit = arglimit if (arglimit or count) < count else count
            matches = self.dp.fetchmatchdata(matchids, limit=limit, id_hero=id_hero)
            output += self.dp.id2nick(id_) + '\n'
            for mid in sorted(matches.keys(), reverse=True):
                match = Match.creatematch(mid, matches[mid])
                output += match.matchstr(self.dp) + '\n'

        return output
Beispiel #7
0
    def getMatchHistory(self, *args, **kwargs):
        params = self._prepare_dict(kwargs)
        url = self._getUrl("IDOTA2Match_570/GetMatchHistory/V001", params)
        f = urllib.urlopen(url)
        d = json.load(f)

        # TODO realize as iterator
        matches = []
        for matchDict in d['result']['matches']:
            try:
                match = Match.fromJSON(matchDict)
                if match is not None:
                    matches.append(match)
            except Exception as e:
                print(e)
                logger.warn("Skipped result")
                raise
        return matches
def task_matches():

    logging.info("Performing match maintainance...")

    matches = list(Match.query().fetch())

    for match in matches:

        # Delete all matches whose last move is older than the specified timeout
        if match.last_move_date:
            expired = (datetime.now() -
                       match.last_move_date) > timedelta(seconds=match.timeout)
        else:
            expired = False

        if expired:

            white = User.get_by_id(match.white_id)
            black = User.get_by_id(match.black_id)

            if match.is_user_turn(white):
                looser = white
                winner = black
            else:
                winner = white
                looser = black

            white.send_message(
                constants.ERROR_TIMEOUT.format(
                    looser.username,
                    humanfriendly.format_timespan(match.timeout)))
            black.send_message(
                constants.ERROR_TIMEOUT.format(
                    looser.username,
                    humanfriendly.format_timespan(match.timeout)))

            winner.end_game(GameResult.WIN)
            looser.end_game(GameResult.LOSE)

            # Delete match
            logging.info("Deleting match %s. Last activity: %s",
                         match.key.id(), str(match.last_move_date))
            match.key.delete()
Beispiel #9
0
    def matchesinfo(self, ids, statstype, limit):
        tmpl_h, tmpl_f = Html.loadtemplates()

        output = tmpl_h.substitute()

        for id_ in ids:
            output += '<h2>{nick}</h2>'.format(nick=id_)
            output += '<table cellspacing="0" cellpadding="2">'
            output += '<tr>' + Html.list2cols(['MID', 'GT', 'GD', 'Date', 'K', 'D', 'A', 'KDR',
                                               'Hero', 'WL', 'Wards', 'CK', 'CD', 'GPM'], 'th') + '</tr>'

            matchids = self.dp.matches(id_, statstype)
            avgdata = text.Text.initavgdata()
            limit = limit if limit else len(matchids)

            for i in range(limit):
                matches = self.dp.fetchmatchdata([matchids[i]])
                match = Match.creatematch(matchids[i], matches[matchids[i]])

                if isinstance(match, Match):
                    matchdata = match.matchesdata(self.dp.nick2id(id_), self.dp)
                    avgdata = text.Text.fillavgdata(avgdata, matchdata)

                rowdata = [LinkItem("/match/" + str(matchdata['mid']), matchdata['mid']),
                           matchdata['gt'],
                           matchdata['gd'],
                           matchdata['date'],
                           matchdata['k'],
                           matchdata['d'],
                           matchdata['a'],
                           round(matchdata['kdr'], 2),
                           matchdata['hero'],
                           matchdata['wl'],
                           matchdata['wa'],
                           matchdata['ck'],
                           matchdata['cd'],
                           matchdata['gpm']]
                output += '<tr>' + Html.list2cols(rowdata) + '</tr>'

            output += '</table>'
        return output + tmpl_f.substitute()
Beispiel #10
0
    def arg_body(self):

        user = self.user
        adversary_username = self.text

        if self.text == "/cancel":
            user.send_message("Game cancelled!",
                              reply_markup=telegram.ReplyKeyboardRemove(True))
        else:
            if adversary_username == user.username and not user.admin:
                user.send_message(
                    constants.ERROR_SAME_USER,
                    reply_markup=telegram.ReplyKeyboardRemove(True))
                return

            query = User.query(User.username == adversary_username)
            query_list = list(query.fetch())

            if len(query_list) != 1:
                # Adversary not found
                invite_button = [[
                    telegram.InlineKeyboardButton(
                        "Invite a friend",
                        switch_inline_query=constants.STRING_SHARED)
                ]]
                reply_markup = telegram.InlineKeyboardMarkup(invite_button)
                user.send_message(
                    adversary_username + " is not a Chess Duel Bot user.",
                    reply_markup=telegram.ReplyKeyboardRemove(True))
                user.send_message(constants.STRING_INVITE,
                                  reply_markup=reply_markup)
                return

            adversary = query_list[0]
            if adversary.status == UserStatus.IDLE:

                try:
                    timeout = int(user.pending_arg)
                except ValueError:
                    # TODO: Print error
                    return

                match = Match(white_id=adversary.key.id(),
                              black_id=user.key.id(),
                              timeout=timeout)
                match.put()

                # Adversary found
                user.setup_match(match, adversary, False)
                user.send_message(
                    constants.STRING_REQUEST_SENT,
                    reply_markup=telegram.ReplyKeyboardRemove(True))

                adversary.setup_match(match, user, True)
                accept_button = [[
                    telegram.InlineKeyboardButton("Accept",
                                                  callback_data='/accept'),
                    telegram.InlineKeyboardButton("Refuse",
                                                  callback_data='/refuse')
                ]]
                reply_markup = telegram.InlineKeyboardMarkup(accept_button)
                adversary.send_message(
                    constants.STRING_REQUEST_RECEIVED.format(
                        user.username,
                        humanfriendly.format_timespan(match.timeout)),
                    reply_markup=reply_markup)
            else:

                # Adversary busy
                user.send_message(
                    "Adversary is busy",
                    reply_markup=telegram.ReplyKeyboardRemove(True))
Beispiel #11
0
def replay_match(orig_match_id, mult=1.0, initial_wait=0.0):

    session = Session()

    # Retrieve the original match and prepare the new event list
    # (already sorted by SQLAlchemy)
    orig_match = session.query(Match).filter(Match.id == orig_match_id).one()
    events = [((min(max(x.timestamp, orig_match.begin), orig_match.end) - orig_match.begin).total_seconds(), x)
              for x in orig_match.events]
    ref_time = 0.0
    for i in xrange(len(events)):
        delta = events[i][0] - ref_time
        ref_time = events[i][0]
        events[i] = (delta / mult, events[i][1])

    # Replicate the original match
    match = Match()
    match.sched_begin = datetime.datetime.now() + datetime.timedelta(seconds=0.5 * initial_wait)
    match.sched_end = match.sched_begin + multiply_timedelta(1.0 / mult, orig_match.sched_end - orig_match.sched_begin)
    match.name = "Replay of \"%s\"" % (orig_match.name)
    match.team_a = orig_match.team_a
    match.team_b = orig_match.team_b
    session.add(match)

    # Add the advantage phases
    phase = AdvantagePhase()
    phase.match = match
    phase.start_sec = 0
    phase.advantage = 10
    session.add(phase)
    phase = AdvantagePhase()
    phase.match = match
    phase.start_sec = 30 * 60
    phase.advantage = 5
    session.add(phase)
    phase = AdvantagePhase()
    phase.match = match
    phase.start_sec = 60 * 60
    phase.advantage = 3
    session.add(phase)

    # Replicate the player_matches
    for orig_pm in session.query(PlayerMatch).filter(PlayerMatch.match == orig_match):
        pm = PlayerMatch()
        pm.match = match
        pm.player = orig_pm.player
        pm.team = orig_pm.team
        session.add(pm)

    # Flush and commit
    session.flush()
    session.commit()

    # Print match ID and start wait
    print "> Feeding match with ID %d" % (match.id)
    print "> Scheduled times: %s -- %s" % (match.sched_begin, match.sched_end)
    print "> Waiting initial %f seconds..." % (initial_wait)
    time.sleep(initial_wait)

    # Set begin
    match.begin = datetime.datetime.now()
    print "> Match begins at %s" % (match.begin)
    session.commit()

    # Replay events
    for wait_secs, orig_ev in events:
        print "> Waiting %f seconds..." % (wait_secs)
        time.sleep(wait_secs)
        ev = Event()
        ev.timestamp = datetime.datetime.now()
        ev.match = match
        ev.type = orig_ev.type
        ev.source = orig_ev.source
        ev.team = orig_ev.team
        ev.player_a = orig_ev.player_a
        ev.player_b = orig_ev.player_b
        ev.red_team = orig_ev.red_team
        ev.blue_team = orig_ev.blue_team
        ev.phase = orig_ev.phase
        print "> Pushing event of type %s and timestamp %s" % (ev.type, ev.timestamp)
        session.add(ev)
        ev.check_type()
        session.commit()

    # Set end
    match.end = datetime.datetime.now()
    print "> Match ends at %s" % (match.end)
    session.commit()

    print "> Finished feeding match with ID %d" % (match.id)
    print "> Scheduled times were: %s -- %s" % (match.sched_begin, match.sched_end)
Beispiel #12
0
def import_from_2012():
    old_session = OldSession()
    session = Session()

    # Match and teams
    match = Match()
    match.name = "24 ore 2012"
    first_team = session.query(Team).filter(Team.name == "Matematici").one()
    second_team = session.query(Team).filter(Team.name == "Fisici").one()
    match.team_a = first_team
    match.team_b = second_team

    # Team mapping
    _team_map = {}
    old_first_team = old_session.query(OldTeam).filter(OldTeam.name == "Matematici").one()
    old_second_team = old_session.query(OldTeam).filter(OldTeam.name == "Fisici").one()
    _team_map[old_first_team.id] = first_team
    _team_map[old_second_team.id] = second_team
    team_map = lambda x: _team_map[x.id]

    # Player mapping
    _player_map = {}
    player_matches = []
    found_player_id = set()
    for old_player in old_session.query(OldPlayer).all():
        player = Player.get_or_create(session, old_player.fname, old_player.lname, None)
        _player_map[old_player.id] = player
        player_match = PlayerMatch()
        player_match.player = player
        player_match.match = match
        player_match.team = team_map(old_player.team)
        player_matches.append(player_match)
    player_map = lambda x: _player_map[x.id]

    # Events
    events = []
    for old_event in old_session.query(OldEvent).order_by(OldEvent.timestamp).all():
        if old_event.type == 'sched_begin':
            match.sched_begin = old_event.timestamp
        elif old_event.type == 'begin':
            match.begin = old_event.timestamp
        elif old_event.type == 'sched_end':
            match.sched_end = old_event.timestamp
        elif old_event.type  == 'end':
            match.end = old_event.timestamp
        else:
            event = Event()
            event.match = match
            event.timestamp = old_event.timestamp
            event.source = Event.EV_SOURCE_MANUAL
            event.type = old_event.type
            if old_event.type in [Event.EV_TYPE_GOAL, Event.EV_TYPE_GOAL_UNDO]:
                event.team = _team_map[int(old_event.param)]
            elif old_event.type == Event.EV_TYPE_SWAP:
                old_red_team_id, old_blue_team_id = map(int, old_event.param.split(','))
                event.red_team = _team_map[old_red_team_id]
                event.blue_team = _team_map[old_blue_team_id]
            elif old_event.type == Event.EV_TYPE_CHANGE:
                old_team_id, old_player_a_id, old_player_b_id = map(int, old_event.param.split(','))
                event.team = _team_map[old_team_id]
                event.player_a = _player_map[old_player_a_id]
                event.player_b = _player_map[old_player_b_id]
                found_player_id.add(event.player_a.id)
                found_player_id.add(event.player_b.id)
            else:
                assert(False, "Command not supported")
            events.append(event)

    session.add(match)
    for pm in player_matches:
        if pm.player.id in found_player_id:
            session.add(pm)
    for ev in events:
        session.add(ev)
        assert(ev.check_type())
    session.flush()
    old_session.rollback()
    session.commit()
Beispiel #13
0
def import_from_2011():
    session = Session()
    match = Match()
    match.name = "24 ore 2011"
    import_log(match, session, '2011/log-seconda-24h.txt')
Beispiel #14
0
def import_from_2010():
    session = Session()
    match = Match()
    match.name = "24 ore 2010"
    import_log(match, session, '2010/log-finale.txt')