Esempio n. 1
0
    def setUp(self):

        # Instantiate a User

        self.azura_name = "Azura"
        self.azura_location = (40.73517750328247, -74.00683227856715)
        self.azura_id = "1"

        self.azura_user_obj = models.User(user_id=self.azura_id,
                                          name=self.azura_name,
                                          current_location=self.azura_location)

        # Add a taste for updating
        self.existing_taste_name = "dawn"
        self.existing_taste_strength = 0.9
        self.existing_taste_datapoints = 3
        self.azura_user_obj._tastes[self.existing_taste_name] = [
            self.existing_taste_strength, self.existing_taste_datapoints
        ]

        # Instantiate second user for __eq__
        self.boethiah_name = "Boethiah"
        self.boethiah_location = (40.76346250260515, -73.98013893542904)
        self.boethiah_id = "2"
        self.boethiah_user_obj = models.User(
            user_id=self.boethiah_id,
            name=self.boethiah_name,
            current_location=self.boethiah_location)

        # Instantiate third user
        self.hircine_name = "Hircine"
        self.hircine_location = (40.76525023033338, -73.96722141608099)
        self.hircine_id = "3"
        self.hircine_user_obj = models.User(
            user_id=self.hircine_id,
            name=self.hircine_name,
            current_location=self.hircine_location)

        # Create a match between Azura and each of the other two users
        self.match_obj_azura_boethiah = models.Match(
            user1=self.azura_user_obj, user2=self.boethiah_user_obj)
        self.azura_user_obj.add_match(self.match_obj_azura_boethiah.id,
                                      self.match_obj_azura_boethiah.timestamp,
                                      self.boethiah_user_obj.id)
        # Manually add to azura object's matches

        self.match_obj_hircine_azura = models.Match(  # Have Azura be user2 for this one
            user1=self.hircine_user_obj,
            user2=self.azura_user_obj)
        # Manually add to azura object's matches
        self.azura_user_obj.add_match(
            self.match_obj_hircine_azura.id,
            self.match_obj_hircine_azura.timestamp + 1,
            self.hircine_user_obj.id)
Esempio n. 2
0
    def test_hash_output_consistent_regardless_of_user_order(self):
        """Does Match(Alice, Bob) hash to same value as Match(Bob, Alice)?"""
        expected_hash = hash(self.matchGrortDrobb)
        match_obj_flipped_members = models.Match(
            self.userDrobb, self.userGrort
        )  # Reverse the user1 and user2 roles from those in setUp
        assert match_obj_flipped_members.user1 == self.matchGrortDrobb.user2 and match_obj_flipped_members.user2 == self.matchGrortDrobb.user1
        actual_hash = hash(match_obj_flipped_members)
        self.assertEqual(actual_hash, expected_hash)

        # Test same for the public id property attribute
        expected_id = self.matchGrortDrobb.id
        actual_id = match_obj_flipped_members.id
        self.assertEqual(actual_id, expected_id)
Esempio n. 3
0
def main() -> models.Result:
    matches = {}
    for path in Path('.').glob('*.log'):
        content = path.read_text()
        soup = BeautifulSoup(content, 'lxml')
        print(f'{len(soup.find_all("table"))} matches')
        for table in soup.find_all('table'):
            match = models.Match()
            set_match_attr(match, 'id', table.tr.th.string.split(' ')[1])
            data = table.find_all('td')
            for key, value in zip(data[::2], data[1::2]):
                set_match_attr(match, str(key.string), str(value.string))
            if match.id in matches:
                print(f'ID {match.id} already set')
            matches[match.id] = match

    return compress(matches)
Esempio n. 4
0
    def setUp(self):

        self.db = DatabaseAPI()  # Testing on the real DB, to have restaurants
        # TODO: script that populates the test DBs with realistic restaurants en masse. And/or separate JSON map for this test
        #   (pointing to same test DB filenames for some like users, different one for datespots)
        self.user_data = model_interfaces.UserModelInterface()

        # Need user objects to instantiate a Match
        grortName = "Grort"
        self.grortCurrentLocation = (40.746667, -74.001111)
        grort_data = {
            "name": grortName,
            "current_location": self.grortCurrentLocation
        }
        self.grort_user_id = self.db.post_object({
            "object_model_name": "user",
            "object_data": grort_data
        })
        self.userGrort = self.user_data.lookup_obj(self.grort_user_id)

        drobbName = "Drobb"
        self.drobbCurrentLocation = (40.767376158866554, -73.98615327558278)
        drobb_data = {
            "name": drobbName,
            "current_location": self.drobbCurrentLocation
        }
        self.drobb_user_id = self.db.post_object({
            "object_model_name": "user",
            "object_data": drobb_data
        })
        self.userDrobb = self.user_data.lookup_obj(self.drobb_user_id)

        # distance should be approx 2610m
        # midpoint should be circa (40.75827478958617, -73.99310556132602)

        self.matchGrortDrobb = models.Match(self.userGrort, self.userDrobb)
        assert self.matchGrortDrobb.midpoint is not None

        # Get the candidates list that the DatabaseAPI would be giving to Match:
        self.candidate_datespots_list = self.db.get_datespots_near(
            {"location": self.matchGrortDrobb.midpoint})
Esempio n. 5
0
 def getMatches(self,
                groupId='',
                studentId='',
                matchId='',
                active=None,
                limit=10,
                index=0):
     cursor = self.connection.cursor()
     get_query = '''SELECT matches.groupId,
                         matches.studentId,
                         matches.matchId,
                         matches.active,
                         users.firstName,
                         users.lastName
                 FROM matches
                 INNER JOIN users
                 ON matches.studentId = users.userGId
                 WHERE (matches.groupId= %s OR matches.studentId= %s OR matches.matchId =%s) OR matches.active = %s 
                 LIMIT %s OFFSET %s 
              '''
     cursor.execute(get_query,
                    (groupId, studentId, matchId, active, limit, index))
     matches = cursor.fetchall()
     if not matches:
         cursor.close()
         return None
     match_list = []
     for match in matches:
         m = models.Match(groupId=match[0],
                          studentId=match[1],
                          matchId=match[2],
                          active=match[3],
                          firstName=match[4],
                          lastName=match[5])
         match_list.append(m)
     cursor.close()
     return match_list
Esempio n. 6
0
 def read_tournament(self, json):
     # Se recuperan los datos del JSON
     league = models.League(self.league_name)
     tournament = models.Tournament(discord_id=self.discord_id,
                                    tournament_name=self.tournament)
     # Ultima actualizacion de goblin spy
     tournament.last_update = json["Info"]["rows"][0][3]
     # Se guardan las instancias de equipos
     all_teams = {}
     ranking = models.Ranking()
     # Lista de los equipos inscritos ordenados por puntuación
     ranking_data = json["LeagueStandings"]["rows"]
     for team_data in ranking_data:
         # team[10] es la casilla del coachbame. Get_Coach revisa si el nombre está inscrito en la DB de usuarios
         recover_coach = self.get_coach(team_data[10])
         coach = models.Coach(team_data[10], team_data[10])
         if recover_coach != team_data[10]:
             coach.display_name = recover_coach[0]
             coach.user_discord_id = recover_coach[1]
         # Se guarda la raza como el emoticono de la raza (bb<race_name>)
         team = models.Team(coach=coach,
                            team_name=team_data[17],
                            race=bloodBowl.Get_Race(int(team_data[16])),
                            wins=team_data[22],
                            draws=team_data[23],
                            loses=team_data[24],
                            rank=team_data[18],
                            td=team_data[25])
         ranking.add_team(team)
         all_teams[team.team_name] = team
     # Primero se recuperan los datos del histórico. Después, si la competición no es de tipo escalera y tiene partidos programados, se recuperan estos, incluidos los ya jugados
     # NOTA: Se crea una nueva instancia de un mismo partido porque en el json no hay ningun identificador comun entre Matches y Schedule
     # Recuoperación del histórico
     tournament.ranking = ranking
     history = models.History()
     matches_data = json["Matches"]["rows"]
     for match_data in matches_data:
         match = models.Match(local_team=all_teams[match_data[14]],
                              visitor_team=all_teams[match_data[17]],
                              local_score=match_data[15],
                              visitor_score=match_data[16],
                              status="played",
                              played_time=match_data[4])
         history.add_match(match)
     tournament.match_history = history
     schedule_data = json["Schedule"]["rows"]
     if schedule_data == None or len(schedule_data) == 0:
         tournament_type = "ladder"
     else:
         tournament_type = schedule_data[0][7]
         schedule = models.Schedule()
         for match_data in schedule_data:
             match = models.Match(local_team=all_teams[match_data[19]],
                                  visitor_team=all_teams[match_data[25]],
                                  local_score=match_data[29],
                                  visitor_score=match_data[30],
                                  status=match_data[10])
             if match.status == "scheduled":
                 if schedule.current_round == 0:
                     schedule.current_round = match_data[8]
                 # Recupera si los usuarios de dicord han establecido una hora para jugar
                 match.programmed_time = self.get_programmed_time(match)
             schedule.add_match(match_data[8], match)
         tournament.schedule = schedule
     league.add_tournament(tournament)
     return league
Esempio n. 7
0
def runGame():

    # get the right database for the starting players
    db_creation.clean_db()
    db_creation.new_db_empty()
    db_creation.fill_db()

    # set the stage
    turn = 'player'
    current_match = models.Match()
    current_match.match_number = 1
    current_match.match_teams = ["Rage", "Peace"]
    current_match.human_team = "Rage"
    starting_field = models.Field()
    starting_gui = models.Gui()

    current_field, current_gui = drawBoard(starting_field, starting_gui)

    while True:  # main game loop
        # Keep looping for player and computer's turns.
        player_move_commit_list = []
        computer_move_commit_list = []
        if turn == 'player':
            # Player's turn:
            moves_committed = False
            moves_commit_list = []
            while moves_committed is False:
                # Keep looping until the player submits three moves
                checkForQuit()
                for event in pygame.event.get():  # event handling loop
                    if event.type == MOUSEBUTTONUP:
                        # Handle mouse click events
                        mousex, mousey = event.pos
                        hex_id, button_name = getSpaceClicked(
                            mousex, mousey, current_field, current_gui)
                        player_selected = check_click(hex_id)

                        if current_gui.action_selection is False and player_selected is not None:
                            # print(hex_id,models.Player(player_selected).player_name)
                            current_gui.player_highlight = True
                            current_gui.player_id_selected = player_selected
                            if player_selected in models.Team(
                                    current_match.human_team).player_list:
                                current_gui.action_menu = True
                                current_gui.top_message = "Choose an action for " + models.Player(
                                    player_selected).player_name
                        elif button_name is not None:
                            # draw possible hexes for an action
                            current_gui.possible_hexes = action_possible_hexes(
                                button_name, current_gui, current_field)
                            if len(current_gui.possible_hexes) > 0:
                                current_gui.action_selection = True
                                current_gui.action_to_do = button_name
                                current_gui.top_message = "Choose a hex for " + button_name
                            # TODO add back button or someway to cancel selection
                        elif hex_id in current_gui.possible_hexes and current_gui.action_selection is True:
                            # after hex selected
                            move_commit_x = action_commit(hex_id, current_gui)
                            moves_commit_list.append(move_commit_x)
                            current_gui.action_selection = False
                            current_gui.action_to_do = None
                            current_gui.possible_hexes = []
                            current_gui.player_id_selected = None
                            current_gui.player_highlight = False
                            m2 = len(
                                models.Team(
                                    current_match.human_team).player_list)
                            m1 = len(moves_commit_list)
                            current_gui.top_message = str(
                                m1) + " out of " + str(m2) + " moves committed"

                # update drawing of game board
                current_field, current_gui = drawBoard(current_field,
                                                       current_gui)

                # update display
                MAINCLOCK.tick(FPS)
                pygame.display.update()

                # checks if all moves_committed
                if len(moves_commit_list) >= len(
                        models.Team(current_match.human_team).player_list):
                    moves_committed = True
                    current_gui.top_message = "Player's turn complete. Computer's turn."
                    player_move_commit_list = moves_commit_list

            # End the turn
        else:
            # Computer's turn:

            current_field, current_gui = drawBoard(current_field, current_gui)

            # Make it look like the computer is thinking by pausing a bit.
            pauseUntil = time.time() + random.randint(5, 15) * 0.1
            while time.time() < pauseUntil:
                pygame.display.update()

            current_gui.top_message = "Computer turn complete. Human's turn"

        current_field = implement_moves(current_field, player_move_commit_list)

        # update board
        current_field, current_gui = drawBoard(current_field, current_gui)

        # update display
        MAINCLOCK.tick(FPS)
        pygame.display.update()

        # Only set for the player's turn if they can make a move.
        turn = 'player'