Beispiel #1
0
def register_player(contest_id, user_id):
	contest = Contest.objects(id = contest_id)[0]
	player_list = PlayerList.objects(contestId = contest_id)[0]
	user_id_to_substitute = player_list.userIds[contest.currentPlayers]
	player_list.userIds[contest.currentPlayers] = user_id
	player_list.save()
	match_list = get_match_list_by_contest_id(contest_id)
	contest.currentPlayers += 1
	contest.save()
	for i in Match.objects(player1Id = user_id_to_substitute):
		if not i.id in match_list.matches: 
			print "OK!"
			continue
		print "YEAH"
		i.player1Id = user_id
		i.save()

	print "HAHA"
	for i in Match.objects(player2Id = user_id_to_substitute):
		if not i.id in match_list.matches:
			print "OK!"
			continue
		print "YEAH"
		i.player2Id = user_id
		i.save()
	if contest.format == "Single Round-Robin":
		graph1 = get_graph_by_contest_id(contest_id)
		for i in graph1.items:
			if i.playerId == user_id_to_substitute:
				i.playerId = user_id
				break
		graph1.save()
Beispiel #2
0
def validate_game_collection():
    """
    To perform AFTER the method model.service.set_player_codes() is called
    Assert the game setup complies with the following constraints:
        - a team cannot play against itself
        - a team cannot play against another team more one than once
        - a team cannot play a game more than once
        - a team cannot play two matches at the same time
        - a game cannot have the same hash as another game
    """
    duel_set_list = list()
    for time in range(1, len(Match.objects().distinct('time')) + 1):
        player_list = list()
        for m in Match.objects(time=time):
            players = m.players_number
            players_set = {players[0], players[1]}
            assert (players[0] not in player_list
                    ), "Team {} plays two games at time {}".format(
                        players[0], time)
            assert (players[1] not in player_list
                    ), "Team {} plays two games at time {}".format(
                        players[1], time)
            assert (
                players[0] != players[1]
            ), "Player {} plays against itself in game {} at time {}".format(
                players[0], m.game_number, time)
            assert (players_set not in duel_set_list
                    ), "Team {} already played against team {}".format(
                        players[0], players[1])
            player_list.append(players[0])
            player_list.append(players[1])
            duel_set_list.append(players_set)

    hash_list = list()

    for g in Game.objects():
        game_hash = g.hash
        assert game_hash not in hash_list, "Hash {} is used twice".format(
            game_hash)
        hash_list.append(game_hash)

        player_list = list()
        matches = Match.objects(game_number=g.number)
        for m in matches:
            players = m.players_number
            assert (
                players[0]
                not in player_list), "Team {} plays twice the game {}".format(
                    players[0], g.number)
            assert (
                players[1]
                not in player_list), "Team {} plays twice the game {}".format(
                    players[1], g.number)
            player_list.append(players[0])
            player_list.append(players[1])
Beispiel #3
0
def get_score(team_code):
    """
    Get the score of a given team
    :param team_code: a team code
    :return: a tuple (score, victories, evens, defeats)
    """
    evens = Match.objects(players_code=team_code, even=True).count()
    victories = Match.objects(winner=team_code).count()
    defeats = Match.objects(loser=team_code).count()
    score = victories * 2 + evens
    return score, victories, evens, defeats
Beispiel #4
0
 def search(self, password=None, **kwargs):
     login_page = request_login("match", password, 2)
     if login_page:
         return login_page
     page = get_html("search.html")
     warning = ""
     len_kwargs = len([k for k, v in kwargs.items() if v != ""])
     if kwargs:
         if len_kwargs > 1:
             try:
                 time = None
                 game_number = None
                 if kwargs["time"]:
                     time = int(kwargs["time"])
                 if kwargs["game_number"]:
                     game_number = int(kwargs["game_number"])
                 if kwargs["team1_code"] and kwargs["team2_code"]:
                     match = Match.objects(players_code__all=[
                         kwargs["team1_code"], kwargs["team2_code"]
                     ]).get()
                 else:
                     team_code = kwargs.get("team1_code") or kwargs.get(
                         "team2_code") or None
                     if team_code:
                         if time:
                             match = Match.objects(
                                 time=time, players_code=team_code).get()
                         else:
                             match = Match.objects(
                                 game_number=game_number,
                                 players_code=team_code).get()
                     else:
                         match = Match.objects(
                             time=time, game_number=game_number).get()
             except ValueError:
                 warning = "Le numéro doit être un nombre"
                 log.error(
                     "{} tried to search a match with an non-integer value)"
                     .format(str(cherrypy.request.remote.ip)))
             except (DoesNotExist, Exception):
                 warning = "Aucun match ne correspond à la recherche"
                 log.error(
                     "{} tried to search a match but it was not found (time={}, game_number={}, team1_code={}, team2_code={})"
                     .format(str(cherrypy.request.remote.ip),
                             kwargs.get("time", ""),
                             kwargs.get("game_number", ""),
                             kwargs.get("team1_code", ""),
                             kwargs.get("team2_code", "")))
             else:
                 return self.match(mid=match.id)
         else:
             warning = "Minimum 2 champs sont nécessaires pour trouver un match"
     return page.replace("{warning}", warning)
Beispiel #5
0
def get_all_schedules():
    schedules = list()
    highest_time_game_number = Match.objects(
        time=model.match.get_match_quantity()).first().game_number
    for match in Game.objects(number=highest_time_game_number).get().matches:
        schedules.append(match.schedule)
    return schedules
Beispiel #6
0
def get_matches(team_code):
    """
    Get list of matches for a given team
    :param team_code: team code
    :return: Match QuerySet ordered in time
    """
    return Match.objects(players_code=team_code).order_by('time')
Beispiel #7
0
def set_matches():
    modified_teams = list()
    for t in Team.objects():
        for m in Match.objects(players_code=t.code).order_by('time'):
            t.matches.append(m)
        modified_teams.append(t)
    for t in modified_teams:
        t.save()
Beispiel #8
0
def set_player_codes():
    """
    Set players codes in all the Match objects
    """
    for match in Match.objects():
        for number in match.players_number:
            match.players_code.append(Team.objects(number=number).get().code)
        match.save()
Beispiel #9
0
def get_opponent_code(game_number, team_code):
    """
    Get the opponent of a given player at a given game
    :param game_number: the game number
    :param team_code: the player code
    :return: the opponent code
    """
    match = Match.objects(game_number=game_number,
                          players_code=team_code).get()
    for p in match.players_code:
        if p != team_code:
            return p
Beispiel #10
0
def reset_match(game_number, team1_code, team2_code):
    """
    Reset the score of a match
    Assert the match exists.
    :param game_number: a game number
    :param team1_code: a team code
    :param team2_code: another team code
    """
    match = Match.objects(game_number=game_number,
                          players_code__all=[team1_code, team2_code]).get()
    match.winner = ""
    match.loser = ""
    match.even = False
    match.recorded = False
    match.save()
    log.info("Match id {} score has been reset".format(match.id))
Beispiel #11
0
def set_even(game_number, team1_code, team2_code):
    """
    Set a match as equally won.
    Assert the match exists.
    :param game_number: a game number
    :param team1_code: a team code
    :param team2_code: another team code
    """
    match = Match.objects(game_number=game_number,
                          players_code__all=[team1_code, team2_code]).get()
    match.winner = ""
    match.loser = ""
    match.even = True
    match.recorded = True
    match.save()
    log.info("Team {} and team {} are equally placed at the game {}".format(
        team1_code, team2_code, game_number))
Beispiel #12
0
def set_winner(game_number, winner_team_code, loser_team_code):
    """
    Set a team as the winner of a match.
    Assert the match exists.
    :param game_number: a game number
    :param winner_team_code: the winner team code
    :param loser_team_code: the loser team code
    :return: True if the match was updated, False if the match was not found
    """
    if winner_team_code == loser_team_code:
        raise BadenException("Winner and loser team code are identical")
    match = Match.objects(
        game_number=game_number,
        players_code__all=[winner_team_code, loser_team_code]).get()
    match.winner = winner_team_code
    match.loser = loser_team_code
    match.even = False
    match.recorded = True
    match.save()
    log.info("Team {} won the game {} against {}".format(
        winner_team_code, game_number, loser_team_code))
Beispiel #13
0
 def get_game_number(self, team1_code, team2_code):
     if not service.is_team(team1_code):
         log.error(
             "{} unsuccessfully tried to get the game number of team code {} but the opponent team code {} was wrong"
             .format(str(cherrypy.request.remote.ip), team2_code,
                     team1_code))
         return ""
     if not service.is_team(team2_code):
         log.error(
             "{} unsuccessfully tried to get the game number of team code {} but the opponent team code {} was wrong"
             .format(str(cherrypy.request.remote.ip), team1_code,
                     team2_code))
         return ""
     try:
         return str(
             Match.objects(players_code__all=[team1_code, team2_code
                                              ]).get().game_number)
     except DoesNotExist:
         msg = "Les équipes {} et {} ne sont pas censées jouer ensemble".format(
             team1_code, team2_code)
         log.info(msg)
         return "Error: " + msg
Beispiel #14
0
 def match(self, password=None, mid=None, winner=None, **unknown_args):
     login_page = request_login("match", password, 2)
     if login_page:
         return login_page
     page = get_html("match.html")
     notification = ""
     error = ""
     try:
         match = Match.objects(id=mid).get()
         game = Game.objects(number=match.game_number).get()
     except DoesNotExist:
         page = html.show(page, "error-not-found")
         page = html.hide(page, "match-form")
         log.error("{} tried to load a not-existing match (id={})".format(
             str(cherrypy.request.remote.ip), mid))
     except Exception:
         page = html.show(page, "error-not-found")
         page = html.hide(page, "match-form")
         log.exception(
             "{} tried to load a not-existing match (id={})".format(
                 str(cherrypy.request.remote.ip), mid))
     else:
         team1_code = match.players_code[0]
         team2_code = match.players_code[1]
         if winner:
             notification = "Le changement de score a bien été enregistré"
             if winner == "even":
                 service.set_even(game.number, team1_code, team2_code)
             elif winner == team1_code:
                 service.set_winner(game.number, team1_code, team2_code)
             elif winner == team2_code:
                 service.set_winner(game.number, team2_code, team1_code)
             elif winner == "no-scores":
                 service.reset_match(game.number, team1_code, team2_code)
             else:
                 error = "Le changement de score n'a pas pu être enregistré"
                 notification = ""
                 log.error(
                     "{} tried to set an unknown type of winner ({}) at match id {}"
                     .format(str(cherrypy.request.remote.ip), winner, mid))
             match = Match.objects(id=mid).get()
         team1_section = service.get_section(team1_code)
         team2_section = service.get_section(team2_code)
         page = page.replace("{game-number}", str(game.number))
         page = page.replace("{game-name}", game.name)
         page = page.replace("{time}", str(match.time))
         page = page.replace("{schedule}", match.schedule)
         page = page.replace("{team1-code}", team1_code)
         page = page.replace("{team2-code}", team2_code)
         page = page.replace("{team1}",
                             "{} - {}".format(team1_code, team1_section))
         page = page.replace("{team2}",
                             "{} - {}".format(team2_code, team2_section))
         page = page.replace("{mid}", str(match.id))
         if not match.recorded:
             page = page.replace('value="no-scores"',
                                 'value="no-scores" checked')
         elif match.even:
             page = page.replace('value="even"', 'value="even" checked')
         elif match.winner == team1_code:
             page = page.replace('value="{}"'.format(team1_code),
                                 'value="{}" checked'.format(team1_code))
         elif match.winner == team2_code:
             page = page.replace('value="{}"'.format(team2_code),
                                 'value="{}" checked'.format(team2_code))
     page = page.replace('{notification}', notification)
     page = page.replace('{error}', error)
     return page
Beispiel #15
0
    def leader(self,
               password=None,
               team1_code=None,
               team2_code=None,
               game_number=None,
               winner=None,
               confirmed=None,
               **unknown_args):
        login_page = request_login("/leader", password, 0)
        if login_page:
            return login_page

        notification = ""
        warning = ""
        page = get_html("leader.html")
        if not force_qr_scan:
            page = page.replace('input readonly', 'input')
        if team1_code and team2_code and game_number:
            wrong_team1 = False if service.is_team(team1_code) else True
            wrong_team2 = False if service.is_team(team2_code) else True
            wrong_game = False if service.is_game(game_number) else True
            good_values = False if wrong_game or wrong_team1 or wrong_team2 else True
            if winner and team2_code == winner:
                team2_code = team1_code
                team1_code = winner
            if confirmed and good_values:
                cherrypy.session['game_number'] = game_number
                try:
                    if winner == "even":
                        service.set_even(int(game_number), team1_code,
                                         team2_code)
                    else:
                        service.set_winner(int(game_number), team1_code,
                                           team2_code)
                    notification = 'Le score a bien été enregistré'
                except Exception:
                    log.exception(
                        "Something bad occurred while an user tried to set a score"
                    )
                    warning = "Le score n'a pas pu être enregistr&eacute.\n" \
                              "Merci de le signaler à l'administrateur.;"
            else:
                # confirm page
                page = get_html("confirm_score.html")
                page = page.replace('{game_number}', str(game_number))
                page = page.replace('{team1_code}', team1_code)
                page = page.replace('{team2_code}', team2_code)
                if winner == "even":
                    page = page.replace('{team1_title}', "Team 1")
                    page = page.replace('{team2_title}', "Team 2")
                    page = page.replace(
                        '{even-hidden-input}',
                        '<input type="hidden" name="winner" value="even"/>')
                    page = html.show(page, "equally-scored")
                else:
                    page = page.replace('{team1_title}', "Gagnant")
                    page = page.replace('{team2_title}', "Perdant")
                    page = page.replace('{even-hidden-input}', '')
                try:
                    match = Match.objects(game_number=game_number,
                                          players_code=team1_code).get()
                    page = page.replace("{time}", str(match.time))
                    page = page.replace("{schedule}", match.schedule)
                    if match.recorded:
                        page = html.show(page, "previous-score")
                        if match.even:
                            page = html.show(page, "previous-equally-scored")
                            page = page.replace('{previous_team1_title}',
                                                "Team 1")
                            page = page.replace('{previous_team2_title}',
                                                "Team 2")
                            page = page.replace('{previous_team1_code}',
                                                match.players_code[0])
                            page = page.replace('{previous_team2_code}',
                                                match.players_code[1])
                        else:
                            page = page.replace('{previous_team1_title}',
                                                "Gagnant")
                            page = page.replace('{previous_team2_title}',
                                                "Perdant")
                            page = page.replace('{previous_team1_code}',
                                                match.winner)
                            page = page.replace('{previous_team2_code}',
                                                match.loser)
                except Exception:
                    log.exception(
                        "An user tried to encode an non existing combination: game_number={}, team1={}, "
                        "team2={}".format(game_number, team1_code, team2_code))
                    warning = "Cette combinaison n'existe pas"
                    page = html.hide(page, "time-row")
                    page = html.hide(page, "confirm-score")
                    page = html.show(page, "retry-button")
                finally:
                    page = page.replace('{previous_team1_title}', "Team 1")
                    page = page.replace('{previous_team2_title}', "Team 2")
                    page = page.replace('{previous_team1_code}', "")
                    page = page.replace('{previous_team2_code}', "")

        page = page.replace("{game-number}",
                            cherrypy.session.get('game_number', ""))
        page = page.replace('{notification}', notification)
        page = page.replace('{warning}', warning)
        return page
Beispiel #16
0
def get_match_by_id(match_id):
	return Match.objects(id = match_id)[0]
Beispiel #17
0
def test_reset_match(distributed_clean_db):
    service.set_winner(1, "A1", "I3")
    service.set_even(2, "A1", "A4")
    service.set_winner(1, "A2", "A3")
    service.set_winner(2, "A2", "I2")
    service.set_even(2, "A3", "B1")
    service.set_even(3, "A3", "I1")
    assert Match.objects(game_number=1, players_code="A1").get().recorded
    assert Match.objects(game_number=2, players_code="A1").get().recorded
    assert Match.objects(game_number=1, players_code="A2").get().recorded
    assert Match.objects(game_number=2, players_code="A2").get().recorded
    assert Match.objects(game_number=2, players_code="A3").get().recorded
    assert Match.objects(game_number=3, players_code="A3").get().recorded
    service.reset_match(1, "A1", "I3")
    service.reset_match(2, "A1", "A4")
    service.reset_match(1, "A2", "A3")
    service.reset_match(2, "A2", "I2")
    service.reset_match(2, "A3", "B1")
    service.reset_match(3, "A3", "I1")
    assert not Match.objects(game_number=1, players_code="A1").get().recorded
    assert not Match.objects(game_number=2, players_code="A1").get().recorded
    assert not Match.objects(game_number=1, players_code="A2").get().recorded
    assert not Match.objects(game_number=2, players_code="A2").get().recorded
    assert not Match.objects(game_number=2, players_code="A3").get().recorded
    assert not Match.objects(game_number=3, players_code="A3").get().recorded
    assert service.get_score("A1")[0] == 0, "Team A1 should have 0 points"
    assert service.get_score("A1")[1] == 0, "Team A1 should have 0 victory"
    assert service.get_score("A1")[2] == 0, "Team A1 should have 0 even"
    assert service.get_score("A2")[0] == 0, "Team A2 should have 0 points"
    assert service.get_score("A2")[1] == 0, "Team A2 should have 0 victories"
    assert service.get_score("A2")[2] == 0, "Team A2 should have 0 evens"
    assert service.get_score("A3")[0] == 0, "Team A3 should have 0 points"
    assert service.get_score("A3")[1] == 0, "Team A3 should have 0 victories"
    assert service.get_score("A3")[2] == 0, "Team A3 should have 0 evens"
    assert service.get_score("A3")[3] == 0, "Team A3 should have 0 defeat"
    assert service.get_score("A4")[0] == 0, "Team A4 should have 0 points"
    assert service.get_score("A4")[1] == 0, "Team A4 should have 0 victories"
    assert service.get_score("A4")[2] == 0, "Team A4 should have 0 even"