예제 #1
0
def get_highest_goals(against=False, top=5):
    """
    Pass in a boolean to tell the method to calculate goals against instead of
    the default which is goals for.
    @return: a list of dictionaries containing the top however many people with
    the highest goals
    @param against: Pass True if you want this to count goals against
    @param top: Pass in the number of "top" people you want (e.g. Top 5)
    """
    players = PlayerModel.query()

    player_goals = []
    for player in players:
        email = player.key.id()
        matches = MatchModel.query(ndb.OR(MatchModel.player1 == email,
                                      MatchModel.player2 == email))
        goals = 0
        new_player = {
            'email': email,
            'data': 0,
            'full_name': get_player_full_name(email)
        }
        for match in matches:
            if against:
                if match.player1 == email:
                    goals += match.scores[0].player2
                    goals += match.scores[1].player2
                    goals += match.scores[2].player2
                elif match.player2 == email:
                    goals += match.scores[0].player1
                    goals += match.scores[1].player1
                    goals += match.scores[2].player1
            elif not against:
                if match.player1 == email:
                    goals += match.scores[0].player1
                    goals += match.scores[1].player1
                    goals += match.scores[2].player1
                elif match.player2 == email:
                    goals += match.scores[0].player2
                    goals += match.scores[1].player2
                    goals += match.scores[2].player2
        new_player["data"] += goals
        player_goals.append(new_player)

    sorted_players = sorted(player_goals, key=itemgetter('data'))

    if len(sorted_players) < top:
        top = len(sorted_players)

    return sorted_players[len(sorted_players)-top:]
예제 #2
0
def match_history(email):
    """

    """
    qry = MatchModel.query(ndb.OR(MatchModel.player1 == email,
        MatchModel.player2 == email))
    match_results = qry.order(-MatchModel.gameDate).fetch()

    history = []

    count = 0

    for result in match_results:
        count += 1
        wins = 0
        losses = 0
        for i in range(0, len(result.scores)):
            winner = calculate_winner(result.scores[i].player1, result.scores[i].player2)
            if winner == "player1":
                if result.player1 == email:
                    wins += 1
                elif result.player2 == email:
                    losses += 1
            elif winner == "player2":
                if result.player1 == email:
                    losses += 1
                elif result.player2 == email:
                    wins += 1

        if result.player1 == email:
            scores = str(result.scores[0].player1) + "-" + str(result.scores[0].player2) + ", " \
                + str(result.scores[1].player1) + "-" + str(result.scores[1].player2) + ", " \
                + str(result.scores[2].player1) + "-" + str(result.scores[2].player2)
        else:
            scores = str(result.scores[0].player2) + "-" + str(result.scores[0].player1) + ", " \
                + str(result.scores[1].player2) + "-" + str(result.scores[1].player1) + ", " \
                + str(result.scores[2].player2) + "-" + str(result.scores[2].player1)

        if wins > losses:

            history.append([count, str(result.gameDate.strftime('%h %d, %Y @ %I:%S')), \
                True, scores, get_player_full_name(result.player1), \
                get_player_full_name(result.player2)])
        elif losses > wins:
            history.append([count, str(result.gameDate.strftime('%h %d, %Y @ %I:%S')), \
                False, scores, get_player_full_name(result.player1), \
                get_player_full_name(result.player2)])

    return history
예제 #3
0
def calc_player_info(player, key):
    """ Returns information for the player viewing page """
    name = player.first_name
    last = player.last_name
    skill = player.skillScore
    total_wins = player.gamesWon
    games = player.gamesPlayed
    total_losses = games - total_wins
    email = key.pairs()[0][1]
    qry = MatchModel.query(ndb.OR(MatchModel.player1 == email,
                                  MatchModel.player2 == email))
    match_results = qry.order(-MatchModel.gameDate).fetch(5)

    last_five_wins = 0
    last_five_losses = 0

    for result in match_results:
        wins = 0
        losses = 0
        for i in range(0, len(result.scores)):
            winner = calculate_winner(result.scores[i].player1, result.scores[i].player2)
            if winner == "player1":
                if result.player1 == email:
                    wins += 1
                elif result.player2 == email:
                    losses += 1
            elif winner == "player2":
                if result.player1 == email:
                    losses += 1
                elif result.player2 == email:
                    wins += 1
        if wins > losses:
            last_five_wins += 1
        elif losses > wins:
            last_five_losses += 1

    total_games = number_to_word(last_five_wins + last_five_losses)

    last_five_games = {"wins" : last_five_wins,
                       "losses" : last_five_losses,
                       "total" : total_games}

    try:
        win_ratio = round(((total_wins / (games * 1.0)) * 100), 2)
    except ZeroDivisionError:
        win_ratio = 0

    qry = MatchModel.query(ndb.OR(MatchModel.player1 == email,
                                  MatchModel.player2 == email))
    match_results = qry.order(-MatchModel.gameDate).fetch()

    streak_wins = 0
    streak_losses = 0
    first = True
    last_result = "wins"
    final_result = ""
    for result in match_results:
        wins = 0
        losses = 0
        if first:
            for i in range(0, len(result.scores)):
                winner = calculate_winner(result.scores[i].player1, result.scores[i].player2)
                if winner == "player1":
                    if result.player1 == email:
                        wins += 1
                    elif result.player2 == email:
                        losses += 1
                elif winner == "player2":
                    if result.player1 == email:
                        losses += 1
                    elif result.player2 == email:
                        wins += 1
            if wins > losses:
                last_result = "wins"
                streak_wins += 1
            elif losses > wins:
                last_result = "losses"
                streak_losses += 1
            first = False
        else:
            for i in range(0, len(result.scores)):
                winner = calculate_winner(result.scores[i].player1, result.scores[i].player2)
                if winner == "player1":
                    if result.player1 == email:
                        wins += 1
                    elif result.player2 == email:
                        losses += 1
                elif winner == "player2":
                    if result.player1 == email:
                        losses += 1
                    elif result.player2 == email:
                        wins += 1
            if wins > losses:
                if last_result == "wins":
                    streak_wins += 1
                else:
                    final_result = "Currently on a {} game losing streak".format(number_to_word(streak_losses))
                    break
            elif losses > wins:
                if last_result == "losses":
                    streak_losses += 1
                else:
                    final_result = "Currently on a {} game winning streak".format(number_to_word(streak_wins))
                    break
    else:
        if len(match_results) == 0:
            final_result = "Hasn't played any games yet!"

    if final_result == "":
        #Need to calculate it
        if last_result == "wins":
            final_result = "Currently on a {} game winning streak".format(number_to_word(streak_wins))
        elif last_result == "losses":
            final_result = "Currently on a {} game losing streak".format(number_to_word(streak_losses))

    player = {
        "email": email,
        "name": name,
        "last": last,
        "skill": skill,
        "wins": total_wins,
        "losses": total_losses,
        "games": games,
        "win_ratio": win_ratio,
        "last_five_games": last_five_games,
        "streak": final_result
    }

    return player
예제 #4
0
# from models.model_io import ModelInput, ModelOptions, ModelOutput
from utils.flag_parser import parse_arguments
import torch.jit as jit
# embed basemodel.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.net_util import norm_col_init, weights_init
from models import MatchModel

if __name__ == '__main__':

    args = parse_arguments()
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # device = 'cpu'
    model = MatchModel(args).to(device)

    # model_input = ModelInput()
    state = torch.zeros(1, 512, 7, 7).to(device)  # [1,512,7,7]
    hidden = (
        torch.zeros(1, args.hidden_state_sz).to(device),  # [1,512]
        torch.zeros(1, args.hidden_state_sz).to(device),  # [1,512]
    )
    target_class_embedding = torch.zeros(300).to(device)  # [300]
    action_probs = torch.zeros(1, args.action_space).to(
        device)  # [1, #(ACTION_SPACE)]

    # model_opts = ModelOptions()
    # tw.draw_model(model,([1,512,7,7],
    #                [1,args.hidden_state_sz],
    #                [1,args.hidden_state_sz],
예제 #5
0
    def post(self):
        a = MatchModel()
        a.player1 = self.request.POST['player1']
        a.player2 = self.request.POST['player2']

        a.scores = utils.calculate_score_from_post(self.request)

        #TODO: Break rest of the score calculation into utils.py
        players = ndb.get_multi([ndb.Key(PlayerModel, a.player1), ndb.Key(PlayerModel, a.player2)])
        p1_total = [a.scores[0].player1, a.scores[1].player1, a.scores[2].player1]
        p2_total = [a.scores[0].player2, a.scores[1].player2, a.scores[2].player2]

        logging.info("Match between %s %s and %s %s" % (players[0].first_name,
                                                        players[0].last_name,
                                                        players[1].first_name,
                                                        players[1].last_name))

        p1_wins = 0
        p2_wins = 0

        for i in range(0, len(p1_total)):
            logging.info("Game %d: %d - %d" % (i + 1, p1_total[i], p2_total[i]))
            if p1_total[i] > p2_total[i]:
                p1_wins += 1
                logging.info("%s wins Game %d" % (players[0].first_name, i + 1))
            elif p2_total[i] > p1_total[i]:
                p2_wins += 1
                logging.info("%s wins Game %d" % (players[1].first_name, i + 1))

        logging.info("%s won %d games; %s won %d games" % (players[0].first_name,
                                p1_wins, players[1].first_name, p2_wins))

        if p1_wins > p2_wins:
            winner = players[0]
            loser = players[1]
        elif p2_wins > p1_wins:
            winner = players[1]
            loser = players[0]
        else:
            logging.info("No score submitted, loading ladder")
            self.get()
            return

        logging.info("Winner: %s" % winner)
        logging.info("Loser: %s" % loser)

        logging.info("%s %s's old rank was %d" %
                     (winner.first_name, winner.last_name, winner.skillScore))
        logging.info("%s %s's old rank was %d" %
                     (loser.first_name, loser.last_name, loser.skillScore))

        winnerRank, loserRank  = utils.calculate_elo_rank(winner.skillScore,
                                                          loser.skillScore)

        # Try returning the point change for some interesting data
        point_change = int(winnerRank - winner.skillScore)

        logging.info("%s %s's rank is now %d, a change of %d points" %
                     (winner.first_name, winner.last_name, winnerRank,
                      winnerRank - winner.skillScore))
        logging.info("%s %s's rank is now %d, a change of %d points" %
                     (loser.first_name, loser.last_name, loserRank,
                      loser.skillScore - loserRank))

        winner.skillScore = int(winnerRank)
        loser.skillScore = int(loserRank)

        basePoints = int((loser.skillScore - winner.skillScore) * 0.3)
#        #print basePoints
        if basePoints < -100 :
            basePoints = 5
        elif basePoints < -20:
            basePoints = 10 #todo: This is wrong, but better.
        elif basePoints < 20:
            basePoints = 20

        a.baseValue = basePoints
        a.put()

#       Not needed with ELO calculations from utils.py
#        bonusPoints = int((basePoints*point_dff)/10)

#        winner.skillScore = winner.skillScore + basePoints + bonusPoints
#        loser.skillScore = loser.skillScore - basePoints - bonusPoints
        winner.gamesWon += 1
        winner.gamesPlayed += 1
        loser.gamesPlayed += 1

        winner.put()
        loser.put()

        user = users.get_current_user()
        user_email = str(user.email())
        if user_email != str(a.player1):
            opponent_email = str(a.player1)
        else:
            opponent_email = str(a.player2)

        #TODO: Break email dispatch into utils.py
        message = mail.EmailMessage()
        message.sender = user_email
        message.to = opponent_email
        message.subject = "Match Entry - Vendasta Foosball Ladder"
        if winner == players[0]:
            message.html = """
<p>A match was entered between %s (winner) and %s (loser).</p>
<p>The game scores were %d-%d, %d-%d, %d-%d</p>
<p>Check out the ladder by going <a href='http://vendladder.appspot.com'>here</a>.</p>
""" % (winner.first_name + " " + winner.last_name,
       loser.first_name + " " + loser.last_name,
            a.scores[0].player1, a.scores[0].player2,
            a.scores[1].player1, a.scores[1].player2,
            a.scores[2].player1, a.scores[2].player2)
        else:
            message.html = """
<p>A match was entered between %s (winner) and %s (loser).</p>
<p>The game scores were %d-%d, %d-%d, %d-%d</p>
<p>Check out the ladder by going <a href='http://vendladder.appspot.com'>here</a>.</p>
""" % (winner.first_name + " " + winner.last_name,
       loser.first_name + " " + loser.last_name,
           a.scores[0].player2, a.scores[0].player1,
           a.scores[1].player2, a.scores[1].player1,
           a.scores[2].player2, a.scores[2].player1)

        logging.info("Emailing %s from %s" % (user_email, opponent_email))

        message.send()

        self.get(success=True, point_change=point_change)
예제 #6
0
    def post(self):
        template_params = handle_user()
        if not 'admin' in template_params:
            self.redirect('/')
            return
        tournament_url = self.request.get("url")
        # Check for input
        if tournament_url == "":
            self.redirect("/addTournaments")
            return
        dup_check = TournamentModel.query(
            TournamentModel.url == convert_url(tournament_url))
        if dup_check.get() is not None:
            render_template(self, 'error_dup_league.html', template_params)
            return
        api.set_credentials(CHALLONGE_USERNAME, CHALLONGE_API)
        #Handle tournament not found error
        tournament = tournaments.show(tournament_url)
        tournament_object = TournamentModel()
        tournament_object.name = tournament['name']
        tournament_object.url = convert_url(tournament_url)
        timestamp = parser.parse(tournament['created-at'][:-6])
        tournament_object.timestamp = timestamp
        tournament_object.put()

        # Extract the matches
        # Move participant seach to preindex'd list rather than 3 challonge requests
        match_list = matches.index(tournament['id'])
        participant_list = participants.index(tournament['id'])
        self.response.out.write(participant_list)
        for match in match_list:
            match_object = MatchModel(parent=tournament_object.key)
            # Find names via challonge
            #match_object.player1 = participants.show(tournament['id'], match['player1-id'])['name']
            #match_object.player2 = participants.show(tournament['id'], match['player2-id'])['name']
            # Find names via list
            for p in participant_list:
                if p['id'] == match['player1-id']:
                    match_object.player1 = p['name']
                if p['id'] == match['player2-id']:
                    match_object.player2 = p['name']
            if match['scores-csv'] != "":
                parts = match['scores-csv'].split('-')
                match_object.player1Score = int(parts[0])
                match_object.player2Score = int(parts[1])
            winner = participants.show(tournament['id'], match['winner-id'])
            match_object.winner = winner['name']
            match_object.label = match['identifier']
            timestamp = parser.parse(match['started-at'][:-6])
            match_object.timestamp = timestamp
            match_object.put()

        self.redirect("/listTournaments")