Exemplo n.º 1
0
    def messages(self, gamedb: Database) -> List[SMSEventMessage]:
        player_messages = []
        losing_teams = gamedb.stream_teams(from_tribe=self.losing_tribe)
        winning_teams = gamedb.stream_teams(from_tribe=self.winning_tribe)

        for team in losing_teams:
            losing_players = []

            # TODO(brandon): optimize this.
            for player in gamedb.list_players(from_team=team):
                losing_players.append(player)

            options_map = messages.players_as_formatted_options_map(
                players=losing_players)

            for player in losing_players:
                gamedb.ballot(player_id=player.id,
                              options=options_map.options,
                              challenge_id=None)

            # NOTE: UX isn't perfect here because we'll show the player's own name
            # as an option to vote out. For MVP this helps with scale because the alternative
            # requires sending a different message to every player (as opposed to every team)
            # which is about a 5x cost increase for SMS.
            player_messages.append(
                SMSEventMessage(
                    content=messages.
                    NOTIFY_MULTI_TRIBE_COUNCIL_EVENT_LOSING_MSG_FMT.format(
                        header=messages.game_sms_header(gamedb=gamedb),
                        tribe=self.losing_tribe.name,
                        time=self.game_options.game_schedule.
                        localized_time_string(self.game_options.game_schedule.
                                              daily_tribal_council_end_time),
                        options=options_map.formatted_string),
                    recipient_phone_numbers=[
                        p.phone_number for p in losing_players
                    ]))

        winning_player_phone_numbers = []
        for team in winning_teams:
            winning_players = gamedb.list_players(from_team=team)
            winning_player_phone_numbers.extend(
                [p.phone_number for p in winning_players])

        player_messages.append(
            SMSEventMessage(
                content=messages.
                NOTIFY_MULTI_TRIBE_COUNCIL_EVENT_WINNING_MSG_FMT.format(
                    header=messages.game_sms_header(gamedb=gamedb),
                    winning_tribe=self.winning_tribe.name,
                    losing_tribe=self.losing_tribe.name,
                    time=self.game_options.game_schedule.localized_time_string(
                        self.game_options.game_schedule.
                        daily_tribal_council_end_time),
                    challenge_time=self.game_options.game_schedule.
                    localized_time_string(self.game_options.game_schedule.
                                          daily_challenge_start_time)),
                recipient_phone_numbers=winning_player_phone_numbers))
        return player_messages
Exemplo n.º 2
0
    def messages(self, gamedb: Database) -> List[SMSEventMessage]:
        player_messages = []
        for team in self.losing_teams:
            losing_players = []
            for losing_player in gamedb.list_players(from_team=team):
                losing_players.append(losing_player)

            # NOTE: UX isn't perfect here because we'll show the player's own name
            # as an option to vote out. For MVP this helps with scale because the alternative
            # requires sending a different message to every player (as opposed to every team)
            # which is about a 5x cost increase for SMS.
            r = [p.phone_number for p in losing_players]
            player_messages.append(
                SMSEventMessage(
                    content=messages.NOTIFY_SINGLE_TRIBE_COUNCIL_EVENT_LOSING_MSG_FMT.format(
                        header=messages.VIR_US_SMS_HEADER,
                        time=self.game_options.game_schedule.localized_time_string(
                            self.game_options.game_schedule.daily_tribal_council_end_time
                        ),
                        options=messages.players_as_formatted_options_list(
                            # TODO(brandon): exclude the voter from the options list of players
                            # to vote out.
                            players=losing_players
                        )
                    ),
                    recipient_phone_numbers=r
                )
            )

        winning_player_phone_numbers = []
        for team in self.winning_teams:
            winning_players = gamedb.list_players(from_team=team)
            winning_player_phone_numbers.extend(
                [p.phone_number for p in winning_players]
            )

        player_messages.append(
            SMSEventMessage(
                content=messages.NOTIFY_SINGLE_TRIBE_COUNCIL_EVENT_WINNING_MSG_FMT.format(
                    header=messages.VIR_US_SMS_HEADER,
                    time=self.game_options.game_schedule.localized_time_string(
                        self.game_options.game_schedule.daily_tribal_council_end_time
                    ),
                    challenge_time=self.game_options.game_schedule.localized_time_string(
                        self.game_options.game_schedule.daily_challenge_start_time
                    )
                ),
                recipient_phone_numbers=winning_player_phone_numbers
            )
        )
        return player_messages
Exemplo n.º 3
0
 def messages(self, gamedb: Database) -> List[SMSEventMessage]:
     player_messages = []
     team = gamedb.team_from_id(id=self.player.team_id)
     teammate_phone_numbers = [p.phone_number for p in gamedb.list_players(
         from_team=team) if p.id != self.player.id]
     player_messages.append(
         SMSEventMessage(
             content=messages.NOTIFY_PLAYER_VOTED_OUT_TEAM_MSG_FMT.format(
                 header=messages.VIR_US_SMS_HEADER,
                 player=messages.format_tiktok_username(
                     self.player.tiktok),
                 time=self.game_options.game_schedule.localized_time_string(
                     self.game_options.game_schedule.daily_challenge_start_time
                 )),
             recipient_phone_numbers=teammate_phone_numbers
         )
     )
     player_messages.append(
         SMSEventMessage(
             content=messages.NOTIFY_PLAYER_VOTED_OUT_MSG_FMT.format(
                 header=messages.VIR_US_SMS_HEADER
             ),
             recipient_phone_numbers=[self.player.phone_number]
         )
     )
     return player_messages
Exemplo n.º 4
0
    def _run_single_tribe_council(self, winning_teams: List[Team], losing_teams: List[Team],
                                  gamedb: Database, engine: Engine):

        # announce winner and tribal council for losing teams
        gamedb.clear_votes()
        engine.add_event(events.NotifySingleTribeCouncilEvent(
            game_id=self._game_id, game_options=self._options,
            winning_teams=winning_teams, losing_teams=losing_teams))
        tribal_council_start_timestamp = _unixtime()

        # wait for votes
        while (((_unixtime() - tribal_council_start_timestamp)
                < self._options.single_tribe_council_time_sec) and not self._stop.is_set()):
            log_message("Waiting for tribal council to end.")
            time.sleep(self._options.game_wait_sleep_interval_sec)

        # count votes
        for team in losing_teams:
            voted_out_player = self._get_voted_out_player(
                team=team, gamedb=gamedb)
            if voted_out_player:
                gamedb.deactivate_player(player=voted_out_player)
                log_message("Deactivated player {}.".format(voted_out_player))
                engine.add_event(events.NotifyPlayerVotedOutEvent(game_id=self._game_id, game_options=self._options,
                                                                  player=voted_out_player))
            else:
                log_message("For some reason no one got voted out...")
                log_message("Players = {}.".format(
                    pprint.pformat(gamedb.list_players(from_team=team))))

        # notify all players of what happened at tribal council
        engine.add_event(
            events.NotifyTribalCouncilCompletionEvent(game_id=self._game_id, game_options=self._options))
Exemplo n.º 5
0
    def _run_single_team_council(self, team: Team, losing_players: List[Player], gamedb: Database, engine: Engine):
        # announce winner and tribal council for losing teams
        gamedb.clear_votes()

        winning_player = [player for player in gamedb.list_players(
            from_team=team) if player not in losing_players][0]
        engine.add_event(events.NotifySingleTeamCouncilEvent(game_id=self._game_id, game_options=self._options,
                                                             winning_player=winning_player, losing_players=losing_players))
        tribal_council_start_timestamp = _unixtime()

        # wait for votes
        while (((_unixtime() - tribal_council_start_timestamp)
                < self._options.single_team_council_time_sec) and not self._stop.is_set()):
            log_message("Waiting for tribal council to end.")
            time.sleep(self._options.game_wait_sleep_interval_sec)

        # count votes
        voted_out_player = self._get_voted_out_player(team=team, gamedb=gamedb)
        if voted_out_player:
            gamedb.deactivate_player(player=voted_out_player)
            log_message("Deactivated player {}.".format(voted_out_player))
            engine.add_event(events.NotifyPlayerVotedOutEvent(game_id=self._game_id, game_options=self._options,
                                                              player=voted_out_player))

        # notify all players of what happened at tribal council
        engine.add_event(
            events.NotifyTribalCouncilCompletionEvent(game_id=self._game_id, game_options=self._options))
Exemplo n.º 6
0
    def _play_single_team(self, team: Team, gamedb: Database, engine: Engine) -> List[Player]:
        while team.size > self._options.target_finalist_count:
            challenge = self._get_challenge(gamedb=gamedb)
            self._run_challenge(challenge=challenge,
                                gamedb=gamedb, engine=engine)
            losing_players = self._score_entries_top_k_players(
                team=team, challenge=challenge, gamedb=gamedb, engine=engine)
            self._run_single_team_council(
                team=team, losing_players=losing_players, gamedb=gamedb, engine=engine)

        return gamedb.list_players(from_team=team)
Exemplo n.º 7
0
    def _merge_teams(self, target_team_size: int, tribe: Tribe, gamedb: Database, engine: Engine):
        # team merging is only necessary when the size of the team == 2
        # once a team size == 2, it should be merged with another team. the optimal
        # choice is to keep team sizes as close to the intended size as possible

        # find all teams with size = 2, these players need to be merged
        small_teams = gamedb.stream_teams(
            from_tribe=tribe, team_size_predicate_value=2)
        merge_candidates = Queue()

        for team in small_teams:
            log_message("Found team of 2. Deacticating team {}.".format(team))

            # do not deactivate the last active team in the tribe
            if gamedb.count_teams(from_tribe=tribe, active_team_predicate_value=True) > 1:
                gamedb.deactivate_team(team)

            for player in gamedb.list_players(from_team=team):
                log_message("Adding merge candidate {}.".format(player))
                merge_candidates.put(player)

        sorted_teams = gamedb.stream_teams(
            from_tribe=tribe, order_by_size=True, descending=False)

        log_message("Redistributing merge candidates...")
        # round robin redistribution strategy
        # simplest case, could use more thought.
        visited = {}
        while not merge_candidates.empty() and sorted_teams:
            for team in sorted_teams:
                other_options_available = team.id not in visited
                visited[team.id] = True

                if (team.size >= target_team_size and other_options_available):
                    log_message("Team {} has size >= target {} and other options are available. "
                                "Continuing search...".format(team, target_team_size))
                    continue

                player = merge_candidates.get()
                if player.team_id == team.id:
                    continue

                log_message("Merging player {} from team {} into team {}.".format(
                    player, player.team_id, team.id))
                player.team_id = team.id
                team.size = team.size + 1
                gamedb.save(team)
                gamedb.save(player)

                # notify player of new team assignment
                engine.add_event(events.NotifyTeamReassignmentEvent(game_id=self._game_id, game_options=self._options, player=player,
                                                                    team=team))
Exemplo n.º 8
0
 def messages(self, gamedb: Database) -> List[SMSEventMessage]:
     return [
         SMSEventMessage(
             content=messages.NOTIFY_IMMUNITY_AWARDED_EVENT_MSG_FMT.format(
                 header=messages.VIR_US_SMS_HEADER,
                 date=self.game_options.game_schedule.tomorrow_localized_string,
                 time=self.game_options.game_schedule.localized_time_string(
                     self.game_options.game_schedule.daily_challenge_start_time
                 )
             ),
             recipient_phone_numbers=[
                 p.phone_number for p in gamedb.list_players(from_team=self.team)]
         )
     ]
Exemplo n.º 9
0
    def _score_entries_top_k_players(self, team: Team, challenge: Challenge,
                                     gamedb: Database,
                                     engine: Engine) -> List[Player]:
        player_scores = {}
        top_scores = list()
        losing_players = list()
        winning_player_ids = set()
        entries = gamedb.stream_entries(from_team=team,
                                        from_challenge=challenge)

        with ThreadPoolExecutor(max_workers=self._options.
                                engine_worker_thread_count) as executor:
            executor.submit(self._score_entries_top_k_players_fn,
                            entries=entries,
                            challenge=challenge,
                            score_dict=player_scores,
                            gamedb=gamedb,
                            engine=engine)

        for player_id, score in player_scores.items():
            heapq.heappush(top_scores, (score, player_id))

        # note that the default python heap pops in ascending order,
        # so the rank here is actually worst to best.
        num_scores = len(top_scores)
        if num_scores == 1:
            raise GameError(
                "Unable to rank losing players with team size = 1.")
        else:
            for rank in range(num_scores):
                score, player_id = heapq.heappop(top_scores)
                log_message(message="Player {} rank {} with score {}.".format(
                    player_id, rank, score),
                            game_id=self._game_id)

                # all but the highest scorer lose
                if rank < (num_scores - 1):
                    losing_players.append(gamedb.player_from_id(player_id))
                else:
                    winning_player_ids.add(player_id)

        # players that did not score also lose.
        losing_player_ids = set([p.id for p in losing_players])
        for player in gamedb.list_players(from_team=team):
            if (player.id
                    not in losing_player_ids) and (player.id
                                                   not in winning_player_ids):
                losing_players.append(player)
        return losing_players
Exemplo n.º 10
0
 def messages(self, gamedb: Database) -> List[SMSEventMessage]:
     team_players = gamedb.list_players(from_team=self.team)
     return [
         SMSEventMessage(
             content=messages.NOTIFY_TEAM_REASSIGNMENT_EVENT_MSG_FMT.format(
                 header=messages.game_sms_header(gamedb=gamedb),
                 team=messages.players_as_formatted_list(
                     players=team_players),
                 date=self.game_options.game_schedule.
                 tomorrow_localized_string,
                 time=self.game_options.game_schedule.localized_time_string(
                     self.game_options.game_schedule.
                     daily_challenge_start_time)),
             recipient_phone_numbers=[self.player.phone_number])
     ]
Exemplo n.º 11
0
    def _run_single_team_council(self, team: Team,
                                 losing_players: List[Player],
                                 gamedb: Database, engine: Engine):
        self._wait_for_tribal_council_start_time()

        # announce winner and tribal council for losing teams
        gamedb.clear_votes()

        winning_players = [
            player for player in gamedb.list_players(from_team=team)
            if player not in losing_players
        ]
        if len(winning_players) > 0:
            winning_player = winning_players[0]
        else:
            engine.stop()
            raise GameError(
                "Unable to determine a winning player for the challenge. Have any entries been submitted?"
            )

        engine.add_event(
            events.NotifySingleTeamCouncilEvent(game_id=self._game_id,
                                                game_options=self._options,
                                                winning_player=winning_player,
                                                losing_players=losing_players))
        self._wait_for_tribal_council_end_time()

        # count votes
        voted_out_player = self._get_voted_out_player(team=team, gamedb=gamedb)
        if voted_out_player:
            gamedb.deactivate_player(player=voted_out_player)
            log_message(
                message="Deactivated player {}.".format(voted_out_player),
                game_id=self._game_id)
            engine.add_event(
                events.NotifyPlayerVotedOutEvent(game_id=self._game_id,
                                                 game_options=self._options,
                                                 player=voted_out_player))

        # notify all players of what happened at tribal council
        engine.add_event(
            events.NotifyTribalCouncilCompletionEvent(
                game_id=self._game_id, game_options=self._options))
Exemplo n.º 12
0
    def _run_single_tribe_council(self, winning_teams: List[Team],
                                  losing_teams: List[Team], gamedb: Database,
                                  engine: Engine):
        self._wait_for_tribal_council_start_time()
        # keep top K teams

        # announce winner and tribal council for losing teams
        gamedb.clear_votes()
        engine.add_event(
            events.NotifySingleTribeCouncilEvent(game_id=self._game_id,
                                                 game_options=self._options,
                                                 winning_teams=winning_teams,
                                                 losing_teams=losing_teams))
        self._wait_for_tribal_council_end_time()

        # count votes
        for team in losing_teams:
            voted_out_player = self._get_voted_out_player(team=team,
                                                          gamedb=gamedb)
            if voted_out_player:
                gamedb.deactivate_player(player=voted_out_player)
                log_message(
                    message="Deactivated player {}.".format(voted_out_player),
                    game_id=self._game_id)
                engine.add_event(
                    events.NotifyPlayerVotedOutEvent(
                        game_id=self._game_id,
                        game_options=self._options,
                        player=voted_out_player))
            else:
                log_message(message="For some reason no one got voted out...",
                            game_id=self._game_id)
                log_message(message="Players = {}.".format(
                    pprint.pformat(gamedb.list_players(from_team=team))),
                            game_id=self._game_id)

        # notify all players of what happened at tribal council
        engine.add_event(
            events.NotifyTribalCouncilCompletionEvent(
                game_id=self._game_id, game_options=self._options))
Exemplo n.º 13
0
    def _merge_teams(self, target_team_size: int, tribe: Tribe,
                     gamedb: Database, engine: Engine):
        with engine:
            # team merging is only necessary when the size of the team == 2
            # once a team size == 2, it should be merged with another team, because
            # a self preservation vote lands in a deadlock. in general, the optimal
            # choice is to keep team sizes as close to the intended size as possible
            # up until a merge becomes necessary.

            # find all teams with size == 2, these players need to be merged
            small_teams = gamedb.stream_teams(from_tribe=tribe,
                                              team_size_predicate_value=2)
            merge_candidates = Queue()

            for team in small_teams:
                # do not deactivate the last active team in the tribe
                count_teams = gamedb.count_teams(
                    from_tribe=tribe, active_team_predicate_value=True)
                if count_teams > 1:
                    log_message(
                        message="Found team of 2. Deactivating team {}.".
                        format(team),
                        game_id=self._game_id)
                    gamedb.deactivate_team(team)
                for player in gamedb.list_players(from_team=team):
                    log_message(
                        message="Adding merge candidate {}.".format(player),
                        game_id=self._game_id)
                    merge_candidates.put(player)

            sorted_teams = gamedb.stream_teams(from_tribe=tribe,
                                               order_by_size=True,
                                               descending=False)

            log_message(message="Redistributing merge candidates...",
                        game_id=self._game_id)
            # round robin redistribution strategy
            # simplest case, could use more thought.
            visited = {}
            while not merge_candidates.empty() and sorted_teams:
                for team in itertools.cycle(sorted_teams):
                    team.count_players = _team_count_players(team, gamedb)
                    other_options_available = team.id not in visited
                    visited[team.id] = True

                    if (team.count_players >= target_team_size
                            and other_options_available):
                        log_message(
                            message=
                            "Team {} has size >= target {} and other options are available. "
                            "Continuing search...".format(
                                team, target_team_size),
                            game_id=self._game_id)
                        continue

                    player = None
                    try:
                        player = merge_candidates.get_nowait()
                    except Empty:
                        log_message(message="Merge candidates empty.")
                        return

                    if player.team_id == team.id:
                        log_message(
                            message=
                            f"Player {str(player)} already on team {str(team)}. Continuing."
                        )
                        continue

                    log_message(
                        message="Merging player {} from team {} into team {}.".
                        format(player, player.team_id, team.id),
                        game_id=self._game_id)
                    player.team_id = team.id
                    team.count_players += 1
                    gamedb.save(team)
                    gamedb.save(player)

                    # notify player of new team assignment
                    engine.add_event(
                        events.NotifyTeamReassignmentEvent(
                            game_id=self._game_id,
                            game_options=self._options,
                            player=player,
                            team=team))