Example #1
0
 def __init__(self):
     self.model = Game()
     self.job = None
     self.speed = 1
     self.root = Tk()
     self.canvas = Field(self.root, self.model)
     self.toolbar = Toolbar(self.root)
     self.toolbar.add_button(text='Load', command=self.load)
     self.toolbar.add_button(text='Save', command=self.save)
     self.toolbar.add_button(text='Origin', command=self.canvas.origin)
     self.toolbar.add_radio_button_group(buttons={
         1: 'Pause',
         2: 'Play'
     },
                                         command=self.on_state_changed)
     self.toolbar.add_radio_button_group(buttons={
         1: 'x1',
         2: 'x2',
         4: 'x4',
         8: 'x8',
         16: 'x16'
     },
                                         command=self.on_speed_changed)
     self.toolbar.pack(side=TOP, fill=X)
     self.canvas.pack()
     self.root.resizable(False, False)
  def GET(self, game_id):
    game = Game.get(game_id)
    chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True)
    you = get_you()
    
    #players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()])

    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if you:
      your_players = [color for (color,player) in game.players.items() if player.id == you.id]
      #print "Your Players: %s" % game.players.items()[0].id
    else:
      print "NOTHING"
      your_players = []
      
    return render('game',game=game, you=get_you(), chats=chats, your_players=your_players)
Example #3
0
    def _PossiblyAddTweetToGame(self, twt, existing_games, added_games,
                                user_map, division, age_bracket, league):
        """Determine if a tweet is a game tweet and add it to a game if so.

    Args:
      twt: tweets.Tweet object to be processed.
      existing_games: list of game_model.Game objects that are currently in the
        db.
      added_games: list of game_model.Game objects that have been added as part 
        of this crawl request.
      user_map: map of string user ids to users which have authored a tweet
        during this crawl cycle and thus may not be propagated in the db yet.
      division: Division to set new Game to, if creating one
      age_bracket: AgeBracket to set new Game to, if creating one
      league: League to set new Game to, if creating one
    """
        if not twt:
            return
        if not twt.two_or_more_integers:
            return

        score_indicies = self._FindScoreIndicies(twt.entities.integers,
                                                 twt.text)
        if not score_indicies:
            logging.debug('Ignoring tweet - numbers aren\'t scores: %s',
                          twt.text)
            return

        teams = self._FindTeamsInTweet(twt, user_map)
        logging.debug('teams: %s', teams)
        scores = [
            twt.entities.integers[score_indicies[0]].num,
            twt.entities.integers[score_indicies[1]].num
        ]
        logging.debug('scores: %s', scores)
        (consistency_score, game) = self._FindMostConsistentGame(
            twt, existing_games + added_games, teams, division, age_bracket,
            league, scores)
        logging.debug('consistency score %s for twt %s', consistency_score,
                      twt.text)
        # TODO: detect tweets that are summaries for the day (eg, "We went
        # 3-0 today")
        # Some examples:
        # - "X and Y both finish 3-1 on the day. Final pool play game at 9am. @FCStourney"
        # - "Y is 3-0 playing Turbine at 3. X is 2-0 winning their third game. @FCStourney"
        # - "3-0 today with wins over Ozone, Grit, and Rut-ro. Quarters against Rogue tomorrow morning!"

        # Tricky cases:
        # - "A really great finals game with @PhxUltimate leaves us coming up a little short, 10-11. Great weekend everyone! #southeastreppin"

        # Try to find a game that matches this tweet in existing games. If no such
        # game exists, create one.
        if consistency_score < GAME_CONSISTENCY_THRESHOLD:
            added_games.append(
                Game.FromTweet(twt, teams, scores, division, age_bracket,
                               league))
        else:
            for source in game.sources:
                if twt.id_64 == source.tweet_id:
                    logging.debug(
                        'Tried to add tweet more than once as game source %s',
                        twt)
                    return
            game.sources.append(GameSource.FromTweet(twt, scores))
            game.sources.sort(
                cmp=lambda x, y: cmp(y.update_date_time, x.update_date_time))
            self._MergeTeamsIntoGame(game, teams)
Example #4
0
    def get(self):
        list_id = self.request.get('list_id')
        if not list_id:
            msg = 'No list name specified'
            logging.warning(msg)
            self.response.write(msg)
            return

        last_tweet_id = self._LookupLatestTweet(list_id)
        crawl_state = CrawlState.FromRequest(self.request, last_tweet_id)

        # In parallel: look-up the latest set of games for this
        # division and cache it
        division, age_bracket, league = list_id_bimap.ListIdBiMap.GetStructuredPropertiesForList(
            crawl_state.list_id)

        backfill_date = ParseDate(self.request.get('backfill_date'))
        update_games_only = self.request.get('update_games_only')
        games_start = datetime.utcnow()
        if backfill_date:
            games_start = backfill_date + timedelta(weeks=1)
            # Query tweets for that week for this list
            if not update_games_only:
                tweet_query = tweets.Tweet.query(
                    tweets.Tweet.from_list == list_id,
                    tweets.Tweet.created_at > games_start - timedelta(weeks=1),
                    tweets.Tweet.created_at <
                    games_start).order().order(-tweets.Tweet.created_at)
                twts_future = tweet_query.fetch_async()

        # For Twitter, only pull up games for the last two weeks.
        twit_games_query = Game.query(
            Game.division == division, Game.age_bracket == age_bracket,
            Game.league == league,
            Game.last_modified_at > games_start - timedelta(weeks=1),
            Game.last_modified_at < games_start).order(-Game.last_modified_at)
        twit_games_future = twit_games_query.fetch_async()

        tourney_ids = []
        if league == League.USAU:
            tourneys_query = Tournament.query(
                Tournament.end_date < games_start + timedelta(days=3))
            tourneys = tourneys_query.fetch(100)
            for tourney in tourneys:
                if not tourney.sub_tournaments:
                    continue
                for st in tourney.sub_tournaments:
                    if st.division == division and st.age_bracket == age_bracket:
                        tourney_ids.append(tourney.id_str)

        if tourney_ids:
            # For SR, pull up games scheduled for a day in either direction.
            sr_games_query = Game.query(Game.division == division,
                                        Game.age_bracket == age_bracket,
                                        Game.league == league,
                                        Game.tournament_id.IN(tourney_ids))
            sr_games_future = sr_games_query.fetch_async()

        if not backfill_date:
            token_manager = oauth_token_manager.OauthTokenManager()
            fetcher = twitter_fetcher.TwitterFetcher(token_manager)
            try:
                json_obj = fetcher.ListStatuses(
                    crawl_state.list_id,
                    count=crawl_state.num_to_crawl,
                    since_id=crawl_state.last_tweet_id,
                    max_id=crawl_state.max_id,
                    fake_data=self.request.get('fake_data'))
            except twitter_fetcher.FetchError as e:
                msg = 'Could not fetch statuses for list %s' % crawl_state.list_id
                logging.warning('%s: %s', msg, e)
                self.response.write(msg)

                # TODO: retry the request a fixed # of times
                return

            # Update the various datastores.
            twts, users = self.UpdateTweetDbWithNewTweets(
                json_obj, crawl_state)

        if backfill_date:
            if update_games_only:
                twts = []
            else:
                twts = twts_future.get_result()
            users = {}

        existing_games = twit_games_future.get_result()
        if tourney_ids:
            sr_existing_games = sr_games_future.get_result()
            existing_games.extend(sr_existing_games)
        self.UpdateGames(twts, existing_games, users, division, age_bracket,
                         league)
  def get(self):
    list_id = self.request.get('list_id')
    if not list_id:
      msg = 'No list name specified'
      logging.warning(msg)
      self.response.write(msg)
      return

    last_tweet_id = self._LookupLatestTweet(list_id)
    crawl_state = CrawlState.FromRequest(self.request, last_tweet_id)
    
    # In parallel: look-up the latest set of games for this
    # division and cache it
    division, age_bracket, league = list_id_bimap.ListIdBiMap.GetStructuredPropertiesForList(
        crawl_state.list_id)

    backfill_date = ParseDate(self.request.get('backfill_date'))
    update_games_only = self.request.get('update_games_only')
    games_start = datetime.utcnow()
    if backfill_date:
      games_start = backfill_date + timedelta(weeks=1)
      # Query tweets for that week for this list
      if not update_games_only:
        tweet_query = tweets.Tweet.query(
            tweets.Tweet.from_list == list_id,
            tweets.Tweet.created_at > games_start - timedelta(weeks=1),
            tweets.Tweet.created_at < games_start).order(
            ).order(-tweets.Tweet.created_at)
        twts_future = tweet_query.fetch_async()

    # For Twitter, only pull up games for the last two weeks.
    twit_games_query = Game.query(Game.division == division,
        Game.age_bracket == age_bracket,
        Game.league == league,
        Game.last_modified_at > games_start - timedelta(weeks=1),
        Game.last_modified_at < games_start).order(
            -Game.last_modified_at)
    twit_games_future = twit_games_query.fetch_async()

    tourney_ids = []
    if league == League.USAU:
      tourneys_query = Tournament.query(
          Tournament.end_date < games_start + timedelta(days=3))
      tourneys = tourneys_query.fetch(100)
      for tourney in tourneys:
        if not tourney.sub_tournaments:
          continue
        for st in tourney.sub_tournaments:
          if st.division == division and st.age_bracket == age_bracket:
            tourney_ids.append(tourney.id_str)

    if tourney_ids:
      # For SR, pull up games scheduled for a day in either direction.
      sr_games_query = Game.query(Game.division == division,
          Game.age_bracket == age_bracket,
          Game.league == league,
          Game.tournament_id.IN(tourney_ids))
      sr_games_future = sr_games_query.fetch_async()

    if not backfill_date:
      token_manager = oauth_token_manager.OauthTokenManager()
      fetcher = twitter_fetcher.TwitterFetcher(token_manager)
      try:
        json_obj = fetcher.ListStatuses(crawl_state.list_id, count=crawl_state.num_to_crawl,
            since_id=crawl_state.last_tweet_id, max_id=crawl_state.max_id,
            fake_data=self.request.get('fake_data'))
      except twitter_fetcher.FetchError as e:
        msg = 'Could not fetch statuses for list %s' % crawl_state.list_id
        logging.warning('%s: %s', msg, e)
        self.response.write(msg)

        # TODO: retry the request a fixed # of times
        return

      # Update the various datastores.
      twts, users = self.UpdateTweetDbWithNewTweets(json_obj, crawl_state)

    if backfill_date:
      if update_games_only:
        twts = []
      else:
        twts = twts_future.get_result()
      users = {}

    existing_games = twit_games_future.get_result()
    if tourney_ids:
      sr_existing_games = sr_games_future.get_result()
      existing_games.extend(sr_existing_games)
    self.UpdateGames(twts, existing_games, users, division, age_bracket, league)
Example #6
0
class GameApp:
    def __init__(self):
        self.model = Game()
        self.job = None
        self.speed = 1
        self.root = Tk()
        self.canvas = Field(self.root, self.model)
        self.toolbar = Toolbar(self.root)
        self.toolbar.add_button(text='Load', command=self.load)
        self.toolbar.add_button(text='Save', command=self.save)
        self.toolbar.add_button(text='Origin', command=self.canvas.origin)
        self.toolbar.add_radio_button_group(buttons={
            1: 'Pause',
            2: 'Play'
        },
                                            command=self.on_state_changed)
        self.toolbar.add_radio_button_group(buttons={
            1: 'x1',
            2: 'x2',
            4: 'x4',
            8: 'x8',
            16: 'x16'
        },
                                            command=self.on_speed_changed)
        self.toolbar.pack(side=TOP, fill=X)
        self.canvas.pack()
        self.root.resizable(False, False)

    def load(self):
        filename = filedialog.askopenfilename(initialdir="./data/",
                                              title="Select file",
                                              filetypes=(("Life files",
                                                          "*.life"),
                                                         ("All files", "*.*")))
        try:
            with open(filename, 'r') as file:
                field = FieldSerializer.deserialize(file)
                self.model.field = field
                self.canvas.update()
        except IOError as error:
            print(error, file=sys.stderr)

    def save(self):
        filename = filedialog.asksaveasfilename(
            initialdir="./data/",
            title="Save file as",
            filetypes=(("Life files", "*.life"), ("All files", "*.*")))
        try:
            with open(filename, 'w') as file:
                buffer = FieldSerializer.serialize(self.model.field)
                buffer.seek(0)
                shutil.copyfileobj(buffer, file)
                buffer.close()
        except IOError as error:
            print(error, file=sys.stderr)

    def play(self):
        self.model.next_state()
        self.job = self.root.after(int(self.speed * 1000), self.play)

    def pause(self):
        if self.job:
            self.root.after_cancel(self.job)

    def on_speed_changed(self, value):
        self.speed = 1 / value

    def on_state_changed(self, value):
        if value == 1:
            self.pause()
        elif value == 2:
            self.play()
 def GET(self):
   you = get_you()
   games = Game.all()
   users = User.all()
   return render("index", games=games, users=users, you=get_you())