Пример #1
0
def battle(user, robot1_id, robot2_id):
    if robot1_id == robot2_id:
        return {'error': True, 'message': 'Robots cannot battle themselves.'}
    robot1 = db_manager.get_robot_by_id(robot1_id)
    if robot1['user_id'] != user:
        return {'error':True, 'message':'Auth error.'}
    robot2 = db_manager.get_robot_by_id(robot2_id)
    if robot1['user_id'] == robot2['user_id']:
        return {'error': True, 'message': 'Users cannot battle themselves.'}
    result = run_battle(robot1, robot2)
    result['opposer'] = robot1['user_id'] 
    result['opposee'] = robot2['user_id'] 
    
    if result['error'] == False:
        rating = (robot1['score'], robot2['score'])
        if result['scores'][0] > result['scores'][1]:
            rating = rate_1vs1(robot1['score'], robot2['score'])
        if result['scores'][1] > result['scores'][0]:
            rating = rate_1vs1(robot2['score'], robot1['score'])

        db_manager.update_robot_score(robot1, int(round(rating[0])))
        db_manager.update_robot_score(robot2, int(round(rating[1]))) 

        timestamp = int(time.time())
        battle_id = str(uuid.uuid4())
        db_manager.store_battle(battle_id, user, robot2['user_id'], robot1_id, robot2_id, robot1['robot_name'], robot2['robot_name'], timestamp, result['scores'][0], result['scores'][1], json.dumps(result['history']))
    return result
Пример #2
0
def GetChangeScore(myScore, winScore, loseScore, uppercent, downpercent):

    sup = abs(myScore - elo.rate_1vs1(myScore, winScore)[0]) * uppercent

    sdown = abs(myScore - elo.rate_1vs1(loseScore, myScore)[1]) * downpercent

    return sup - sdown
Пример #3
0
def update_elo(elo_list, i0, i1, res):
    if res[0] > 0:
        elo_list[i0], elo_list[i1] = elo.rate_1vs1(elo_list[i0], elo_list[i1])
    elif res[0] == 0.5:
        elo_list[i0], elo_list[i1] = elo.rate_1vs1(elo_list[i0], elo_list[i1],
                                                   True)
    else:
        elo_list[i1], elo_list[i0] = elo.rate_1vs1(elo_list[i1], elo_list[i0])
    return elo_list
Пример #4
0
    def calculate_score(self, comparison_pairs):
        """
        Calculate scores for a set of comparison_pairs
        :param comparison_pairs: array of comparison_pairs
        :return: dictionary key -> ScoredObject
        """
        self.storage = {}
        self.opponents = {}
        elo.setup()

        keys = self.get_keys_from_comparison_pairs(comparison_pairs)
        # create default ratings for every available key
        for key in keys:
            self.storage[key] = ScoredObject(
                key=key,
                score=elo.Rating(),
                variable1=elo.Rating(),
                variable2=None,
                rounds=0,
                opponents=0,
                wins=0,
                loses=0
            )
            self.opponents[key] = set()

        # calculate rating for every match
        for comparison_pair in comparison_pairs:
            key1 = comparison_pair.key1
            key2 = comparison_pair.key2
            winner = comparison_pair.winner

            # skip incomplete comparisosns
            if winner is None:
                self._update_rounds_only(key1)
                self._update_rounds_only(key2)
                continue

            r1 = self.storage[key1].score
            r2 = self.storage[key2].score

            winner_key1 = winner == ComparisonWinner.key1
            winner_key2 = winner == ComparisonWinner.key2

            if winner_key1:
                r1, r2 = elo.rate_1vs1(r1, r2)
            elif winner_key2:
                r2, r1 = elo.rate_1vs1(r2, r1)
            elif winner == ComparisonWinner.draw:
                r1, r2 = elo.rate_1vs1(r1, r2, drawn=True)
            else:
                raise InvalidWinnerException

            self._update_rating(key1, r1, key2, winner_key1, winner_key2)
            self._update_rating(key2, r2, key1, winner_key2, winner_key1)

        # return comparison results
        return self.storage
Пример #5
0
def update_elo_2(agent_list, elo_list, i0, i1, res):
    #print(agent_list, elo_list)
    if res[0] > 0:
        agent_list[i0], _ = elo.rate_1vs1(agent_list[i0], elo_list[i1])
    elif res[0] == 0.5:
        agent_list[i0], _ = elo.rate_1vs1(agent_list[i0], elo_list[i1], True)
    else:
        _, agent_list[i0] = elo.rate_1vs1(elo_list[i1], agent_list[i0])
    return agent_list
Пример #6
0
 def update_and_return_elo(self, fight_date, opponent_id, f_dict):
     fight = self.fight_info_dict[fight_date]
     opponent = f_dict[opponent_id]
     opponent_elo = opponent.get_elo(fight_date, f_dict)
     if fight['result'].lower() == 'win':
         result = rate_1vs1(self.elo, opponent_elo)
         self.elo = result[0]
     elif fight['result'].lower() == 'loss':
         result = rate_1vs1(opponent_elo, self.elo)
         self.elo = result[1]
Пример #7
0
    def calculate_score(self, comparison_pairs):
        """
        Calculate scores for a set of comparison_pairs
        :param comparison_pairs: array of comparison_pairs
        :return: dictionary key -> ScoredObject
        """
        self.storage = {}
        self.opponents = {}
        elo.setup()

        keys = self.get_keys_from_comparison_pairs(comparison_pairs)
        # create default ratings for every available key
        for key in keys:
            self.storage[key] = ScoredObject(key=key,
                                             score=elo.Rating(),
                                             variable1=elo.Rating(),
                                             variable2=None,
                                             rounds=0,
                                             opponents=0,
                                             wins=0,
                                             loses=0)
            self.opponents[key] = set()

        # calculate rating for every match
        for comparison_pair in comparison_pairs:
            key1 = comparison_pair.key1
            key2 = comparison_pair.key2
            winner = comparison_pair.winner

            # skip incomplete comparisosns
            if winner is None:
                self._update_rounds_only(key1)
                self._update_rounds_only(key2)
                continue

            r1 = self.storage[key1].score
            r2 = self.storage[key2].score

            winner_key1 = winner == ComparisonWinner.key1
            winner_key2 = winner == ComparisonWinner.key2

            if winner_key1:
                r1, r2 = elo.rate_1vs1(r1, r2)
            elif winner_key2:
                r2, r1 = elo.rate_1vs1(r2, r1)
            elif winner == ComparisonWinner.draw:
                r1, r2 = elo.rate_1vs1(r1, r2, drawn=True)
            else:
                raise InvalidWinnerException

            self._update_rating(key1, r1, key2, winner_key1, winner_key2)
            self._update_rating(key2, r2, key1, winner_key2, winner_key1)

        # return comparison results
        return self.storage
Пример #8
0
 def do_work(self):
   p1 = self.game[0]
   p2 = self.game[1]
   p1wins = 0
   p2wins = 0
   while True:
     winner = Game([RobotPlayer(0, p1[1]), RobotPlayer(1, p2[1])]).play()
     p1wins += 1 - winner
     p2wins += winner
     if p1wins == first_to:
       return list(zip((p1[0], p2[0]), rate_1vs1(p1[2], p2[2])))
     if p2wins == first_to:
       return list(zip((p2[0], p1[0]), rate_1vs1(p2[2], p1[2])))
Пример #9
0
 def update_elo(self, fight_date):
     fight = self.fight_info_dict[fight_date]
     opponent = f_dict.get(fight['opponent_id'], None)
     if opponent is None:
         opponent_elo = starting_elo
     else:
         opponent_elo = opponent.elo
     if fight['result'].lower() == 'win':
         result = rate_1vs1(self.elo, opponent_elo)
         self.elo = result[0]
     elif fight['result'].lower() == 'loss':
         result = rate_1vs1(opponent_elo, self.elo)
         self.elo = result[1]
Пример #10
0
def compute_score(state, team_1_score, team_2_score, points_difference):
    """
    State contains the outcome of the game between team_1 and team_2.
    It is "WIN" if player 1 wins, "LOSS" if he looses and "DRAW" otherwise.
    """
    # +1 to avoid having a k_factor of 0 when there is a DRAW.
    elo.setup(k_factor=BASE_K_FACTOR * (points_difference + 1))
    if state == "WIN":
        scores = elo.rate_1vs1(team_1_score, team_2_score)
    elif state == "LOSS":
        scores = elo.rate_1vs1(team_2_score, team_1_score)[::-1]
    else:
        scores = elo.rate_1vs1(team_1_score, team_2_score, drawn=True)
    return scores
Пример #11
0
def new_match(request):
    form = NewMatchForm()
    if request.method == 'POST':
        form = NewMatchForm(request.POST)
        if form.is_valid():
            winner = form.cleaned_data.get('winner')
            looser = form.cleaned_data.get('looser')
            elo = rate_1vs1(int(winner.rating), int(looser.rating))

            match = models.Match.objects.create(winner=winner, looser=looser)
            match.save()

            winner.rating = int(round(Decimal(elo[0]), 0))
            winner.save()
            looser.rating = int(round(Decimal(elo[1]), 0))
            looser.save()

            winner_history = models.PlayerHistory.objects.create(
                player=winner, match=match, rating=winner.rating)
            winner_history.save()
            looser_history = models.PlayerHistory.objects.create(
                player=looser, match=match, rating=looser.rating)
            looser_history.save()

            messages.success(
                request,
                "Zarejestrowany mecz.\n Nowe ELO dla {0} {1}: {2}\nNowe ELO dla {3} {4}: {5}\n"
                .format(winner.first_name, winner.last_name, winner.rating,
                        looser.first_name, looser.last_name, looser.rating))
            return redirect(reverse('home'))
        else:
            return render(request, 'new_match.html', {'form': form})

    return render(request, 'new_match.html', {'form': form})
Пример #12
0
def register_game(game: RegisterGameRequest):
    black, white = (player_repository.find_by_name(game.black_player_name),
                    player_repository.find_by_name(game.white_player_name))

    winner, loser = (white, black) if game.result == 'WHITE' else (black,
                                                                   white)

    winner.elo, loser.elo = rate_1vs1(winner.elo,
                                      loser.elo,
                                      drawn=game.result == 'DRAW')

    game = Game(white_player_id=white.id,
                white_player_name=white.name,
                white_player_elo=white.elo,
                black_player_id=black.id,
                black_player_name=black.name,
                black_player_elo=black.elo,
                result=game.result,
                time=datetime.now())

    game = game_repository.save(game)
    player_repository.update(winner)
    player_repository.update(loser)

    return game
Пример #13
0
def settle_victory(winner_id, loser_id):
  winner_score = get_score(winner_id)
  loser_score = get_score(loser_id)
  if None not in (winner_score, loser_score):
    new_scores = elo.rate_1vs1(winner_score, loser_score)
    set_score(winner_id, new_scores[0])
    set_score(loser_id, new_scores[1])
def get_new_score():
    score_res = SPREADSHEET.values().get(spreadsheetId=SPREADSHEET_ID,
                                         range=MENU_RANGE).execute()
    score_values = score_res.get('values', [])

    voting_res = SPREADSHEET.values().get(spreadsheetId=SPREADSHEET_ID,
                                          range=HISTORY_RANGE).execute()
    voting_values = voting_res.get('values', [])

    score = {}
    voting = {}
    if not score_values:
        print('No Menu data found.')
    else:
        for row in score_values:
            score[(row[1])] = float(row[2])

    if not voting_values:
        print('No History data found')
    else:
        for row in voting_values:
            winner = 1 if (row[3] > row[4]) else 2
            loser = 2 if winner == 1 else 1
            is_draw = 1 if row[3] == row[4] else 0
            win_score, lose_score = rate_1vs1(score[row[winner]],
                                              score[row[loser]], is_draw)
            score[row[winner]] = win_score
            score[row[loser]] = lose_score

    return score
Пример #15
0
def ranking(matches, start=1000):
    players = {}

    for match in matches:
        winner = match.winner
        loser = match.loser

        if winner not in players:
            players[winner] = Rating(start)

        if loser not in players:
            players[loser] = Rating(start)

        new_winner, new_loser = rate_1vs1(players[winner], players[loser])
        players[winner] = new_winner
        players[loser] = new_loser

    sorted_players = sorted(players.items(), key=operator.itemgetter(1))
    sorted_players.reverse()
    sorted_players = [{
        'player': p,
        'score': int(s)
    } for p, s in sorted_players]

    return sorted_players
Пример #16
0
    def elo(self, request):
        players = {}
        start = 1000
        matches = Match.objects.order_by('created_at').all()

        for match in matches:
            winner = match.winner.id
            loser = match.loser.id

            if winner not in players:
                players[winner] = Rating(start)

            if loser not in players:
                players[loser] = Rating(start)

            new_winner, new_loser = rate_1vs1(players[winner], players[loser])
            players[winner] = new_winner
            players[loser] = new_loser

        sorted_players = sorted(players.items(), key=operator.itemgetter(1))
        sorted_players.reverse()
        sorted_players = [{
            'player': p,
            'score': int(s)
        } for p, s in sorted_players]

        return JsonResponse(sorted_players, safe=False)
Пример #17
0
    def update_elo_after_match_ends(self, checkmated_player_color):
        if checkmated_player_color == 'red' and self.is_red or checkmated_player_color == 'black' and not self.is_red:
            loser_elo = self.elo
            winner_elo = self.opponent_elo
        else:
            loser_elo = self.opponent_elo
            winner_elo = self.elo
        # host doesn't set opponents elo
        new_winner_elo, new_loser_elo = rate_1vs1(winner_elo, loser_elo)

        # Update the player's elo. Server will update it in the database
        if checkmated_player_color == 'red' and self.is_red or checkmated_player_color == 'black' and not self.is_red:
            new_elo = int(new_loser_elo)
        else:
            new_elo = int(new_winner_elo)
        loser_elo, new_loser_elo = int(loser_elo), int(new_loser_elo)
        winner_elo, new_winner_elo = int(winner_elo), int(new_winner_elo)
        self.elo = new_elo
        print("My new elo is", new_elo)

        # Tell the game screen to open the game over dialog popup
        app = App.get_running_app()
        winner_color = 'red' if checkmated_player_color == 'black' else 'black'
        app.root.ids.game_screen.display_game_over_dialog(
            winner_color, loser_elo, new_loser_elo, winner_elo, new_winner_elo,
            self.nickname, self.opponent_nickname)
        app.root.ids.game_screen.game_is_playing = False
Пример #18
0
 def fight(self, win, loose):
     score_win = self.get_score(win)
     score_loose = self.get_score(loose)
     score_win_final, score_loose_final = elo.rate_1vs1(
         score_win, score_loose)
     self.set_score(win, float(score_win_final))
     self.set_score(loose, float(score_loose_final))
Пример #19
0
 def draw(self, a, b):
     score_a = self.get_score(a)
     score_b = self.get_score(b)
     final_score_a, final_score_b = elo.rate_1vs1(score_a,
                                                  score_b,
                                                  drawn=True)
     self.set_score(a, float(final_score_a))
     self.set_score(b, float(final_score_b))
Пример #20
0
    def updateElo(self, winner_id, loser_id):
        winner = self.users[winner_id]
        loser = self.users[loser_id]

        new_elos = rate_1vs1(winner.elo, loser.elo)

        winner.elo = int(round(new_elos[0]))
        loser.elo = int(round(new_elos[1]))
Пример #21
0
def rate_elo(season):
    scores = defaultdict(lambda: 0)
    results = data[0]
    season_results = results[results.season == season]
    for i, result in season_results.iterrows():
        w, l = result['wteam'], result['lteam']
        scores[w], scores[l] = rate_1vs1(Rating(scores[w]), Rating(scores[l]))
    return scores
Пример #22
0
    def post_match_rating(row):
        ''' Calculate ratings for each player based on the match result '''

        # Player names and pre match ratings
        p1 = row['no1team1']
        p2 = row['no2team1']
        p3 = row['no1team2']
        p4 = row['no2team2']

        p1PreRating = player_rating(p1)
        p2PreRating = player_rating(p2)
        p3PreRating = player_rating(p3)
        p4PreRating = player_rating(p4)

        # Team ratings is used for calculating player ratings only
        t1PreRating = team_rating(p1, p2)
        t2PreRating = team_rating(p3, p4)
        t1PostRating = np.NaN
        t2PostRating = np.NaN

        # Elo rater takes winning team rating as first argument
        if row['team1WinMatch'] == 1:
            t1PostRating, t2PostRating = elo.rate_1vs1(t1PreRating,
                                                       t2PreRating)
        elif row['drawMatch'] == 1:
            t1PostRating, t2PostRating = elo.rate_1vs1(t1PreRating,
                                                       t2PreRating,
                                                       drawn=True)
        elif row['team2WinMatch'] == 1:
            t2PostRating, t1PostRating = elo.rate_1vs1(t2PreRating,
                                                       t1PreRating)

        # Calculate new player rating
        p1PostRating = p1PreRating + (t1PostRating - t1PreRating)
        p2PostRating = p2PreRating + (t1PostRating - t1PreRating)
        p3PostRating = p3PreRating + (t2PostRating - t2PreRating)
        p4PostRating = p4PreRating + (t2PostRating - t2PreRating)

        # Update ratings df
        for name, newRating in [(p1, p1PostRating), (p2, p2PostRating),
                                (p3, p3PostRating), (p4, p4PostRating)]:
            rating.loc[rating['playerName'] == name, 'elo'] = newRating

        return p1PostRating, p2PostRating, p3PostRating, p4PostRating
Пример #23
0
        def _get_elo_graph(gamename):
            #setup plotly
            import random
            import plotly.plotly as py
            import plotly.graph_objs as go
            py.sign_in('slack_gamebot', 'e07cmetnop')

            #get games from ORM
            games = Game.objects.filter(gamename=gamename).order_by('created_on')

            #instantiate rankings object
            rankings = {}
            tracing = {}
            for game in games:
                tracing[game.winner] = begin_elo_at
                tracing[game.loser] = begin_elo_at
                rankings[game.winner] = begin_elo_at
                rankings[game.loser] = begin_elo_at

            x_axis = [game.created_on for game in games] + [ timezone.now() + timezone.timedelta(hours=6) ]

            #setup history object
            rankings_history = rankings.copy()
            for player in rankings_history.keys():
                rankings_history[player] = []

            #build traces
            for game in games:
                new_rankings = rate_1vs1(rankings[game.winner],rankings[game.loser])
                rankings[game.winner] = new_rankings[0]
                rankings[game.loser] = new_rankings[1]
                for player in tracing.keys():
                    rankings_history[player] =  rankings_history[player] + [rankings[player]]

            #add todays ranking
            for player in tracing.keys():
                rankings_history[player] =  rankings_history[player] + [rankings_history[player][-1]]

            traces = []
            # Create traces
            for player in tracing.keys():
                traces = traces + [ go.Scatter(
                    x = x_axis,
                    y = rankings_history[player],
                    mode = 'lines',
                    name = player
                ) ]

            # Plot!
            url = ""
            try:
                url = py.plot(traces, filename='python-datetime',auto_open=False,xTitle='Dates',yTitle='ELO Rankings',title='Leaderboard history for ' + gamename) + ".png?" + str(random.random())
            except Exception:
                pass

            return url
Пример #24
0
    def rate_players(self):
        for p1, p2 in product(self.players, self.players):
            if p1 == p2: continue
            if p1['score'] > p2['score']:
                new_elo_p1, new_elo_p2 = rate_1vs1(p1['program'].elo,
                                                   p2['program'].elo)
            elif p2['score'] > p1['score']:
                new_elo_p2, new_elo_p1 = rate_1vs1(p2['program'].elo,
                                                   p1['program'].elo)
            else:
                new_elo_p1, new_elo_p2 = rate_1vs1(p1['program'].elo,
                                                   p2['program'].elo,
                                                   drawn=True)
            p1['new_elos'].append(new_elo_p1)
            p2['new_elos'].append(new_elo_p2)

        for player in self.players:
            player['program'].elo = sum(player['new_elos']) / len(
                player['new_elos'])
Пример #25
0
def match():
    if request.method == "POST":
        conn = sqlite3.connect('ucenici.db')
        c = conn.cursor()
        lista = get_ucenik()
        win = request.form["nmm1"]
        lose = request.form["nmm2"]
        elo1 = int(get_elo(win))
        elo2 = int(get_elo(lose))
        if request.form["draw"]:
            new_elo1, new_elo2 = rate_1vs1(elo1, elo2, True)
        else:
            new_elo1, new_elo2 = rate_1vs1(elo1, elo2)
        update_elo(win, int(new_elo1))
        update_elo(lose, int(new_elo2))
        lista = get_ucenik()
        return render_template("match.html", ucenik=lista)
    else:
        lista = get_ucenik()
        return render_template("match.html", ucenik=lista)
Пример #26
0
def look_up_elo(result_df, team_name, date_played):
    global elo_df
    if ((elo_df['team_name'] == team_name) &
        (elo_df['date_played'] == date_played)).any():
        elo = elo_df[(elo_df['team_name'] == team_name)
                     & (elo_df['date_played'] == date_played)]['elo'].values[0]
    else:
        last_game = result_df[(result_df['team_name'] == team_name) & (
            result_df['date_played'] < date_played)].sort_values(
                'date_played', ascending=False).head(1)
        if len(last_game) == 0:
            elo = starting_elo
        else:
            pre_game_result_df = result_df[
                result_df['date_played'] < list(last_game['date_played'])[0]]
            g_id = list(last_game['g_id'])[0]
            opponent_team = result_df[(result_df['team_name'] != team_name)
                                      & (result_df['g_id'] == g_id)]

            opponent_team_elo_before_last_game = look_up_elo(
                pre_game_result_df, opponent_team['team_name'].values[0],
                last_game['date_played'].values[0])
            elo_before_previous_game = look_up_elo(
                pre_game_result_df, team_name,
                last_game['date_played'].values[0])
            if last_game['result'].values[0] == 1:
                result = rate_1vs1(elo_before_previous_game,
                                   opponent_team_elo_before_last_game)
                elo = result[0]
            else:
                result = rate_1vs1(opponent_team_elo_before_last_game,
                                   elo_before_previous_game)
                elo = result[1]
        elo_dict = {
            'team_name': team_name,
            'date_played': date_played,
            'elo': elo
        }
        new_elo = pd.DataFrame([elo_dict])
        elo_df = elo_df.append(new_elo)
    return elo
Пример #27
0
def sim(all_games):
    while len(all_games) != 0:
        #Remove one random game
        game = all_games.pop(all_games.index(choice(all_games)))
        
        #Rating Update for winner
        A,B = game[0],game[1]
        rat_a,rat_b = rate_1vs1(A.elo,B.elo)
        if rat_b < 0:
            rat_b = 0
        A.update_elo(rat_a)
        B.update_elo(rat_b)
Пример #28
0
def user_wins(request, id):
    if request.method == 'PUT':
        try:
            user = Profile.objects.get(id=id)
        except Profile.DoesNotExist:
            return HttpResponse(status=404)
        data = json.loads(request.body.decode())
        user.wins = user.wins + data['win']
        user.loses = user.loses + data['lose']
        mypoint = data['mypoint']
        yourpoint = data['yourpoint']
        if (data['win'] == 1):
            user.point = user.point + (rate_1vs1(mypoint, yourpoint)[0] -
                                       mypoint)
        else:
            user.point = user.point + (rate_1vs1(yourpoint, mypoint)[1] -
                                       mypoint)
        user.save()
        return HttpResponse(status=200)
    else:
        return HttpResponseNotAllowed(['PUT'])
Пример #29
0
def sim_time(all_games):
    time_end = time.time() + 2
    while time.time() < time_end:
        #Remove one random game
        game = choice(all_games)
        
        #Rating Update for winner
        A,B = game[0],game[1]
        rat_a,rat_b = rate_1vs1(A.elo,B.elo)
        if rat_b < 0:
            rat_b = 0
        A.update_elo(rat_a)
        B.update_elo(rat_b)
Пример #30
0
def update_ratings(players: Annotated[List[GamePlayer], 2], game: Game):
    # in the form [winner, loser]
    players.sort(key=lambda player: player.score, reverse=True)

    # calculate changes to elos
    stats: Annotated[List[StatsTable],
                     2] = [
                         StatsTable.query.filter_by(
                             player_id=player.player_id,
                             question_type=game.question_type).one_or_none()
                         for player in players
                     ]
    (stats[0].elo, stats[1].elo) = rate_1vs1(stats[0].elo, stats[1].elo)
    db.session.commit()
Пример #31
0
 def elo(self):
     if self.win == 1:
         print 'one'
         print rate_1vs1(self.player, self.word)
         return rate_1vs1(self.player, self.word)
     elif self.win == 0:
         print 'zero'
         print rate_1vs1(self.word, self.player)
         return rate_1vs1(self.word, self.player)
Пример #32
0
def get_entrant_elo_from_event(elo, event_id):
    get_phase_ids = f"""
    query TournamentQuery{{
        event(id: {event_id}){{
            name
            phases{{
                id
                phaseOrder
                phaseGroups{{
                    nodes{{
                        id
                        displayIdentifier
                    }}
                }}
            }}
        }}
    }}
    """
    r = requests.post(
        "https://api.smash.gg/gql/alpha",
        data={
            "query": get_phase_ids,
            "variables": f'{{}}',
        },
        headers={
            'Authorization': f'Bearer {"690ea7f74c5f9b331c7148ba0a7a34e3"}',
        }
    )
    r = r.json()
    phases: list = r['data']['event']['phases']
    phases.sort(key=lambda x: x['phaseOrder'])
    entrant_info = elo
    for phase in phases:
        phase_id = phase['id']
        # Loop over the phases in order, doing all the things
        for phase_group in phase['phaseGroups']['nodes']:
            phase_group_id = phase_group['id']
            sets_to_do_stuff = get_all_sets_to_do_stuff(phase_id, phase_group_id)
            time.sleep(1)
            for sett in sets_to_do_stuff:
                print(f"Processing set {sett}")
                winner, loser = get_set_info(sett)
                if winner not in entrant_info:
                    entrant_info[winner] = 1200
                if loser not in entrant_info:
                    entrant_info[loser] = 1200
                entrant_info[winner], entrant_info[loser] = rate_1vs1(entrant_info[winner], entrant_info[loser])
                time.sleep(0.5)
Пример #33
0
    def save(self, *args, **kwargs):
        self.winner_initial_score = self.winner.score
        self.loser_initial_score = self.loser.score

        winner_new_score, loser_new_score = rate_1vs1(self.winner_initial_score, self.loser_initial_score)
        winner_new_int_score = int(winner_new_score)
        loser_new_int_score = int(loser_new_score)

        self.score_change = winner_new_int_score - self.winner_initial_score
        super(ComparisonItemVote, self).save(*args, **kwargs)

        self.winner.score = winner_new_int_score
        self.winner.save()

        self.loser.score = loser_new_int_score
        self.loser.save()
Пример #34
0
    def show(self):
        for choice in self.choices:
            winner = self.options[choice.winner]
            loser = self.options[choice.loser]
            winner, loser = rate_1vs1(winner, loser)
            self.options[choice.winner] = winner
            self.options[choice.loser] = loser

        sorted_options = sorted(
            self.options.items(), key=operator.itemgetter(1))
        sorted_options.reverse()

        print '\nRankings:'
        rank = 1
        for option, score in sorted_options:
            print "{}. {} (~{})".format(rank, option, int(score))
            rank += 1
        print ''
Пример #35
0
    def update_elos(self, game_id, sender, winner):
        # Only update the elo once. This can be accomplished by only running
        # this function from the command sent by the winner
        # Sender was the winner
        if winner == True:
            winner_elo = self.nicknames_for_clients[sender]['elo']
            both_players = self.clients_by_rooms[game_id].copy()
            both_players.remove(sender)
            loser = both_players[0]
            loser_elo = self.nicknames_for_clients[loser]['elo']
            new_winner_elo, new_loser_elo = rate_1vs1(winner_elo, loser_elo)

            # Set the new elos in the dictionary
            self.nicknames_for_clients[sender]['elo'] = new_winner_elo
            self.nicknames_for_clients[loser]['elo'] = new_loser_elo

            # Update the new elos in firebase
            set_elo(self.firebase_ids_for_clients[sender], new_winner_elo)
            set_elo(self.firebase_ids_for_clients[loser], new_loser_elo)
Пример #36
0
        def _get_elo(gamename):
            #get games from ORM
            games = Game.objects.filter(gamename=gamename).order_by('created_on')

            #instantiate rankings object
            rankings = {}
            for game in games:
                rankings[game.winner] = begin_elo_at
                rankings[game.loser] = begin_elo_at

            #build actual rankings
            for game in games:
                new_rankings = rate_1vs1(rankings[game.winner],rankings[game.loser])
                rankings[game.winner] = new_rankings[0]
                rankings[game.loser] = new_rankings[1]

            for player in rankings:
                rankings[player] = int(round(rankings[player],0))

            return rankings
Пример #37
0
	def update_players(self):

		date_now = timezone.now()
		winnerTrueskillExistingRating = Rating(mu=self.winner.mu, sigma=self.winner.sigma)
		loserTrueskillExistingRating = Rating(mu=self.loser.mu, sigma=self.loser.sigma)

		winnerTrueskillUpdatedRating, loserTrueskillUpdatedRating = rate_1vs1(winnerTrueskillExistingRating, loserTrueskillExistingRating)
		elo_result = elo.rate_1vs1(self.winner.elo, self.loser.elo)

		self.winner.mu = winnerTrueskillUpdatedRating.mu
		self.winner.sigma = winnerTrueskillUpdatedRating.sigma
		self.winner.elo = elo_result[0]
		self.winner.save()

		self.loser.mu = loserTrueskillUpdatedRating.mu
		self.loser.sigma = loserTrueskillUpdatedRating.sigma
		self.loser.elo = elo_result[1]
		self.loser.save()

		return self.winner, self.loser
Пример #38
0
        def _get_elo(gamename):
            #get games from ORM
            games = Game.objects.filter(
                gamename=gamename).order_by('created_on')

            #instantiate rankings object
            rankings = {}
            for game in games:
                rankings[game.winner] = begin_elo_at
                rankings[game.loser] = begin_elo_at

            #build actual rankings
            for game in games:
                new_rankings = rate_1vs1(rankings[game.winner],
                                         rankings[game.loser])
                rankings[game.winner] = new_rankings[0]
                rankings[game.loser] = new_rankings[1]

            for player in rankings:
                rankings[player] = int(round(rankings[player], 0))

            return rankings
Пример #39
0
    def calculate_score_1vs1(self, key1_scored_object, key2_scored_object, winner, other_comparison_pairs):
        """
        Calculates the scores for a new 1vs1 comparison without re-calculating all previous scores
        :param key1_scored_object: Contains score parameters for key1
        :param key2_scored_object: Contains score parameters for key2
        :param winner: indicates the comparison winner
        :param other_comparison_pairs: Contains all previous comparison_pairs that the 2 keys took part in.
            This is a subset of all comparison pairs and is used to calculate round, wins, loses, and opponent counts
        :return: tuple of ScoredObject (key1, key2)
        """
        self.storage = {}
        self.opponents = {}
        elo.setup()

        key1 = key1_scored_object.key
        key2 = key2_scored_object.key

        # Note: if value are None, elo.Rating will use default rating 1400
        r1 = elo.Rating(
            value=key1_scored_object.variable1
        )
        r2 = elo.Rating(
            value=key2_scored_object.variable1
        )

        if winner == ComparisonWinner.key1:
            r1, r2 = elo.rate_1vs1(r1, r2)
        elif winner == ComparisonWinner.key2:
            r2, r1 = elo.rate_1vs1(r2, r1)
        elif winner == ComparisonWinner.draw:
            r1, r2 = elo.rate_1vs1(r1, r2, drawn=True)
        else:
            raise InvalidWinnerException

        for key in [key1, key2]:
            self.opponents[key] = set()
            self.storage[key] = ScoredObject(
                key=key,
                score=r1 if key == key1 else r2,
                variable1=r1 if key == key1 else r2,
                variable2=None,
                rounds=0,
                opponents=0,
                wins=0,
                loses=0
            )

        # calculate opponents, wins, loses, rounds for every match for key1 and key2
        for comparison_pair in (other_comparison_pairs + [ComparisonPair(key1, key2, winner)]):
            cp_key1 = comparison_pair.key1
            cp_key2 = comparison_pair.key2
            cp_winner = comparison_pair.winner
            cp_winner_key1 = cp_winner == ComparisonWinner.key1
            cp_winner_key2 = cp_winner == ComparisonWinner.key2

            if cp_key1 == key1 or cp_key1 == key2:
                if cp_winner is None:
                    self._update_rounds_only(cp_key1)
                else:
                    self._update_result_stats(cp_key1, cp_key2, cp_winner_key1, cp_winner_key2)

            if cp_key2 == key1 or cp_key2 == key2:
                if cp_winner is None:
                    self._update_rounds_only(cp_key2)
                else:
                    self._update_result_stats(cp_key2, cp_key1, cp_winner_key2, cp_winner_key1)

        return (self.storage[key1], self.storage[key2])
Пример #40
0
    def update_company_ladder(self):
        """
        Called when a match is created (or recached) to
        update the ladder and players.
        """

        # create rating objects
        w_rating = elo.Rating(self.winner.rating)
        l_rating = elo.Rating(self.loser.rating)

        # calculate the new ratings based on who won
        w_rating_after, l_rating_after = elo.rate_1vs1(w_rating, l_rating)

        # if neither player has a rank, set both ranks to the best available
        if self.winner.company == self.loser.company:
            if self.winner.rank is None and self.loser.rank is None:
                # get the highest rank number in the company
                highest_rank = \
                        self.winner.company.player_set.order_by('-rank')[0].rank
                if highest_rank is None:
                    highest_rank = 0
                self.winner.rank = highest_rank + 1
                self.loser.rank = self.winner.rank + 1

        # calculate the new ranks based on who won
        w_rank = self.winner.rank or \
                self.winner.company.player_set.count()
        l_rank = self.loser.rank or \
                self.loser.company.player_set.count()

        # if neither player had a rank, put the winner ahead of the loser
        if w_rank == l_rank:
            w_rank -= 1

        if w_rank < l_rank:
            w_rank_after, l_rank_after = w_rank, l_rank
        else:
            w_rank_after, l_rank_after = l_rank, l_rank + 1

        # update the match quality
        self.match_quality = elo.quality_1vs1(w_rating, l_rating)

        # save the player ratings
        self.winner_rating_before = w_rating
        self.winner_rating_after = w_rating_after
        self.loser_rating_before = l_rating
        self.loser_rating_after = l_rating_after

        # save the player ranks
        self.winner_rank_before = w_rank
        self.winner_rank_after = w_rank_after
        self.loser_rank_before = l_rank
        self.loser_rank_after = l_rank_after

        # update the players
        self.winner.add_match(self)
        self.loser.add_match(self)

        # update the company so new ranks can be calculated
        if w_rank != w_rank_after and self.winner.company == self.loser.company:
            self.winner.company.update_player_rank(
                    self.winner, w_rank_after, self)

        # save the match again
        self.save()
Пример #41
0
def post_match(request):
    if request.method == 'POST':

        team_1_json = json.loads(request.POST['team_1'])
        team_2_json = json.loads(request.POST['team_2'])

        # Get team objects, might be a DoublesTeam, might be a Player
        try:
            team_1 = helper_functions.build_team_object(team_1_json)
            team_2 = helper_functions.build_team_object(team_2_json)
        except ValueError as e:
            return HttpResponse(json.dumps({"error": 1, "message": str(e)}), content_type="application/json")

        # Check which team has priority and swap if necessary.
        try:
            if helper_functions.get_team_full_name(team_2) < helper_functions.get_team_full_name(team_1):
                # flip lists of players so that team 1 is alphabetically superior
                team_1, team_2 = team_2, team_1
                # flip scores so that scores align with players
                team_1_json['scores'], team_2_json['scores'] = team_2_json['scores'], team_1_json['scores']
        except ValueError as e:
            return HttpResponse(json.dumps({"error": 2, "message": str(e)}), content_type="application/json")

        team_1_player_list = helper_functions.get_team_player_list(team_1)
        team_2_player_list = helper_functions.get_team_player_list(team_2)

        # IF either team has more than on player, create a DoublesMatch
        if len(team_1_player_list) == 2 or len(team_2_player_list) == 2:
            match = DoublesMatch(
                player_1=(team_1_player_list[0].user.first_name + " " + team_1_player_list[0].user.last_name),
                player_2=(team_2_player_list[0].user.first_name + " " + team_2_player_list[0].user.last_name)
            )

            # Add second player to the team (if it exists).
            if len(team_1_player_list) == 2:
                match.player_3 = team_1_player_list[1].user.first_name + " " + team_1_player_list[1].user.last_name
            if len(team_2_player_list) == 2:
                match.player_4 = team_2_player_list[1].user.first_name + " " + team_2_player_list[1].user.last_name

            # Add team names if they exist
            if team_1.team_name:
                match.team_1_name = team_1.team_name
            if team_2.team_name:
                match.team_2_name = team_2.team_name
        else:
            # Create Match object
            match = Match(
                player_1=(team_1_player_list[0].user.first_name + " " + team_1_player_list[0].user.last_name),
                player_2=(team_2_player_list[0].user.first_name + " " + team_2_player_list[0].user.last_name)
            )

        match.timestamp = time.time()
        match.full_clean()
        match.save()

        game_list = []
        # for each score pair add a game
        for score in team_1_json['scores']:
            # Create game object
            game = MatchGame(
                score_1=score,
                #get index of score in team_1['scores'] and get the team_2['scores'] item at that same index
                score_2=team_2_json['scores'][team_1_json['scores'].index(score)]
            )

            game.full_clean()
            game.save()
            # Add to game list
            game_list.append(game)

            # Grab old list for point change calculations
            old_ratings = (team_1.elo_ranking, team_2.elo_ranking)

            # update ratings, total wins/losses, and calculate point change from game
            if game.score_1 > game.score_2:
                # Calculate new ranking
                new_ratings = rate_1vs1(team_1.elo_ranking, team_2.elo_ranking)
                team_1.elo_ranking = round(new_ratings[0])
                team_2.elo_ranking = round(new_ratings[1])

                #wins/losses for player and match
                match.team_1_wins += 1

                # match point change
                match.team_1_point_change = team_1.elo_ranking - old_ratings[0]
                match.team_2_point_change = team_2.elo_ranking - old_ratings[1]
            else:
                new_ratings = rate_1vs1(team_2.elo_ranking, team_1.elo_ranking)
                team_2.elo_ranking = round(new_ratings[0])
                team_1.elo_ranking = round(new_ratings[1])

                match.team_2_wins += 1
                match.team_1_point_change = team_1.elo_ranking - old_ratings[1]
                match.team_2_point_change = team_2.elo_ranking - old_ratings[0]

        for g in game_list:
            match.games.add(g)

        match.save()

        # Adding a win based on who won the match
        if match.team_1_wins > match.team_2_wins:
            team_1.total_wins += 1
            team_2.total_losses += 1
        else:
            team_2.total_wins += 1
            team_1.total_losses += 1

        # If team is 1 player, only add it to them, otherwise, add to team object
        # TODO: This will fail if one of the teams is a Doubles Team and the other is a Player
        for team in [team_1, team_2]:
            team.matches.add(match)
            team.save()

    return HttpResponse(json.dumps({"error": 0, "message": "OK"}), content_type="application/json")
Пример #42
0
 def draw(self,a,b):
     score_a = self.get_score(a)
     score_b = self.get_score(b)
     final_score_a, final_score_b = elo.rate_1vs1(score_a,score_b,drawn=True)
     self.set_score(a,float(final_score_a))
     self.set_score(b,float(final_score_b))
Пример #43
0
 def fight(self,win,loose):
     score_win = self.get_score(win)
     score_loose = self.get_score(loose)
     score_win_final, score_loose_final = elo.rate_1vs1(score_win,score_loose)
     self.set_score(win,float(score_win_final))
     self.set_score(loose,float(score_loose_final))