コード例 #1
0
def delete_pool():
    tournament = Tournament.get()
    id = request.json["id"]
    tournament.pools.pop(id, None)
    curs = tournament.conn.cursor()
    curs.execute("""DELETE FROM pools WHERE id=%s""", [id])
    return ('', 200)
コード例 #2
0
def add_team():
    tournament = Tournament.get()
    logging.debug(f"Request received on add_team:\n{request}")
    json = request.json

    athletes_temp = json["user"]
    id_athletes_in_team = []
    athlete_in_team = []
    for athlete_dict in athletes_temp:
        if len(athlete_dict["name"]) > 0:
            try:
                weight = float(athlete_dict["weight"])
            except:
                weight = -1
            athlete = Athlete(athlete_dict["belt"], weight,
                              athlete_dict["name"])
            athlete.to_bdd(tournament.conn)
            id_athletes_in_team.append(athlete.id)
            athlete_in_team.append(athlete)
            tournament.add_athlete(athlete)

    if len(athlete_in_team) == 0:
        raise BadRequest
    if len(json["name"]) != 0:
        name = json["name"]
    else:
        name = athletes_temp[0]["name"]

    team = Team(json["origin"], name, id_athletes_in_team, athlete_in_team)
    team.to_bdd(tournament.conn)
    tournament.add_team(team)
    return ('', 200)
コード例 #3
0
def score_team_v_team(pool: Pool, teamA: Team, teamB: Team):
    tournament = Tournament.get()
    id_matches_to_consider_temp = [
        match_id for match_id in teamA.match_list
        if tournament.matches[match_id].isPool
        and tournament.matches[match_id].origin == pool.id
    ]
    id_matches_to_consider = [
        match_id for match_id in id_matches_to_consider_temp
        if tournament.matches[match_id].id_J1 in teamB.athletes_id
        or tournament.matches[match_id].id_J2 in teamB.athletes_id
    ]
    gagne = 0
    for match_id in id_matches_to_consider:
        if tournament.matches[match_id].winner in teamA.athletes_id:
            gagne += 1
        else:
            gagne -= 1

    penalties = 0
    score = 0
    for match_id in id_matches_to_consider:
        match = tournament.matches[match_id]
        if match.id_J1 in teamA.athletes_id:
            score += 10 * (match.score_J1[0] - match.score_J2[0]) + 5 * (
                match.score_J1[1] - match.score_J2[1])
            penalties += match.score_J1[2] - match.score_J2[2]
        else:
            score -= 10 * (match.score_J1[0] - match.score_J2[0]) + 5 * (
                match.score_J1[1] - match.score_J2[1])
            penalties -= match.score_J1[2] - match.score_J2[2]

    return gagne, score, penalties
コード例 #4
0
def add_pool():
    tournament = Tournament.get()
    json = request.json
    teams_id = json["teams"]
    pool = Pool([tournament.teams[id] for id in teams_id], json["name"])
    pool.to_bdd(tournament.conn)
    tournament.pools[pool.id] = pool
    return ('', 200)
コード例 #5
0
def add_bracket():
    tournament = Tournament.get()
    json = request.json
    bracket = Bracket(json["random"], json["teams"], json["name"],
                      json["durations"]["time_match"],
                      json["durations"]["time_wazahari"],
                      json["durations"]["time_ippon"])
    bracket.to_bdd()
    tournament.brackets[bracket.id] = bracket
コード例 #6
0
def name_players():
    global Nombre
    global fenetre
    global Entree
    global Tournoi
    nbrJoueurs=int(Nombre.get())

    Tournoi = Tournament()
    Tournoi.Gtournament_init(nbrJoueurs)

    fenetre.destroy()
    fenetre=Tk()
    fenetre.title('State the name of the ai (simply state h for a human player)')
    for i in range(nbrJoueurs):
        string=list_ai[randint(0,len(list_ai)-1)]
        entree=Entry(fenetre,width=20,font=text_font)
        entree.insert(END,string)
        entree.pack()
        Entree.append(entree)
    bouton = Button(fenetre,text="Valider",font=game_font,command=select_game)
    bouton.pack()
コード例 #7
0
def display_nbrJoueurs(event):
    global Nombre
    global fenetre
    global Tournoi
    Tournoi = Tournament()
    fenetre.destroy()
    fenetre=Tk()
    fenetre.title('Players')

    label=Label(fenetre,text="Number of players:",font=game_font,bg="yellow").pack(padx=10, pady=10)
    Nombre=Spinbox(fenetre, from_=2, to=10,font=text_font)
    Nombre.pack()
    bouton = Button(fenetre,text="Send",font=game_font,command=name_players)
    bouton.pack()
コード例 #8
0
def update_team():
    tournament = Tournament.get()
    json_global = request.json
    json_users = json_global["user"]
    list_users = []
    team = tournament.teams[json_global["id"]]
    curs = tournament.conn.cursor()
    logging.info(json_users)
    for json in json_users:
        id_user = json["id"]

        try:
            name = json["name"]
        except KeyError:
            pass
        try:
            weight = json["weight"]
        except KeyError:
            pass
        try:
            belt = json["belt"]
        except KeyError:
            pass
        if id_user != 0:
            athlete = tournament.athletes[id_user]
            athlete.name = name
            athlete.weight = weight
            athlete.belt = belt
            curs.execute(
                """UPDATE users SET name=%s, belt=%s, weight=%s WHERE id=%s""",
                [athlete.name, athlete.belt, athlete.weight, athlete.id])
        else:
            athlete = Athlete(belt, weight, name)
            athlete.to_bdd(tournament.conn)
        tournament.athletes[athlete.id] = athlete
        list_users.append(athlete.id)

    for user_id in team.athletes_id:
        if user_id not in list_users:
            tournament.athletes.pop(user_id, None)
            curs.execute(f"""DELETE FROM users WHERE id={user_id}""")

    team.athletes_id = list_users
    team.athletes = [tournament.athletes[id] for id in list_users]
    curs.execute("""UPDATE teams SET athletes=%s WHERE id=%s""",
                 [list_users, team.id])
    tournament.conn.commit()
    curs.close()
    return ('', 200)
コード例 #9
0
def get_time_match():
    tournament = Tournament.get()
    json = request.json
    id = json["id"]
    if json["isPool"]:
        result = {
            "time_match": tournament.pools[id].time_match,
            "time_wazahari": tournament.pools[id].time_wazahari,
            "time_ippon": tournament.pools[id].time_ippon
        }
    else:
        result = {
            "time_match": tournament.brackets[id].time_match,
            "time_wazahari": tournament.brackets[id].time_wazahari,
            "time_ippon": tournament.brackets[id].time_ippon
        }
    return jsonify(result)
コード例 #10
0
def get_pool():
    tournament = Tournament.get()
    pool = tournament.pools[request.json["id"]]
    result = pool.to_dict()
    matches = []
    for teamA in pool.teams:
        for teamB in pool.teams:
            if teamA.id != teamB.id:
                gagne, score, penalties = score_function(pool, teamA, teamB)
                victoire = (gagne > 0) - (gagne < 0)
                if victoire == 0:
                    victoire = (score > 0) - (score < 0)
                if victoire == 0:
                    victoire = (penalties < 0) - (penalties > 0)
                logging.info(
                    f"Match entre {teamA.id} et {teamB.id}: {gagne}, {score}, {penalties}, victoire = {victoire}"
                )
                matches.append((teamA.id, teamB.id, victoire))
    result["scores"] = matches
    return jsonify(result)
コード例 #11
0
def get_team_vs():
    tournament = Tournament.get()
    json = request.json
    teamA = tournament.teams[json["team1"]]
    teamB = tournament.teams[json["team2"]]
    if json["isPool"]:
        gagne, score, penalties = score_function(
            tournament.pools[json["groupID"]], teamA, teamB)
    result = {
        "team1": teamA.to_dict(),
        "team2": teamB.to_dict(),
        "winner": gagne,
        "score": score,
        "penalties": penalties
    }
    matches = []
    for match_id in teamA.match_list:
        match = tournament.matches[match_id]
        if match.isPool == json["isPool"]:
            if match.origin == json["groupID"] and match_id in teamB.match_list:
                inverse = (match.id_J1 in teamB.athletes_id)
                matches.append(match.to_dict(inverse))
    result["matches"] = matches
    return jsonify(result)
コード例 #12
0
def get_all_users():
    tournament = Tournament.get()
    list_athletes = [athlete.to_dict() for athlete in tournament.athletes.values()]
    return jsonify(list_athletes)
コード例 #13
0
def get_all_team():
    tournament = Tournament.get()
    list_teams = [team.to_dict() for team in tournament.teams.values()]
    return jsonify(list_teams)
コード例 #14
0
def get_team():
    tournament = Tournament.get()
    json = request.json
    return jsonify(tournament.teams[json["id"]].to_dict())
コード例 #15
0
def get_all_pools():
    tournament = Tournament.get()
    return jsonify([pool.to_dict() for pool in tournament.pools.values()])
コード例 #16
0
def get_user():
    tournament = Tournament.get()
    json = request.json
    return jsonify(tournament.athletes[json["id"]].to_dict())
コード例 #17
0
    app.add_url_rule('/delete_pool',
                     'delete_pool',
                     pool.delete_pool,
                     methods=['POST'])
    app.add_url_rule('/get_all_pools', 'get_all_pools', pool.get_all_pools)
    app.add_url_rule('/get_pool', 'get_pool', pool.get_pool, methods=['POST'])
    app.add_url_rule('/set_score',
                     'set_score',
                     matches.set_score,
                     methods=['POST'])
    app.add_url_rule('/get_team_vs',
                     'get_team_vs',
                     teams.get_team_vs,
                     methods=['POST'])
    app.add_url_rule('/get_time_match',
                     'get_time_match',
                     bracket.get_time_match,
                     methods=['POST'])
    app.add_url_rule('/add_bracket',
                     'add_bracket',
                     bracket.add_bracket,
                     methods=['POST'])
    return app


if __name__ == "__main__":
    tournament = Tournament()
    app = create_server()
    CORS(app)
    app.run(host='0.0.0.0')
コード例 #18
0
"""
To test a trained agent on an environment from the carl/ directory run

python3 -m scripts.run_tournament
"""

import argparse

from src.circuit import Circuit
from src.tournament import TournamentEnvironment, Tournament

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--num_laps', type=int, default=3)
    args = parser.parse_args()

    circuit = Circuit([(0, 0), (0.5, 1), (0, 2), (2, 2), (3, 1), (6, 2),
                       (6, 0)],
                      width=0.3)
    env = TournamentEnvironment(circuit, render=True, laps=args.num_laps)
    tournament = Tournament(env, 10000)
    tournament.run()
    print('\n'.join(map(str, tournament.scores)))
コード例 #19
0
                Result.DRAWN),
        Pairing(players['Alexander Donchenko'], players['Andrey Esipenko'],
                Result.BLACK_WIN),
        Pairing(players['Magnus Carlsen'], players['Maxime-Vachier Lagrave'],
                Result.WHITE_WIN),
        Pairing(players['Jorden van Foreest'], players['Nils Grandelius'],
                Result.WHITE_WIN),
        Pairing(players['Aryan Tari'], players['Fabiano Caruana'],
                Result.DRAWN),
        Pairing(players['Alireza Firouzja'], players['Radoslaw Wojtaszek'],
                Result.DRAWN),
        Pairing(players['Jan-Krzysztof Duda'], players['Pentala Harikrishna'],
                Result.DRAWN)
    ]
    pairings[13] = round13

    return pairings


if __name__ == '__main__':
    name = 'Tata Steel Masters 2021'
    players = get_players()
    rounds = 13
    tiebreaks = ['Direct encounter', 'Sonneborn-Berger', 'Games with Black']
    pairings = get_pairings(players)

    tournament = Tournament(name, players, rounds, tiebreaks, pairings)
    standings = tournament.calculate_standings()
    print('{0}, Standings after round {1}:\n'.format(name, len(pairings)))
    print(standings)