Ejemplo n.º 1
0
class SubottoCore:

    def __init__(self, match_id):
        self.session = Session()
        self.match = self.session.query(Match).filter(Match.id == match_id).one()
        self.teams = [self.match.team_a, self.match.team_b]
        self.order = [None, None]
        self.queues = [[], []]
        self.score = [0, 0]
        self.players = [[None, None], [None, None]]
        self.listeners = []

        self.last_event_id = 0
        self.last_player_match_id = 0
        self.last_timestamp = None

    def close(self):
        self.session.rollback()
        self.session.close()

    def detect_team(self, team):
        if team == self.match.team_a:
            return 0
        else:
            return 1

    def new_player_match(self, player_match):
        print >> sys.stderr, "> Received new player match: %r" % (player_match)

        for listener in self.listeners:
            listener.new_player_match(player_match)

    def new_event(self, event):
        print >> sys.stderr, "> Received new event: %r" % (event)

        if event.type == Event.EV_TYPE_SWAP:
            self.order = [event.red_team, event.blue_team]

        elif event.type == Event.EV_TYPE_CHANGE:
            self.players[self.detect_team(event.team)] = [event.player_a, event.player_b]

        elif event.type == Event.EV_TYPE_GOAL:
            self.score[self.detect_team(event.team)] += 1

        elif event.type == Event.EV_TYPE_GOAL_UNDO:
            self.score[self.detect_team(event.team)] -= 1

        elif event.type == Event.EV_TYPE_ADVANTAGE_PHASE:
            pass

        else:
            print >> sys.stderr, "> Wrong event type %r\n" % (event.type)

        for listener in self.listeners:
            listener.new_event(event)

    def regenerate(self):
        print >> sys.stderr, "> Regeneration"
        for listener in self.listeners:
            listener.regenerate()

    def update(self):
        self.session.rollback()

        for player_match in self.session.query(PlayerMatch).filter(PlayerMatch.match == self.match).filter(PlayerMatch.id > self.last_player_match_id).order_by(PlayerMatch.id):
            self.new_player_match(player_match)
            self.last_player_match_id = player_match.id

        for event in self.session.query(Event).filter(Event.match == self.match).filter(Event.id > self.last_event_id).order_by(Event.id):
            if self.last_timestamp is not None and event.timestamp <= self.last_timestamp:
                print >> sys.stderr, "> Timestamp monotonicity error at %s!\n" % (event.timestamp)
                #sys.exit(1)
            self.new_event(event)
            self.last_timestamp = event.timestamp
            self.last_event_id = event.id

        for idx in [0, 1]:
            team = self.teams[idx]
            this_num = 0
            self.queues[idx] = []
            for queue_element in self.match.get_queue(team):
                if queue_element.num != this_num:
                    printf >> sys.stderr, "> Error: queues are inconsistent"
                this_num += 1
                self.queues[idx].append((queue_element.player_a, queue_element.player_b))

        self.regenerate()
        return True

    def act_event(self, event, source=None):
        event.timestamp = now()
        event.match = self.match
        if source is None:
            event.source = Event.EV_SOURCE_MANUAL
        else:
            event.source = source
        if not event.check_type():
            print >> sys.stderr, "> Sending bad event..."
        self.session.add(event)
        self.session.commit()
        self.update()

    def act_switch_teams(self, source=None):
        e = Event()
        e.type = Event.EV_TYPE_SWAP
        if self.order == [None, None]:
            e.red_team = self.teams[0]
            e.blue_team = self.teams[1]
        else:
            e.red_team = self.order[1]
            e.blue_team = self.order[0]
        self.act_event(e, source)

    def act_goal(self, team, source=None):
        e = Event()
        e.type = Event.EV_TYPE_GOAL
        e.team = team
        self.act_event(e, source)

    def act_goal_undo(self, team, source=None):
        e = Event()
        e.type = Event.EV_TYPE_GOAL_UNDO
        e.team = team
        self.act_event(e, source)

    def act_team_change(self, team, player_a, player_b, source=None):
        e = Event()
        e.type = Event.EV_TYPE_CHANGE
        e.team = team
        e.player_a = player_a
        e.player_b = player_b
        self.act_event(e, source)

    def act_add_to_queue(self, team, player_a, player_b):
        qe = QueueElement()
        qe.match = self.match
        qe.team = team
        qe.player_a = player_a
        qe.player_b = player_b
        qe.num = len(self.queues[self.detect_team(team)])
        self.session.add(qe)
        self.session.commit()
        self.update()

    def act_remove_from_queue(self, team, num):
        queue = self.match.get_queue(team)
        self.session.delete(queue[num])
        self.session.flush()
        del queue[num]
        # Indirect assignement to prevent failing constraints
        for i in xrange(num, len(queue)):
            queue[i].num = None
        self.session.flush()
        for i in xrange(num, len(queue)):
            queue[i].num = i
        self.session.commit()
        self.update()

    def act_swap_queue(self, team, num1, num2):
        queue = self.match.get_queue(team)
        # Indirect assignement to prevent failing constraints
        queue[num1].num = None
        queue[num2].num = None
        self.session.flush()
        queue[num1].num = num2
        queue[num2].num = num1
        self.session.commit()
        self.update()

    def act_begin_match(self, begin=None):
        if begin is None:
            begin = datetime.datetime.now()
        self.match.begin = begin
        self.session.commit()

    def act_end_match(self, end=None):
        if end is None:
            end = datetime.datetime.now()
        self.match.end = end
        self.session.commit()

    def act_add_player_match_from_name(self, team, fname, lname, comment=None, bulk=False):
        player = Player.get_or_create(self.session, fname, lname, comment)
        try:
            player_match = self.session.query(PlayerMatch).filter(PlayerMatch.match == self.match). \
                filter(PlayerMatch.player == player).one()
        except NoResultFound:
            player_match = PlayerMatch()
            player_match.player = player
            player_match.match = self.match
            player_match.team = team
            self.session.add(player_match)
            if not bulk:
                self.session.commit()

    def easy_get_red_team(self):
        return self.order[0]

    def easy_get_blue_team(self):
        return self.order[1]

    def easy_get_red_score(self):
        return self.score[self.detect_team(self.easy_get_red_team())]

    def easy_get_blue_score(self):
        return self.score[self.detect_team(self.easy_get_blue_team())]

    def easy_act_red_goal_cell(self):
        self.act_goal(self.easy_get_blue_team(), source=Event.EV_SOURCE_CELL_RED_PLAIN)

    def easy_act_red_supergoal_cell(self):
        self.act_goal(self.easy_get_blue_team(), source=Event.EV_SOURCE_CELL_RED_SUPER)

    def easy_act_red_goal_button(self):
        self.act_goal(self.easy_get_red_team(), source=Event.EV_SOURCE_BUTTON_RED_GOAL)

    def easy_act_red_goalundo_button(self):
        self.act_goal_undo(self.easy_get_red_team(), source=Event.EV_SOURCE_BUTTON_RED_UNDO)

    def easy_act_blue_goal_cell(self):
        self.act_goal(self.easy_get_red_team(), source=Event.EV_SOURCE_CELL_BLUE_PLAIN)

    def easy_act_blue_supergoal_cell(self):
        self.act_goal(self.easy_get_red_team(), source=Event.EV_SOURCE_CELL_BLUE_SUPER)

    def easy_act_blue_goal_button(self):
        self.act_goal(self.easy_get_blue_team(), source=Event.EV_SOURCE_BUTTON_BLUE_GOAL)

    def easy_act_blue_goalundo_button(self):
        self.act_goal_undo(self.easy_get_blue_team(), source=Event.EV_SOURCE_BUTTON_BLUE_UNDO)
Ejemplo n.º 2
0
    last_interesting = 0.0
    try:
        while True:
            line = sys.stdin.readline()
            if line == '':
                break
            data = [my_float(x) for x in line.strip().split(",")]
            if retime:
                data[0] = time.time()
            timestamp = float(data[0])
            log = Log.from_tuple(data)
            if timestamp - last_interesting >= 1.0 / INTERESTING_FPS:
                log.interesting = True
                last_interesting = timestamp
            session.add(log)
            session.flush()
            now = time.time()
            if now - last_commit >= COMMIT_FREQ:
                last_commit = now
                # After the implicit flush, all the objects in the
                # session are weakly references by the session, so
                # they're immediately pruned; i.e., this shouldn't
                # have memory leaks
                session.commit()

    except KeyboardInterrupt:
        pass

    finally:
        session.commit()
Ejemplo n.º 3
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)
Ejemplo n.º 4
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()